text
stringlengths
3
1.05M
# -*- coding: utf-8 -*- import base64 import cgi import copy import csv import datetime import decimal import os import shutil import sys import types from collections import OrderedDict from ._compat import ( PY2, StringIO, BytesIO, pjoin, exists, hashlib_md5, basestring, iteritems, xrange, implements_iterator, implements_bool, copyreg, reduce, to_bytes, to_native, long ) from ._globals import DEFAULT, IDENTITY, AND, OR from ._gae import Key from .exceptions import NotFoundException, NotAuthorizedException from .helpers.regex import ( REGEX_TABLE_DOT_FIELD, REGEX_ALPHANUMERIC, REGEX_PYTHON_KEYWORDS, REGEX_STORE_PATTERN, REGEX_UPLOAD_PATTERN, REGEX_CLEANUP_FN, REGEX_VALID_TB_FLD, REGEX_TYPE ) from .helpers.classes import ( Reference, MethodAdder, SQLCallableList, SQLALL, Serializable, BasicStorage, SQLCustomType, OpRow, cachedprop ) from .helpers.methods import ( list_represent, bar_decode_integer, bar_decode_string, bar_encode, archive_record, cleanup, use_common_filters, pluralize, attempt_upload_on_insert, attempt_upload_on_update, delete_uploaded_files ) from .helpers.serializers import serializers from .utils import deprecated DEFAULTLENGTH = {'string': 512, 'password': 512, 'upload': 512, 'text': 2**15, 'blob': 2**31} class Row(BasicStorage): """ A dictionary that lets you do d['a'] as well as d.a this is only used to store a `Row` """ def __getitem__(self, k): key = str(k) _extra = super(Row, self).get('_extra', None) if _extra is not None: v = _extra.get(key, DEFAULT) if v != DEFAULT: return v try: return BasicStorage.__getattribute__(self, key) except AttributeError: pass m = REGEX_TABLE_DOT_FIELD.match(key) if m: try: e = super(Row, self).__getitem__(m.group(1)) return e[m.group(2)] except (KeyError, TypeError): pass key = m.group(2) try: return super(Row, self).__getitem__(key) except KeyError: pass try: e = super(Row, self).get('__get_lazy_reference__') if e is not None and callable(e): self[key] = e(key) return self[key] except Exception as e: raise e raise KeyError __str__ = __repr__ = lambda self: '<Row %s>' % \ self.as_dict(custom_types=[LazySet]) __int__ = lambda self: self.get('id') __long__ = lambda self: long(self.get('id')) __call__ = __getitem__ def __getattr__(self, k): try: return self.__getitem__(k) except KeyError: raise AttributeError def __copy__(self): return Row(self) def __eq__(self, other): try: return self.as_dict() == other.as_dict() except AttributeError: return False def get(self, key, default=None): try: return self.__getitem__(key) except(KeyError, AttributeError, TypeError): return default def as_dict(self, datetime_to_str=False, custom_types=None): SERIALIZABLE_TYPES = [str, int, float, bool, list, dict] DT_INST = (datetime.date, datetime.datetime, datetime.time) if PY2: SERIALIZABLE_TYPES += [unicode, long] if isinstance(custom_types, (list, tuple, set)): SERIALIZABLE_TYPES += custom_types elif custom_types: SERIALIZABLE_TYPES.append(custom_types) d = dict(self) for k in list(d.keys()): v = d[k] if d[k] is None: continue elif isinstance(v, Row): d[k] = v.as_dict() elif isinstance(v, Reference): d[k] = long(v) elif isinstance(v, decimal.Decimal): d[k] = float(v) elif isinstance(v, DT_INST): if datetime_to_str: d[k] = v.isoformat().replace('T', ' ')[:19] elif not isinstance(v, tuple(SERIALIZABLE_TYPES)): del d[k] return d def as_xml(self, row_name="row", colnames=None, indent=' '): def f(row, field, indent=' '): if isinstance(row, Row): spc = indent+' \n' items = [f(row[x], x, indent+' ') for x in row] return '%s<%s>\n%s\n%s</%s>' % ( indent, field, spc.join(item for item in items if item), indent, field) elif not callable(row): if REGEX_ALPHANUMERIC.match(field): return '%s<%s>%s</%s>' % (indent, field, row, field) else: return '%s<extra name="%s">%s</extra>' % \ (indent, field, row) else: return None return f(self, row_name, indent=indent) def as_json(self, mode="object", default=None, colnames=None, serialize=True, **kwargs): """ serializes the row to a JSON object kwargs are passed to .as_dict method only "object" mode supported `serialize = False` used by Rows.as_json TODO: return array mode with query column order mode and colnames are not implemented """ item = self.as_dict(**kwargs) if serialize: return serializers.json(item) else: return item def pickle_row(s): return Row, (dict(s), ) copyreg.pickle(Row, pickle_row) class Table(Serializable, BasicStorage): """ Represents a database table Example:: You can create a table as:: db = DAL(...) db.define_table('users', Field('name')) And then:: db.users.insert(name='me') # print db.users._insert(...) to see SQL db.users.drop() """ def __init__(self, db, tablename, *fields, **args): """ Initializes the table and performs checking on the provided fields. Each table will have automatically an 'id'. If a field is of type Table, the fields (excluding 'id') from that table will be used instead. Raises: SyntaxError: when a supplied field is of incorrect type. """ # import DAL here to avoid circular imports from .base import DAL super(Table, self).__init__() self._actual = False # set to True by define_table() self._db = db self._tablename = self._dalname = tablename if not isinstance(tablename, str) or hasattr(DAL, tablename) or not \ REGEX_VALID_TB_FLD.match(tablename) or \ REGEX_PYTHON_KEYWORDS.match(tablename): raise SyntaxError('Field: invalid table name: %s, ' 'use rname for "funny" names' % tablename) self._rname = args.get('rname') or \ db and db._adapter.dialect.quote(tablename) self._raw_rname = args.get('rname') or db and tablename self._sequence_name = args.get('sequence_name') or \ db and db._adapter.dialect.sequence_name(self._raw_rname) self._trigger_name = args.get('trigger_name') or \ db and db._adapter.dialect.trigger_name(tablename) self._common_filter = args.get('common_filter') self._format = args.get('format') self._singular = args.get( 'singular', tablename.replace('_', ' ').capitalize()) self._plural = args.get( 'plural', pluralize(self._singular.lower()).capitalize()) # horrible but for backard compatibility of appamdin: if 'primarykey' in args and args['primarykey'] is not None: self._primarykey = args.get('primarykey') self._before_insert = [attempt_upload_on_insert(self)] self._before_update = [ delete_uploaded_files, attempt_upload_on_update(self)] self._before_delete = [delete_uploaded_files] self._after_insert = [] self._after_update = [] self._after_delete = [] self._virtual_fields = [] self._virtual_methods = [] self.add_method = MethodAdder(self) fieldnames, newfields = set(), [] _primarykey = getattr(self, '_primarykey', None) if _primarykey is not None: if not isinstance(_primarykey, list): raise SyntaxError( "primarykey must be a list of fields from table '%s'" % tablename) if len(_primarykey) == 1: self._id = [ f for f in fields if isinstance(f, Field) and f.name == _primarykey[0]][0] elif not [f for f in fields if (isinstance(f, Field) and f.type == 'id') or (isinstance(f, dict) and f.get("type", None) == "id")]: field = Field('id', 'id') newfields.append(field) fieldnames.add('id') self._id = field virtual_fields = [] def include_new(field): newfields.append(field) fieldnames.add(field.name) if field.type == 'id': self._id = field for field in fields: if isinstance(field, (FieldVirtual, FieldMethod)): virtual_fields.append(field) elif isinstance(field, Field) and field.name not in fieldnames: if field.db is not None: field = copy.copy(field) include_new(field) elif isinstance(field, Table): table = field for field in table: if field.name not in fieldnames and field.type != 'id': t2 = not table._actual and self._tablename include_new(field.clone(point_self_references_to=t2)) elif isinstance(field, dict) and \ field['fieldname'] not in fieldnames: include_new(Field(**field)) elif not isinstance(field, (Field, Table)): raise SyntaxError( 'define_table argument is not a Field or Table: %s' % field ) fields = newfields tablename = tablename self._fields = SQLCallableList() self.virtualfields = [] fields = list(fields) if db and db._adapter.uploads_in_blob is True: uploadfields = [f.name for f in fields if f.type == 'blob'] for field in fields: fn = field.uploadfield if isinstance(field, Field) and field.type == 'upload'\ and fn is True and not field.uploadfs: fn = field.uploadfield = '%s_blob' % field.name if isinstance(fn, str) and fn not in uploadfields and \ not field.uploadfs: fields.append(Field(fn, 'blob', default='', writable=False, readable=False)) fieldnames_set = set() reserved = dir(Table) + ['fields'] if (db and db.check_reserved): check_reserved = db.check_reserved_keyword else: def check_reserved(field_name): if field_name in reserved: raise SyntaxError("field name %s not allowed" % field_name) for field in fields: field_name = field.name check_reserved(field_name) if db and db._ignore_field_case: fname_item = field_name.lower() else: fname_item = field_name if fname_item in fieldnames_set: raise SyntaxError( "duplicate field %s in table %s" % (field_name, tablename)) else: fieldnames_set.add(fname_item) self.fields.append(field_name) self[field_name] = field if field.type == 'id': self['id'] = field field.bind(self) self.ALL = SQLALL(self) if _primarykey is not None: for k in _primarykey: if k not in self.fields: raise SyntaxError( "primarykey must be a list of fields from table '%s " % tablename) else: self[k].notnull = True for field in virtual_fields: self[field.name] = field @property def fields(self): return self._fields @cachedprop def _upload_fieldnames(self): return set(field.name for field in self if field.type == 'upload') def update(self, *args, **kwargs): raise RuntimeError("Syntax Not Supported") def _enable_record_versioning(self, archive_db=None, archive_name='%(tablename)s_archive', is_active='is_active', current_record='current_record', current_record_label=None): db = self._db archive_db = archive_db or db archive_name = archive_name % dict(tablename=self._dalname) if archive_name in archive_db.tables(): return # do not try define the archive if already exists fieldnames = self.fields() same_db = archive_db is db field_type = self if same_db else 'bigint' clones = [] for field in self: nfk = same_db or not field.type.startswith('reference') clones.append( field.clone(unique=False, type=field.type if nfk else 'bigint') ) archive_db.define_table( archive_name, Field(current_record, field_type, label=current_record_label), *clones, **dict(format=self._format)) self._before_update.append( lambda qset, fs, db=archive_db, an=archive_name, cn=current_record: archive_record(qset, fs, db[an], cn)) if is_active and is_active in fieldnames: self._before_delete.append( lambda qset: qset.update(is_active=False)) newquery = lambda query, t=self, name=self._tablename: reduce( AND, [ tab.is_active == True for tab in db._adapter.tables(query).values() if tab._raw_rname == self._raw_rname] ) query = self._common_filter if query: self._common_filter = lambda q: reduce( AND, [query(q), newquery(q)]) else: self._common_filter = newquery def _validate(self, **vars): errors = Row() for key, value in iteritems(vars): value, error = self[key].validate(value) if error: errors[key] = error return errors def _create_references(self): db = self._db pr = db._pending_references self._referenced_by_list = [] self._referenced_by = [] self._references = [] for field in self: # fieldname = field.name #FIXME not used ? field_type = field.type if isinstance(field_type, str) and ( field_type.startswith('reference ') or field_type.startswith('list:reference ')): is_list = field_type[:15] == 'list:reference ' if is_list: ref = field_type[15:].strip() else: ref = field_type[10:].strip() if not ref: SyntaxError('Table: reference to nothing: %s' % ref) if '.' in ref: rtablename, throw_it, rfieldname = ref.partition('.') else: rtablename, rfieldname = ref, None if rtablename not in db: pr[rtablename] = pr.get(rtablename, []) + [field] continue rtable = db[rtablename] if rfieldname: if not hasattr(rtable, '_primarykey'): raise SyntaxError( 'keyed tables can only reference other keyed tables (for now)') if rfieldname not in rtable.fields: raise SyntaxError( "invalid field '%s' for referenced table '%s'" " in table '%s'" % (rfieldname, rtablename, self._tablename) ) rfield = rtable[rfieldname] else: rfield = rtable._id if is_list: rtable._referenced_by_list.append(field) else: rtable._referenced_by.append(field) field.referent = rfield self._references.append(field) else: field.referent = None if self._tablename in pr: referees = pr.pop(self._tablename) for referee in referees: if referee.type.startswith('list:reference '): self._referenced_by_list.append(referee) else: self._referenced_by.append(referee) def _filter_fields(self, record, id=False): return dict([(k, v) for (k, v) in iteritems(record) if k in self.fields and (self[k].type != 'id' or id)]) def _build_query(self, key): """ for keyed table only """ query = None for k, v in iteritems(key): if k in self._primarykey: if query: query = query & (self[k] == v) else: query = (self[k] == v) else: raise SyntaxError( 'Field %s is not part of the primary key of %s' % (k, self._tablename)) return query def __getitem__(self, key): if not key: return None elif isinstance(key, dict): """ for keyed table """ query = self._build_query(key) return self._db(query).select( limitby=(0, 1), orderby_on_limitby=False ).first() else: try: isgoogle = 'google' in self._db._drivers_available and \ isinstance(key, Key) except: isgoogle = False if str(key).isdigit() or isgoogle: return self._db(self._id == key).select( limitby=(0, 1), orderby_on_limitby=False ).first() else: try: return getattr(self, key) except: raise KeyError(key) def __call__(self, key=DEFAULT, **kwargs): for_update = kwargs.get('_for_update', False) if '_for_update' in kwargs: del kwargs['_for_update'] orderby = kwargs.get('_orderby', None) if '_orderby' in kwargs: del kwargs['_orderby'] if key is not DEFAULT: if isinstance(key, Query): record = self._db(key).select( limitby=(0, 1), for_update=for_update, orderby=orderby, orderby_on_limitby=False).first() elif not str(key).isdigit(): record = None else: record = self._db(self._id == key).select( limitby=(0, 1), for_update=for_update, orderby=orderby, orderby_on_limitby=False).first() if record: for k, v in iteritems(kwargs): if record[k] != v: return None return record elif kwargs: query = reduce(lambda a, b: a & b, [ self[k] == v for k, v in iteritems(kwargs)]) return self._db(query).select(limitby=(0, 1), for_update=for_update, orderby=orderby, orderby_on_limitby=False).first() else: return None def __setitem__(self, key, value): if isinstance(key, dict) and isinstance(value, dict): """ option for keyed table """ if set(key.keys()) == set(self._primarykey): value = self._filter_fields(value) kv = {} kv.update(value) kv.update(key) if not self.insert(**kv): query = self._build_query(key) self._db(query).update(**self._filter_fields(value)) else: raise SyntaxError( 'key must have all fields from primary key: %s' % self._primarykey) elif str(key).isdigit(): if key == 0: self.insert(**self._filter_fields(value)) elif self._db(self._id == key)\ .update(**self._filter_fields(value)) is None: raise SyntaxError('No such record: %s' % key) else: if isinstance(key, dict): raise SyntaxError( 'value must be a dictionary: %s' % value) self.__dict__[str(key)] = value if isinstance(value, (FieldVirtual, FieldMethod)): if value.name == 'unknown': value.name = str(key) if isinstance(value, FieldVirtual): self._virtual_fields.append(value) else: self._virtual_methods.append(value) def __setattr__(self, key, value): if key[:1] != '_' and key in self: raise SyntaxError( 'Object exists and cannot be redefined: %s' % key) self[key] = value def __delitem__(self, key): if isinstance(key, dict): query = self._build_query(key) if not self._db(query).delete(): raise SyntaxError('No such record: %s' % key) elif not str(key).isdigit() or \ not self._db(self._id == key).delete(): raise SyntaxError('No such record: %s' % key) def __iter__(self): for fieldname in self.fields: yield self[fieldname] def __repr__(self): return '<Table %s (%s)>' % (self._tablename, ', '.join(self.fields())) def __str__(self): if self._tablename == self._dalname: return self._tablename return self._db._adapter.dialect._as(self._dalname, self._tablename) @property @deprecated('sqlsafe', 'sql_shortref', 'Table') def sqlsafe(self): return self.sql_shortref @property @deprecated('sqlsafe_alias', 'sql_fullref', 'Table') def sqlsafe_alias(self): return self.sql_fullref @property def sql_shortref(self): if self._tablename == self._dalname: return self._rname return self._db._adapter.sqlsafe_table(self._tablename) @property def sql_fullref(self): if self._tablename == self._dalname: return self._rname return self._db._adapter.sqlsafe_table(self._tablename, self._rname) def query_name(self, *args, **kwargs): return (self.sql_fullref,) def _drop(self, mode=''): return self._db._adapter.dialect.drop_table(self, mode) def drop(self, mode=''): return self._db._adapter.drop_table(self, mode) def _filter_fields_for_operation(self, fields): new_fields = {} # format: new_fields[name] = (field, value) input_fieldnames = set(fields) table_fieldnames = set(self.fields) empty_fieldnames = OrderedDict((name, name) for name in self.fields) for name in list(input_fieldnames & table_fieldnames): field = self[name] value = field.filter_in(fields[name]) \ if field.filter_in else fields[name] new_fields[name] = (field, value) del empty_fieldnames[name] return list(empty_fieldnames), new_fields def _compute_fields_for_operation(self, fields, to_compute): row = OpRow(self) for name, tup in iteritems(fields): field, value = tup if isinstance( value, ( types.LambdaType, types.FunctionType, types.MethodType, types.BuiltinFunctionType, types.BuiltinMethodType ) ): value = value() row.set_value(name, value, field) for name, field in to_compute: try: row.set_value(name, field.compute(row), field) except (KeyError, AttributeError): # error silently unless field is required! if field.required and name not in fields: raise RuntimeError( 'unable to compute required field: %s' % name) return row def _fields_and_values_for_insert(self, fields): empty_fieldnames, new_fields = \ self._filter_fields_for_operation(fields) to_compute = [] for name in empty_fieldnames: field = self[name] if field.compute: to_compute.append((name, field)) elif field.default is not None: new_fields[name] = (field, field.default) elif field.required: raise RuntimeError( 'Table: missing required field: %s' % name) return self._compute_fields_for_operation( new_fields, to_compute) def _fields_and_values_for_update(self, fields): empty_fieldnames, new_fields = \ self._filter_fields_for_operation(fields) to_compute = [] for name in empty_fieldnames: field = self[name] if field.compute: to_compute.append((name, field)) if field.update is not None: new_fields[name] = (field, field.update) return self._compute_fields_for_operation( new_fields, to_compute) def _insert(self, **fields): row = self._fields_and_values_for_insert(fields) return self._db._adapter._insert(self, row.op_values()) def insert(self, **fields): row = self._fields_and_values_for_insert(fields) if any(f(row) for f in self._before_insert): return 0 ret = self._db._adapter.insert(self, row.op_values()) if ret and self._after_insert: for f in self._after_insert: f(row, ret) return ret def _validate_fields(self, fields, defattr='default'): response = Row() response.id, response.errors = None, Row() new_fields = copy.copy(fields) for fieldname in self.fields: default = getattr(self[fieldname], defattr) if callable(default): default = default() raw_value = fields.get(fieldname, default) value, error = self[fieldname].validate(raw_value) if error: response.errors[fieldname] = "%s" % error elif value is not None: new_fields[fieldname] = value return response, new_fields def validate_and_insert(self, **fields): response, new_fields = self._validate_fields(fields) if not response.errors: response.id = self.insert(**new_fields) return response def validate_and_update(self, _key=DEFAULT, **fields): response, new_fields = self._validate_fields(fields, 'update') #: select record(s) for update if _key is DEFAULT: record = self(**fields) elif isinstance(_key, dict): record = self(**_key) else: record = self(_key) #: do the update if not response.errors and record: if '_id' in self: myset = self._db(self._id == record[self._id.name]) else: query = None for key, value in iteritems(_key): if query is None: query = getattr(self, key) == value else: query = query & (getattr(self, key) == value) myset = self._db(query) response.id = myset.update(**new_fields) return response def update_or_insert(self, _key=DEFAULT, **values): if _key is DEFAULT: record = self(**values) elif isinstance(_key, dict): record = self(**_key) else: record = self(_key) if record: record.update_record(**values) newid = None else: newid = self.insert(**values) return newid def validate_and_update_or_insert(self, _key=DEFAULT, **fields): if _key is DEFAULT or _key == '': primary_keys = {} for key, value in iteritems(fields): if key in self._primarykey: primary_keys[key] = value if primary_keys != {}: record = self(**primary_keys) _key = primary_keys else: required_keys = {} for key, value in iteritems(fields): if getattr(self, key).required: required_keys[key] = value record = self(**required_keys) _key = required_keys elif isinstance(_key, dict): record = self(**_key) else: record = self(_key) if record: response = self.validate_and_update(_key, **fields) if hasattr(self, '_primarykey'): primary_keys = {} for key in self._primarykey: primary_keys[key] = getattr(record, key) response.id = primary_keys else: response = self.validate_and_insert(**fields) return response def bulk_insert(self, items): """ here items is a list of dictionaries """ data = [self._fields_and_values_for_insert(item) for item in items] if any(f(el) for el in data for f in self._before_insert): return 0 ret = self._db._adapter.bulk_insert( self, [el.op_values() for el in data]) ret and [ [f(el, ret[k]) for k, el in enumerate(data)] for f in self._after_insert] return ret def _truncate(self, mode=''): return self._db._adapter.dialect.truncate(self, mode) def truncate(self, mode=''): return self._db._adapter.truncate(self, mode) def import_from_csv_file(self, csvfile, id_map = None, null = '<NULL>', unique = 'uuid', id_offset = None, # id_offset used only when id_map is None transform = None, *args, **kwargs ): """ Import records from csv file. Column headers must have same names as table fields. Field 'id' is ignored. If column names read 'table.file' the 'table.' prefix is ignored. - 'unique' argument is a field which must be unique (typically a uuid field) - 'restore' argument is default False; if set True will remove old values in table first. - 'id_map' if set to None will not map ids The import will keep the id numbers in the restored table. This assumes that there is an field of type id that is integer and in incrementing order. Will keep the id numbers in restored table. """ delimiter = kwargs.get('delimiter', ',') quotechar = kwargs.get('quotechar', '"') quoting = kwargs.get('quoting', csv.QUOTE_MINIMAL) restore = kwargs.get('restore', False) if restore: self._db[self].truncate() reader = csv.reader(csvfile, delimiter=delimiter, quotechar=quotechar, quoting=quoting) colnames = None if isinstance(id_map, dict): if self._tablename not in id_map: id_map[self._tablename] = {} id_map_self = id_map[self._tablename] def fix(field, value, id_map, id_offset): list_reference_s = 'list:reference' if value == null: value = None elif field.type == 'blob': value = base64.b64decode(value) elif field.type == 'double' or field.type == 'float': if not value.strip(): value = None else: value = float(value) elif field.type in ('integer', 'bigint'): if not value.strip(): value = None else: value = long(value) elif field.type.startswith('list:string'): value = bar_decode_string(value) elif field.type.startswith(list_reference_s): ref_table = field.type[len(list_reference_s):].strip() if id_map is not None: value = [id_map[ref_table][long(v)] for v in bar_decode_string(value)] else: value = [v for v in bar_decode_string(value)] elif field.type.startswith('list:'): value = bar_decode_integer(value) elif id_map and field.type.startswith('reference'): try: value = id_map[field.type[9:].strip()][long(value)] except KeyError: pass elif id_offset and field.type.startswith('reference'): try: value = id_offset[field.type[9:].strip()]+long(value) except KeyError: pass return value def is_id(colname): if colname in self: return self[colname].type == 'id' else: return False first = True unique_idx = None for lineno, line in enumerate(reader): if not line: return if not colnames: # assume this is the first line of the input, contains colnames colnames = [x.split('.', 1)[-1] for x in line][:len(line)] cols, cid = {}, None for i, colname in enumerate(colnames): if is_id(colname): cid = colname elif colname in self.fields: cols[colname] = self[colname] if colname == unique: unique_idx = i elif len(line)==len(colnames): # every other line contains instead data items = dict(zip(colnames, line)) if transform: items = transform(items) ditems = dict() csv_id = None for field in self: fieldname = field.name if fieldname in items: try: value = fix(field, items[fieldname], id_map, id_offset) if field.type!='id': ditems[fieldname] = value else: csv_id = long(value) except ValueError: raise RuntimeError("Unable to parse line:%s" % (lineno+1)) if not (id_map or csv_id is None or id_offset is None or unique_idx): curr_id = self.insert(**ditems) if first: first = False # First curr_id is bigger than csv_id, # then we are not restoring but # extending db table with csv db table id_offset[self._tablename] = (curr_id-csv_id) \ if curr_id > csv_id else 0 # create new id until we get the same as old_id+offset while curr_id < csv_id+id_offset[self._tablename]: self._db(self[cid] == curr_id).delete() curr_id = self.insert(**ditems) # Validation. Check for duplicate of 'unique' &, # if present, update instead of insert. elif not unique_idx: new_id = self.insert(**ditems) else: unique_value = line[unique_idx] query = self[unique] == unique_value record = self._db(query).select().first() if record: record.update_record(**ditems) new_id = record[self._id.name] else: new_id = self.insert(**ditems) if id_map and csv_id is not None: id_map_self[csv_id] = new_id if lineno % 1000 == 999: self._db.commit() def as_dict(self, flat=False, sanitize=True): table_as_dict = dict( tablename=str(self), fields=[], sequence_name=self._sequence_name, trigger_name=self._trigger_name, common_filter=self._common_filter, format=self._format, singular=self._singular, plural=self._plural) for field in self: if (field.readable or field.writable) or (not sanitize): table_as_dict["fields"].append(field.as_dict( flat=flat, sanitize=sanitize)) return table_as_dict def with_alias(self, alias): other = copy.copy(self) other['ALL'] = SQLALL(other) other['_tablename'] = alias for fieldname in other.fields: tmp = self[fieldname].clone() tmp.bind(other) other[fieldname] = tmp if 'id' in self and 'id' not in other.fields: other['id'] = other[self.id.name] other._id = other[self._id.name] self._db[alias] = other return other def on(self, query): return Expression(self._db, self._db._adapter.dialect.on, self, query) def create_index(self, name, *fields, **kwargs): return self._db._adapter.create_index(self, name, *fields, **kwargs) def drop_index(self, name): return self._db._adapter.drop_index(self, name) class Select(BasicStorage): def __init__(self, db, query, fields, attributes): self._db = db self._tablename = None # alias will be stored here self._rname = self._raw_rname = self._dalname = None self._common_filter = None self._query = query # if false, the subquery will never reference tables from parent scope self._correlated = attributes.pop('correlated', True) self._attributes = attributes self._qfields = list(fields) self._fields = SQLCallableList() self._virtual_fields = [] self._virtual_methods = [] self.virtualfields = [] self._sql_cache = None self._colnames_cache = None fieldcheck = set() for item in fields: if isinstance(item, Field): checkname = item.name field = item.clone() elif isinstance(item, Expression): if item.op != item._dialect._as: continue checkname = item.second field = Field(item.second, type=item.type) else: raise SyntaxError('Invalid field in Select') if db and db._ignore_field_case: checkname = checkname.lower() if checkname in fieldcheck: raise SyntaxError("duplicate field %s in select query" % field.name) fieldcheck.add(checkname) field.bind(self) self.fields.append(field.name) self[field.name] = field self.ALL = SQLALL(self) @property def fields(self): return self._fields def update(self, *args, **kwargs): raise RuntimeError("update() method not supported") def __getitem__(self, key): try: return getattr(self, key) except AttributeError: raise KeyError(key) def __setitem__(self, key, value): self.__dict__[str(key)] = value def __call__(self): adapter = self._db._adapter colnames, sql = self._compile() cache = self._attributes.get('cache', None) if cache and self._attributes.get('cacheable', False): return adapter._cached_select(cache, sql, self._fields, self._attributes, colnames) return adapter._select_aux(sql, self._qfields, self._attributes, colnames) def __setattr__(self, key, value): if key[:1] != '_' and key in self: raise SyntaxError( 'Object exists and cannot be redefined: %s' % key) self[key] = value def __iter__(self): for fieldname in self.fields: yield self[fieldname] def __repr__(self): return '<Select (%s)>' % ', '.join(map(str, self._qfields)) def __str__(self): return self._compile(with_alias=(self._tablename is not None))[1] def with_alias(self, alias): other = copy.copy(self) other['ALL'] = SQLALL(other) other['_tablename'] = alias for fieldname in other.fields: tmp = self[fieldname].clone() tmp.bind(other) other[fieldname] = tmp return other def on(self, query): if not self._tablename: raise SyntaxError("Subselect must be aliased for use in a JOIN") return Expression(self._db, self._db._adapter.dialect.on, self, query) def _compile(self, outer_scoped=[], with_alias=False): if not self._correlated: outer_scoped = [] if outer_scoped or not self._sql_cache: adapter = self._db._adapter attributes = self._attributes.copy() attributes['outer_scoped'] = outer_scoped colnames, sql = adapter._select_wcols(self._query, self._qfields, **attributes) # Do not cache when the query may depend on external tables if not outer_scoped: self._colnames_cache, self._sql_cache = colnames, sql else: colnames, sql = self._colnames_cache, self._sql_cache if with_alias and self._tablename is not None: sql = '(%s)' % sql[:-1] sql = self._db._adapter.dialect.alias(sql, self._tablename) return colnames, sql def query_name(self, outer_scoped=[]): if self._tablename is None: raise SyntaxError("Subselect must be aliased for use in a JOIN") colnames, sql = self._compile(outer_scoped, True) # This method should also return list of placeholder values # in the future return (sql,) @property def sql_shortref(self): if self._tablename is None: raise SyntaxError("Subselect must be aliased for use in a JOIN") return self._db._adapter.dialect.quote(self._tablename) def _filter_fields(self, record, id=False): return dict([(k, v) for (k, v) in iteritems(record) if k in self.fields and (self[k].type != 'id' or id)]) def _expression_wrap(wrapper): def wrap(self, *args, **kwargs): return wrapper(self, *args, **kwargs) return wrap class Expression(object): _dialect_expressions_ = {} def __new__(cls, *args, **kwargs): for name, wrapper in iteritems(cls._dialect_expressions_): setattr(cls, name, _expression_wrap(wrapper)) new_cls = super(Expression, cls).__new__(cls) return new_cls def __init__(self, db, op, first=None, second=None, type=None, **optional_args): self.db = db self.op = op self.first = first self.second = second self._table = getattr(first, '_table', None) if not type and first and hasattr(first, 'type'): self.type = first.type else: self.type = type if isinstance(self.type, str): self._itype = REGEX_TYPE.match(self.type).group(0) else: self._itype = None self.optional_args = optional_args @property def _dialect(self): return self.db._adapter.dialect def sum(self): return Expression( self.db, self._dialect.aggregate, self, 'SUM', self.type) def max(self): return Expression( self.db, self._dialect.aggregate, self, 'MAX', self.type) def min(self): return Expression( self.db, self._dialect.aggregate, self, 'MIN', self.type) def len(self): return Expression( self.db, self._dialect.length, self, None, 'integer') def avg(self): return Expression( self.db, self._dialect.aggregate, self, 'AVG', self.type) def abs(self): return Expression( self.db, self._dialect.aggregate, self, 'ABS', self.type) def lower(self): return Expression( self.db, self._dialect.lower, self, None, self.type) def upper(self): return Expression( self.db, self._dialect.upper, self, None, self.type) def replace(self, a, b): return Expression( self.db, self._dialect.replace, self, (a, b), self.type) def year(self): return Expression( self.db, self._dialect.extract, self, 'year', 'integer') def month(self): return Expression( self.db, self._dialect.extract, self, 'month', 'integer') def day(self): return Expression( self.db, self._dialect.extract, self, 'day', 'integer') def hour(self): return Expression( self.db, self._dialect.extract, self, 'hour', 'integer') def minutes(self): return Expression( self.db, self._dialect.extract, self, 'minute', 'integer') def coalesce(self, *others): return Expression( self.db, self._dialect.coalesce, self, others, self.type) def coalesce_zero(self): return Expression( self.db, self._dialect.coalesce_zero, self, None, self.type) def seconds(self): return Expression( self.db, self._dialect.extract, self, 'second', 'integer') def epoch(self): return Expression( self.db, self._dialect.epoch, self, None, 'integer') def __getitem__(self, i): if isinstance(i, slice): start = i.start or 0 stop = i.stop db = self.db if start < 0: pos0 = '(%s - %d)' % (self.len(), abs(start) - 1) else: pos0 = start + 1 maxint = sys.maxint if PY2 else sys.maxsize if stop is None or stop == maxint: length = self.len() elif stop < 0: length = '(%s - %d - %s)' % (self.len(), abs(stop) - 1, pos0) else: length = '(%s - %s)' % (stop + 1, pos0) return Expression(db, self._dialect.substring, self, (pos0, length), self.type) else: return self[i:i + 1] def __str__(self): return str(self.db._adapter.expand(self, self.type)) def __or__(self, other): # for use in sortby return Expression(self.db, self._dialect.comma, self, other, self.type) def __invert__(self): if hasattr(self, '_op') and self.op == self._dialect.invert: return self.first return Expression(self.db, self._dialect.invert, self, type=self.type) def __add__(self, other): return Expression(self.db, self._dialect.add, self, other, self.type) def __sub__(self, other): if self.type in ('integer', 'bigint'): result_type = 'integer' elif self.type in ['date', 'time', 'datetime', 'double', 'float']: result_type = 'double' elif self.type.startswith('decimal('): result_type = self.type else: raise SyntaxError("subtraction operation not supported for type") return Expression(self.db, self._dialect.sub, self, other, result_type) def __mul__(self, other): return Expression(self.db, self._dialect.mul, self, other, self.type) def __div__(self, other): return Expression(self.db, self._dialect.div, self, other, self.type) def __truediv__(self, other): return self.__div__(other) def __mod__(self, other): return Expression(self.db, self._dialect.mod, self, other, self.type) def __eq__(self, value): return Query(self.db, self._dialect.eq, self, value) def __ne__(self, value): return Query(self.db, self._dialect.ne, self, value) def __lt__(self, value): return Query(self.db, self._dialect.lt, self, value) def __le__(self, value): return Query(self.db, self._dialect.lte, self, value) def __gt__(self, value): return Query(self.db, self._dialect.gt, self, value) def __ge__(self, value): return Query(self.db, self._dialect.gte, self, value) def like(self, value, case_sensitive=True, escape=None): op = case_sensitive and self._dialect.like or self._dialect.ilike return Query(self.db, op, self, value, escape=escape) def ilike(self, value, escape=None): return self.like(value, case_sensitive=False, escape=escape) def regexp(self, value): return Query(self.db, self._dialect.regexp, self, value) def belongs(self, *value, **kwattr): """ Accepts the following inputs:: field.belongs(1, 2) field.belongs((1, 2)) field.belongs(query) Does NOT accept: field.belongs(1) If the set you want back includes `None` values, you can do:: field.belongs((1, None), null=True) """ db = self.db if len(value) == 1: value = value[0] if isinstance(value, Query): value = db(value)._select(value.first._table._id) elif not isinstance(value, (Select, basestring)): value = set(value) if kwattr.get('null') and None in value: value.remove(None) return (self == None) | Query( self.db, self._dialect.belongs, self, value) return Query(self.db, self._dialect.belongs, self, value) def startswith(self, value): if self.type not in ('string', 'text', 'json', 'jsonb', 'upload'): raise SyntaxError("startswith used with incompatible field type") return Query(self.db, self._dialect.startswith, self, value) def endswith(self, value): if self.type not in ('string', 'text', 'json', 'jsonb', 'upload'): raise SyntaxError("endswith used with incompatible field type") return Query(self.db, self._dialect.endswith, self, value) def contains(self, value, all=False, case_sensitive=False): """ For GAE contains() is always case sensitive """ if isinstance(value, (list, tuple)): subqueries = [self.contains(str(v), case_sensitive=case_sensitive) for v in value if str(v)] if not subqueries: return self.contains('') else: return reduce(all and AND or OR, subqueries) if self.type not in ('string', 'text', 'json', 'jsonb', 'upload') and not \ self.type.startswith('list:'): raise SyntaxError("contains used with incompatible field type") return Query( self.db, self._dialect.contains, self, value, case_sensitive=case_sensitive) def with_alias(self, alias): return Expression(self.db, self._dialect._as, self, alias, self.type) # GIS expressions def st_asgeojson(self, precision=15, options=0, version=1): return Expression(self.db, self.db._adapter.ST_ASGEOJSON, self, dict(precision=precision, options=options, version=version), 'string') def st_astext(self): return Expression( self.db, self._dialect.st_astext, self, type='string') def st_x(self): return Expression(self.db, self._dialect.st_x, self, type='string') def st_y(self): return Expression(self.db, self._dialect.st_y, self, type='string') def st_distance(self, other): return Expression( self.db, self._dialect.st_distance, self, other, 'double') def st_simplify(self, value): return Expression( self.db, self._dialect.st_simplify, self, value, self.type) def st_simplifypreservetopology(self, value): return Expression( self.db, self._dialect.st_simplifypreservetopology, self, value, self.type) # GIS queries def st_contains(self, value): return Query(self.db, self._dialect.st_contains, self, value) def st_equals(self, value): return Query(self.db, self._dialect.st_equals, self, value) def st_intersects(self, value): return Query(self.db, self._dialect.st_intersects, self, value) def st_overlaps(self, value): return Query(self.db, self._dialect.st_overlaps, self, value) def st_touches(self, value): return Query(self.db, self._dialect.st_touches, self, value) def st_within(self, value): return Query(self.db, self._dialect.st_within, self, value) def st_dwithin(self, value, distance): return Query( self.db, self._dialect.st_dwithin, self, (value, distance)) class FieldVirtual(object): def __init__(self, name, f=None, ftype='string', label=None, table_name=None): # for backward compatibility (self.name, self.f) = (name, f) if f else ('unknown', name) self.type = ftype self.label = label or self.name.capitalize().replace('_', ' ') self.represent = lambda v, r=None: v self.formatter = IDENTITY self.comment = None self.readable = True self.writable = False self.requires = None self.widget = None self.tablename = table_name self.filter_out = None def __str__(self): return '%s.%s' % (self.tablename, self.name) class FieldMethod(object): def __init__(self, name, f=None, handler=None): # for backward compatibility (self.name, self.f) = (name, f) if f else ('unknown', name) self.handler = handler or VirtualCommand @implements_bool class Field(Expression, Serializable): Virtual = FieldVirtual Method = FieldMethod Lazy = FieldMethod # for backward compatibility """ Represents a database field Example: Usage:: a = Field(name, 'string', length=32, default=None, required=False, requires=IS_NOT_EMPTY(), ondelete='CASCADE', notnull=False, unique=False, uploadfield=True, widget=None, label=None, comment=None, uploadfield=True, # True means store on disk, # 'a_field_name' means store in this field in db # False means file content will be discarded. writable=True, readable=True, update=None, authorize=None, autodelete=False, represent=None, uploadfolder=None, uploadseparate=False # upload to separate directories by uuid_keys # first 2 character and tablename.fieldname # False - old behavior # True - put uploaded file in # <uploaddir>/<tablename>.<fieldname>/uuid_key[:2] # directory) uploadfs=None # a pyfilesystem where to store upload ) to be used as argument of `DAL.define_table` """ def __init__(self, fieldname, type='string', length=None, default=DEFAULT, required=False, requires=DEFAULT, ondelete='CASCADE', notnull=False, unique=False, uploadfield=True, widget=None, label=None, comment=None, writable=True, readable=True, update=None, authorize=None, autodelete=False, represent=None, uploadfolder=None, uploadseparate=False, uploadfs=None, compute=None, custom_store=None, custom_retrieve=None, custom_retrieve_file_properties=None, custom_delete=None, filter_in=None, filter_out=None, custom_qualifier=None, map_none=None, rname=None): self._db = self.db = None # both for backward compatibility self.table = self._table = None self.op = None self.first = None self.second = None if PY2 and isinstance(fieldname, unicode): try: fieldname = str(fieldname) except UnicodeEncodeError: raise SyntaxError('Field: invalid unicode field name') self.name = fieldname = cleanup(fieldname) if (not isinstance(fieldname, str) or hasattr(Table, fieldname) or not REGEX_VALID_TB_FLD.match(fieldname) or REGEX_PYTHON_KEYWORDS.match(fieldname)): raise SyntaxError('Field: invalid field name: %s, ' 'use rname for "funny" names' % fieldname) if not isinstance(type, (Table, Field)): self.type = type else: self.type = 'reference %s' % type self.length = length if length is not None else \ DEFAULTLENGTH.get(self.type, 512) self.default = default if default != DEFAULT else (update or None) self.required = required # is this field required self.ondelete = ondelete.upper() # this is for reference fields only self.notnull = notnull self.unique = unique self.uploadfield = uploadfield self.uploadfolder = uploadfolder self.uploadseparate = uploadseparate self.uploadfs = uploadfs self.widget = widget self.comment = comment self.writable = writable self.readable = readable self.update = update self.authorize = authorize self.autodelete = autodelete self.represent = list_represent if represent is None and \ type in ('list:integer', 'list:string') else represent self.compute = compute self.isattachment = True self.custom_store = custom_store self.custom_retrieve = custom_retrieve self.custom_retrieve_file_properties = custom_retrieve_file_properties self.custom_delete = custom_delete self.filter_in = filter_in self.filter_out = filter_out self.custom_qualifier = custom_qualifier self.label = (label if label is not None else fieldname.replace('_', ' ').title()) self.requires = requires if requires is not None else [] self.map_none = map_none self._rname = self._raw_rname = rname stype = self.type if isinstance(self.type, SQLCustomType): stype = self.type.type self._itype = REGEX_TYPE.match(stype).group(0) if stype else None def bind(self, table): if self._table is not None: raise ValueError( 'Field %s is already bound to a table' % self.longname) self.db = self._db = table._db self.table = self._table = table self.tablename = self._tablename = table._tablename if self._db and self._rname is None: self._rname = self._db._adapter.sqlsafe_field(self.name) self._raw_rname = self.name def set_attributes(self, *args, **attributes): self.__dict__.update(*args, **attributes) return self def clone(self, point_self_references_to=False, **args): field = copy.copy(self) if point_self_references_to and \ self.type == 'reference %s' % self._tablename: field.type = 'reference %s' % point_self_references_to field.__dict__.update(args) field.db = field._db = None field.table = field._table = None field.tablename = field._tablename = None if self._db and \ self._rname == self._db._adapter.sqlsafe_field(self.name): # Reset the name because it may need to be requoted by bind() field._rname = field._raw_rname = None return field def store(self, file, filename=None, path=None): # make sure filename is a str sequence filename = "{}".format(filename) if self.custom_store: return self.custom_store(file, filename, path) if isinstance(file, cgi.FieldStorage): filename = filename or file.filename file = file.file elif not filename: filename = file.name filename = os.path.basename( filename.replace('/', os.sep).replace('\\', os.sep)) m = REGEX_STORE_PATTERN.search(filename) extension = m and m.group('e') or 'txt' uuid_key = self._db.uuid().replace('-', '')[-16:] encoded_filename = to_native( base64.b16encode(to_bytes(filename)).lower()) newfilename = '%s.%s.%s.%s' % ( self._tablename, self.name, uuid_key, encoded_filename) newfilename = newfilename[:(self.length - 1 - len(extension))] + \ '.' + extension self_uploadfield = self.uploadfield if isinstance(self_uploadfield, Field): blob_uploadfield_name = self_uploadfield.uploadfield keys = {self_uploadfield.name: newfilename, blob_uploadfield_name: file.read()} self_uploadfield.table.insert(**keys) elif self_uploadfield is True: if self.uploadfs: dest_file = self.uploadfs.open(newfilename, 'wb') else: if path: pass elif self.uploadfolder: path = self.uploadfolder elif self.db._adapter.folder: path = pjoin(self.db._adapter.folder, '..', 'uploads') else: raise RuntimeError( "you must specify a Field(..., uploadfolder=...)") if self.uploadseparate: if self.uploadfs: raise RuntimeError("not supported") path = pjoin(path, "%s.%s" % ( self._tablename, self.name), uuid_key[:2] ) if not exists(path): os.makedirs(path) pathfilename = pjoin(path, newfilename) dest_file = open(pathfilename, 'wb') try: shutil.copyfileobj(file, dest_file) except IOError: raise IOError( 'Unable to store file "%s" because invalid permissions, ' 'readonly file system, or filename too long' % pathfilename) dest_file.close() return newfilename def retrieve(self, name, path=None, nameonly=False): """ If `nameonly==True` return (filename, fullfilename) instead of (filename, stream) """ self_uploadfield = self.uploadfield if self.custom_retrieve: return self.custom_retrieve(name, path) if self.authorize or isinstance(self_uploadfield, str): row = self.db(self == name).select().first() if not row: raise NotFoundException if self.authorize and not self.authorize(row): raise NotAuthorizedException file_properties = self.retrieve_file_properties(name, path) filename = file_properties['filename'] if isinstance(self_uploadfield, str): # ## if file is in DB stream = BytesIO(to_bytes(row[self_uploadfield] or '')) elif isinstance(self_uploadfield, Field): blob_uploadfield_name = self_uploadfield.uploadfield query = self_uploadfield == name data = self_uploadfield.table(query)[blob_uploadfield_name] stream = BytesIO(to_bytes(data)) elif self.uploadfs: # ## if file is on pyfilesystem stream = self.uploadfs.open(name, 'rb') else: # ## if file is on regular filesystem # this is intentially a sting with filename and not a stream # this propagates and allows stream_file_or_304_or_206 to be called fullname = pjoin(file_properties['path'], name) if nameonly: return (filename, fullname) stream = open(fullname, 'rb') return (filename, stream) def retrieve_file_properties(self, name, path=None): m = REGEX_UPLOAD_PATTERN.match(name) if not m or not self.isattachment: raise TypeError('Can\'t retrieve %s file properties' % name) self_uploadfield = self.uploadfield if self.custom_retrieve_file_properties: return self.custom_retrieve_file_properties(name, path) if m.group('name'): try: filename = base64.b16decode(m.group('name'), True).decode('utf-8') filename = REGEX_CLEANUP_FN.sub('_', filename) except (TypeError, AttributeError): filename = name else: filename = name # ## if file is in DB if isinstance(self_uploadfield, (str, Field)): return dict(path=None, filename=filename) # ## if file is on filesystem if not path: if self.uploadfolder: path = self.uploadfolder else: path = pjoin(self.db._adapter.folder, '..', 'uploads') if self.uploadseparate: t = m.group('table') f = m.group('field') u = m.group('uuidkey') path = pjoin(path, "%s.%s" % (t, f), u[:2]) return dict(path=path, filename=filename) def formatter(self, value): requires = self.requires if value is None: return self.map_none if not requires: return value if not isinstance(requires, (list, tuple)): requires = [requires] elif isinstance(requires, tuple): requires = list(requires) else: requires = copy.copy(requires) requires.reverse() for item in requires: if hasattr(item, 'formatter'): value = item.formatter(value) return value def validate(self, value): if not self.requires or self.requires == DEFAULT: return ((value if value != self.map_none else None), None) requires = self.requires if not isinstance(requires, (list, tuple)): requires = [requires] for validator in requires: (value, error) = validator(value) if error: return (value, error) return ((value if value != self.map_none else None), None) def count(self, distinct=None): return Expression( self.db, self._dialect.count, self, distinct, 'integer') def as_dict(self, flat=False, sanitize=True): attrs = ( 'name', 'authorize', 'represent', 'ondelete', 'custom_store', 'autodelete', 'custom_retrieve', 'filter_out', 'uploadseparate', 'widget', 'uploadfs', 'update', 'custom_delete', 'uploadfield', 'uploadfolder', 'custom_qualifier', 'unique', 'writable', 'compute', 'map_none', 'default', 'type', 'required', 'readable', 'requires', 'comment', 'label', 'length', 'notnull', 'custom_retrieve_file_properties', 'filter_in') serializable = (int, long, basestring, float, tuple, bool, type(None)) def flatten(obj): if isinstance(obj, dict): return dict((flatten(k), flatten(v)) for k, v in obj.items()) elif isinstance(obj, (tuple, list, set)): return [flatten(v) for v in obj] elif isinstance(obj, serializable): return obj elif isinstance(obj, (datetime.datetime, datetime.date, datetime.time)): return str(obj) else: return None d = dict() if not (sanitize and not (self.readable or self.writable)): for attr in attrs: if flat: d.update({attr: flatten(getattr(self, attr))}) else: d.update({attr: getattr(self, attr)}) d["fieldname"] = d.pop("name") return d def __bool__(self): return True def __str__(self): if self._table: return '%s.%s' % (self.tablename, self.name) return '<no table>.%s' % self.name def __hash__(self): return id(self) @property def sqlsafe(self): if self._table is None: raise SyntaxError('Field %s is not bound to any table' % self.name) return self._table.sql_shortref + '.' + self._rname @property @deprecated('sqlsafe_name', '_rname', 'Field') def sqlsafe_name(self): return self._rname @property def longname(self): if self._table is None: raise SyntaxError('Field %s is not bound to any table' % self.name) return self._table._tablename + '.' + self.name class Query(Serializable): """ Necessary to define a set. It can be stored or can be passed to `DAL.__call__()` to obtain a `Set` Example: Use as:: query = db.users.name=='Max' set = db(query) records = set.select() """ def __init__(self, db, op, first=None, second=None, ignore_common_filters=False, **optional_args ): self.db = self._db = db self.op = op self.first = first self.second = second self.ignore_common_filters = ignore_common_filters self.optional_args = optional_args @property def _dialect(self): return self.db._adapter.dialect def __repr__(self): return '<Query %s>' % str(self) def __str__(self): return str(self.db._adapter.expand(self)) def __and__(self, other): return Query(self.db, self._dialect._and, self, other) __rand__ = __and__ def __or__(self, other): return Query(self.db, self._dialect._or, self, other) __ror__ = __or__ def __invert__(self): if self.op == self._dialect._not: return self.first return Query(self.db, self._dialect._not, self) def __eq__(self, other): return repr(self) == repr(other) def __ne__(self, other): return not (self == other) def case(self, t=1, f=0): return Expression(self.db, self._dialect.case, self, (t, f)) def as_dict(self, flat=False, sanitize=True): """Experimental stuff This allows to return a plain dictionary with the basic query representation. Can be used with json/xml services for client-side db I/O Example: Usage:: q = db.auth_user.id != 0 q.as_dict(flat=True) { "op": "NE", "first":{ "tablename": "auth_user", "fieldname": "id" }, "second":0 } """ SERIALIZABLE_TYPES = (tuple, dict, set, list, int, long, float, basestring, type(None), bool) def loop(d): newd = dict() for k, v in d.items(): if k in ("first", "second"): if isinstance(v, self.__class__): newd[k] = loop(v.__dict__) elif isinstance(v, Field): newd[k] = {"tablename": v._tablename, "fieldname": v.name} elif isinstance(v, Expression): newd[k] = loop(v.__dict__) elif isinstance(v, SERIALIZABLE_TYPES): newd[k] = v elif isinstance(v, (datetime.date, datetime.time, datetime.datetime)): newd[k] = unicode(v) if PY2 else str(v) elif k == "op": if callable(v): newd[k] = v.__name__ elif isinstance(v, basestring): newd[k] = v else: pass # not callable or string elif isinstance(v, SERIALIZABLE_TYPES): if isinstance(v, dict): newd[k] = loop(v) else: newd[k] = v return newd if flat: return loop(self.__dict__) else: return self.__dict__ class Set(Serializable): """ Represents a set of records in the database. Records are identified by the `query=Query(...)` object. Normally the Set is generated by `DAL.__call__(Query(...))` Given a set, for example:: myset = db(db.users.name=='Max') you can:: myset.update(db.users.name='Massimo') myset.delete() # all elements in the set myset.select(orderby=db.users.id, groupby=db.users.name, limitby=(0, 10)) and take subsets: subset = myset(db.users.id<5) """ def __init__(self, db, query, ignore_common_filters=None): self.db = db self._db = db # for backward compatibility self.dquery = None # if query is a dict, parse it if isinstance(query, dict): query = self.parse(query) if ignore_common_filters is not None and \ use_common_filters(query) == ignore_common_filters: query = copy.copy(query) query.ignore_common_filters = ignore_common_filters self.query = query def __repr__(self): return '<Set %s>' % str(self.query) def __call__(self, query, ignore_common_filters=False): return self.where(query, ignore_common_filters) def where(self, query, ignore_common_filters=False): if query is None: return self elif isinstance(query, Table): query = self.db._adapter.id_query(query) elif isinstance(query, str): query = Expression(self.db, query) elif isinstance(query, Field): query = query != None if self.query: return Set(self.db, self.query & query, ignore_common_filters=ignore_common_filters) else: return Set(self.db, query, ignore_common_filters=ignore_common_filters) def _count(self, distinct=None): return self.db._adapter._count(self.query, distinct) def _select(self, *fields, **attributes): adapter = self.db._adapter tablenames = adapter.tables(self.query, attributes.get('join', None), attributes.get('left', None), attributes.get('orderby', None), attributes.get('groupby', None)) fields = adapter.expand_all(fields, tablenames) return adapter._select(self.query, fields, attributes) def _delete(self): db = self.db table = db._adapter.get_table(self.query) return db._adapter._delete(table, self.query) def _update(self, **update_fields): db = self.db table = db._adapter.get_table(self.query) row = table._fields_and_values_for_update(update_fields) return db._adapter._update(table, self.query, row.op_values()) def as_dict(self, flat=False, sanitize=True): if flat: uid = dbname = uri = None codec = self.db._db_codec if not sanitize: uri, dbname, uid = (self.db._dbname, str(self.db), self.db._db_uid) d = {"query": self.query.as_dict(flat=flat)} d["db"] = {"uid": uid, "codec": codec, "name": dbname, "uri": uri} return d else: return self.__dict__ def parse(self, dquery): """Experimental: Turn a dictionary into a Query object""" self.dquery = dquery return self.build(self.dquery) def build(self, d): """Experimental: see .parse()""" op, first, second = (d["op"], d["first"], d.get("second", None)) left = right = built = None if op in ("AND", "OR"): if not (type(first), type(second)) == (dict, dict): raise SyntaxError("Invalid AND/OR query") if op == "AND": built = self.build(first) & self.build(second) else: built = self.build(first) | self.build(second) elif op == "NOT": if first is None: raise SyntaxError("Invalid NOT query") built = ~self.build(first) else: # normal operation (GT, EQ, LT, ...) for k, v in {"left": first, "right": second}.items(): if isinstance(v, dict) and v.get("op"): v = self.build(v) if isinstance(v, dict) and ("tablename" in v): v = self.db[v["tablename"]][v["fieldname"]] if k == "left": left = v else: right = v if hasattr(self.db._adapter, op): opm = getattr(self.db._adapter, op) if op == "EQ": built = left == right elif op == "NE": built = left != right elif op == "GT": built = left > right elif op == "GE": built = left >= right elif op == "LT": built = left < right elif op == "LE": built = left <= right elif op in ("JOIN", "LEFT_JOIN", "RANDOM", "ALLOW_NULL"): built = Expression(self.db, opm) elif op in ("LOWER", "UPPER", "EPOCH", "PRIMARY_KEY", "COALESCE_ZERO", "RAW", "INVERT"): built = Expression(self.db, opm, left) elif op in ("COUNT", "EXTRACT", "AGGREGATE", "SUBSTRING", "REGEXP", "LIKE", "ILIKE", "STARTSWITH", "ENDSWITH", "ADD", "SUB", "MUL", "DIV", "MOD", "AS", "ON", "COMMA", "NOT_NULL", "COALESCE", "CONTAINS", "BELONGS"): built = Expression(self.db, opm, left, right) # expression as string elif not (left or right): built = Expression(self.db, op) else: raise SyntaxError("Operator not supported: %s" % op) return built def isempty(self): return not self.select(limitby=(0, 1), orderby_on_limitby=False) def count(self, distinct=None, cache=None): db = self.db if cache: sql = self._count(distinct=distinct) if isinstance(cache, dict): cache_model = cache['model'] time_expire = cache['expiration'] key = cache.get('key') if not key: key = db._uri + '/' + sql key = hashlib_md5(key).hexdigest() else: cache_model, time_expire = cache key = db._uri + '/' + sql key = hashlib_md5(key).hexdigest() return cache_model( key, lambda self=self, distinct=distinct: db._adapter.count( self.query, distinct), time_expire) return db._adapter.count(self.query, distinct) def select(self, *fields, **attributes): adapter = self.db._adapter tablenames = adapter.tables(self.query, attributes.get('join', None), attributes.get('left', None), attributes.get('orderby', None), attributes.get('groupby', None)) fields = adapter.expand_all(fields, tablenames) return adapter.select(self.query, fields, attributes) def iterselect(self, *fields, **attributes): adapter = self.db._adapter tablenames = adapter.tables(self.query, attributes.get('join', None), attributes.get('left', None), attributes.get('orderby', None), attributes.get('groupby', None)) fields = adapter.expand_all(fields, tablenames) return adapter.iterselect(self.query, fields, attributes) def nested_select(self, *fields, **attributes): adapter = self.db._adapter tablenames = adapter.tables(self.query, attributes.get('join', None), attributes.get('left', None), attributes.get('orderby', None), attributes.get('groupby', None)) fields = adapter.expand_all(fields, tablenames) return adapter.nested_select(self.query, fields, attributes) def delete(self): db = self.db table = db._adapter.get_table(self.query) if any(f(self) for f in table._before_delete): return 0 ret = db._adapter.delete(table, self.query) ret and [f(self) for f in table._after_delete] return ret def update(self, **update_fields): db = self.db table = db._adapter.get_table(self.query) row = table._fields_and_values_for_update(update_fields) if not row._values: raise ValueError("No fields to update") if any(f(self, row) for f in table._before_update): return 0 ret = db._adapter.update(table, self.query, row.op_values()) ret and [f(self, row) for f in table._after_update] return ret def update_naive(self, **update_fields): """ Same as update but does not call table._before_update and _after_update """ table = self.db._adapter.get_table(self.query) row = table._fields_and_values_for_update(update_fields) if not row._values: raise ValueError("No fields to update") ret = self.db._adapter.update(table, self.query, row.op_values()) return ret def validate_and_update(self, **update_fields): table = self.db._adapter.get_table(self.query) response = Row() response.errors = Row() new_fields = copy.copy(update_fields) for key, value in iteritems(update_fields): value, error = table[key].validate(value) if error: response.errors[key] = '%s' % error else: new_fields[key] = value if response.errors: response.updated = None else: row = table._fields_and_values_for_update(new_fields) if not row._values: raise ValueError("No fields to update") if any(f(self, row) for f in table._before_update): ret = 0 else: ret = self.db._adapter.update( table, self.query, row.op_values()) ret and [f(self, row) for f in table._after_update] response.updated = ret return response class LazyReferenceGetter(object): def __init__(self, table, id): self.db, self.tablename, self.id = table._db, table._tablename, id def __call__(self, other_tablename): if self.db._lazy_tables is False: raise AttributeError() table = self.db[self.tablename] other_table = self.db[other_tablename] for rfield in table._referenced_by: if rfield.table == other_table: return LazySet(rfield, self.id) raise AttributeError() class LazySet(object): def __init__(self, field, id): self.db, self.tablename, self.fieldname, self.id = \ field.db, field._tablename, field.name, id def _getset(self): query = self.db[self.tablename][self.fieldname] == self.id return Set(self.db, query) def __repr__(self): return repr(self._getset()) def __call__(self, query, ignore_common_filters=False): return self.where(query, ignore_common_filters) def where(self, query, ignore_common_filters=False): return self._getset()(query, ignore_common_filters) def _count(self, distinct=None): return self._getset()._count(distinct) def _select(self, *fields, **attributes): return self._getset()._select(*fields, **attributes) def _delete(self): return self._getset()._delete() def _update(self, **update_fields): return self._getset()._update(**update_fields) def isempty(self): return self._getset().isempty() def count(self, distinct=None, cache=None): return self._getset().count(distinct, cache) def select(self, *fields, **attributes): return self._getset().select(*fields, **attributes) def nested_select(self, *fields, **attributes): return self._getset().nested_select(*fields, **attributes) def delete(self): return self._getset().delete() def update(self, **update_fields): return self._getset().update(**update_fields) def update_naive(self, **update_fields): return self._getset().update_naive(**update_fields) def validate_and_update(self, **update_fields): return self._getset().validate_and_update(**update_fields) class VirtualCommand(object): def __init__(self, method, row): self.method = method self.row = row def __call__(self, *args, **kwargs): return self.method(self.row, *args, **kwargs) @implements_bool class BasicRows(object): """ Abstract class for Rows and IterRows """ def __bool__(self): return True if self.first() is not None else False def __str__(self): """ Serializes the table into a csv file """ s = StringIO() self.export_to_csv_file(s) return s.getvalue() def as_trees(self, parent_name='parent_id', children_name='children', render=False): """ returns the data as list of trees. :param parent_name: the name of the field holding the reference to the parent (default parent_id). :param children_name: the name where the children of each row will be stored as a list (default children). :param render: whether we will render the fields using their represent (default False) can be a list of fields to render or True to render all. """ roots = [] drows = {} rows = list(self.render(fields=None if render is True else render)) \ if render else self for row in rows: drows[row.id] = row row[children_name] = [] for row in rows: parent = row[parent_name] if parent is None: roots.append(row) else: drows[parent][children_name].append(row) return roots def as_list(self, compact=True, storage_to_dict=True, datetime_to_str=False, custom_types=None): """ Returns the data as a list or dictionary. Args: storage_to_dict: when True returns a dict, otherwise a list datetime_to_str: convert datetime fields as strings """ (oc, self.compact) = (self.compact, compact) if storage_to_dict: items = [item.as_dict(datetime_to_str, custom_types) for item in self] else: items = [item for item in self] self.compact = oc return items def as_dict(self, key='id', compact=True, storage_to_dict=True, datetime_to_str=False, custom_types=None): """ Returns the data as a dictionary of dictionaries (storage_to_dict=True) or records (False) Args: key: the name of the field to be used as dict key, normally the id compact: ? (default True) storage_to_dict: when True returns a dict, otherwise a list(default True) datetime_to_str: convert datetime fields as strings (default False) """ # test for multiple rows multi = False f = self.first() if f and isinstance(key, basestring): multi = any([isinstance(v, f.__class__) for v in f.values()]) if ("." not in key) and multi: # No key provided, default to int indices def new_key(): i = 0 while True: yield i i += 1 key_generator = new_key() key = lambda r: key_generator.next() rows = self.as_list(compact, storage_to_dict, datetime_to_str, custom_types) if isinstance(key, str) and key.count('.') == 1: (table, field) = key.split('.') return dict([(r[table][field], r) for r in rows]) elif isinstance(key, str): return dict([(r[key], r) for r in rows]) else: return dict([(key(r), r) for r in rows]) def xml(self, strict=False, row_name='row', rows_name='rows'): """ Serializes the table using sqlhtml.SQLTABLE (if present) """ if not strict and not self.db.has_representer('rows_xml'): strict = True if strict: return '<%s>\n%s\n</%s>' % ( rows_name, '\n'.join( row.as_xml( row_name=row_name, colnames=self.colnames ) for row in self), rows_name ) rv = self.db.represent('rows_xml', self) if hasattr(rv, 'xml') and callable(getattr(rv, 'xml')): return rv.xml() return rv def as_xml(self, row_name='row', rows_name='rows'): return self.xml(strict=True, row_name=row_name, rows_name=rows_name) def as_json(self, mode='object', default=None): """ Serializes the rows to a JSON list or object with objects mode='object' is not implemented (should return a nested object structure) """ items = [record.as_json( mode=mode, default=default, serialize=False, colnames=self.colnames ) for record in self] return serializers.json(items) def export_to_csv_file(self, ofile, null='<NULL>', *args, **kwargs): """ Exports data to csv, the first line contains the column names Args: ofile: where the csv must be exported to null: how null values must be represented (default '<NULL>') delimiter: delimiter to separate values (default ',') quotechar: character to use to quote string values (default '"') quoting: quote system, use csv.QUOTE_*** (default csv.QUOTE_MINIMAL) represent: use the fields .represent value (default False) colnames: list of column names to use (default self.colnames) This will only work when exporting rows objects!!!! DO NOT use this with db.export_to_csv() """ delimiter = kwargs.get('delimiter', ',') quotechar = kwargs.get('quotechar', '"') quoting = kwargs.get('quoting', csv.QUOTE_MINIMAL) represent = kwargs.get('represent', False) writer = csv.writer(ofile, delimiter=delimiter, quotechar=quotechar, quoting=quoting) def unquote_colnames(colnames): unq_colnames = [] for col in colnames: m = self.db._adapter.REGEX_TABLE_DOT_FIELD.match(col) if not m: unq_colnames.append(col) else: unq_colnames.append('.'.join(m.groups())) return unq_colnames colnames = kwargs.get('colnames', self.colnames) write_colnames = kwargs.get('write_colnames', True) # a proper csv starting with the column names if write_colnames: writer.writerow(unquote_colnames(colnames)) def none_exception(value): """ Returns a cleaned up value that can be used for csv export: - unicode text is encoded as such - None values are replaced with the given representation (default <NULL>) """ if value is None: return null elif PY2 and isinstance(value, unicode): return value.encode('utf8') elif isinstance(value, Reference): return long(value) elif hasattr(value, 'isoformat'): return value.isoformat()[:19].replace('T', ' ') elif isinstance(value, (list, tuple)): # for type='list:..' return bar_encode(value) return value repr_cache = {} fieldlist = [f if isinstance(f, Field) else None for f in self.fields] fieldmap = dict(zip(self.colnames, fieldlist)) for record in self: row = [] for col in colnames: field = fieldmap[col] if field is None: row.append(record._extra[col]) else: t, f = field._tablename, field.name if isinstance(record.get(t, None), (Row, dict)): value = record[t][f] else: value = record[f] if field.type == 'blob' and value is not None: value = base64.b64encode(value) elif represent and field.represent: if field.type.startswith('reference'): if field not in repr_cache: repr_cache[field] = {} if value not in repr_cache[field]: repr_cache[field][value] = field.represent( value, record ) value = repr_cache[field][value] else: value = field.represent(value, record) row.append(none_exception(value)) writer.writerow(row) # for consistent naming yet backwards compatible as_csv = __str__ json = as_json class Rows(BasicRows): """ A wrapper for the return value of a select. It basically represents a table. It has an iterator and each row is represented as a `Row` dictionary. """ # ## TODO: this class still needs some work to care for ID/OID def __init__(self, db=None, records=[], colnames=[], compact=True, rawrows=None, fields=[]): self.db = db self.records = records self.fields = fields self.colnames = colnames self.compact = compact self.response = rawrows def __repr__(self): return '<Rows (%s)>' % len(self.records) def setvirtualfields(self, **keyed_virtualfields): """ For reference:: db.define_table('x', Field('number', 'integer')) if db(db.x).isempty(): [db.x.insert(number=i) for i in range(10)] from gluon.dal import lazy_virtualfield class MyVirtualFields(object): # normal virtual field (backward compatible, discouraged) def normal_shift(self): return self.x.number+1 # lazy virtual field (because of @staticmethod) @lazy_virtualfield def lazy_shift(instance, row, delta=4): return row.x.number+delta db.x.virtualfields.append(MyVirtualFields()) for row in db(db.x).select(): print row.number, row.normal_shift, row.lazy_shift(delta=7) """ if not keyed_virtualfields: return self for row in self.records: for (tablename, virtualfields) in iteritems(keyed_virtualfields): attributes = dir(virtualfields) if tablename not in row: box = row[tablename] = Row() else: box = row[tablename] updated = False for attribute in attributes: if attribute[0] != '_': method = getattr(virtualfields, attribute) if hasattr(method, '__lazy__'): box[attribute] = VirtualCommand(method, row) elif type(method) == types.MethodType: if not updated: virtualfields.__dict__.update(row) updated = True box[attribute] = method() return self def __and__(self, other): if self.colnames != other.colnames: raise Exception('Cannot & incompatible Rows objects') records = self.records + other.records return self.__class__( self.db, records, self.colnames, fields=self.fields, compact=self.compact or other.compact) def __or__(self, other): if self.colnames != other.colnames: raise Exception('Cannot | incompatible Rows objects') records = [record for record in other.records if record not in self.records] records = self.records + records return self.__class__( self.db, records, self.colnames, fields=self.fields, compact=self.compact or other.compact) def __len__(self): return len(self.records) def __getslice__(self, a, b): return self.__class__( self.db, self.records[a:b], self.colnames, compact=self.compact, fields=self.fields) def __getitem__(self, i): row = self.records[i] keys = list(row.keys()) if self.compact and len(keys) == 1 and keys[0] != '_extra': return row[keys[0]] return row def __iter__(self): """ Iterator over records """ for i in xrange(len(self)): yield self[i] def __eq__(self, other): if isinstance(other, Rows): return (self.records == other.records) else: return False def column(self, column=None): return [r[str(column) if column else self.colnames[0]] for r in self] def first(self): if not self.records: return None return self[0] def last(self): if not self.records: return None return self[-1] def append(self, row): self.records.append(row) def insert(self, position, row): self.records.insert(position, row) def find(self, f, limitby=None): """ Returns a new Rows object, a subset of the original object, filtered by the function `f` """ if not self: return self.__class__( self.db, [], self.colnames, compact=self.compact, fields=self.fields) records = [] if limitby: a, b = limitby else: a, b = 0, len(self) k = 0 for i, row in enumerate(self): if f(row): if a <= k: records.append(self.records[i]) k += 1 if k == b: break return self.__class__( self.db, records, self.colnames, compact=self.compact, fields=self.fields) def exclude(self, f): """ Removes elements from the calling Rows object, filtered by the function `f`, and returns a new Rows object containing the removed elements """ if not self.records: return self.__class__( self.db, [], self.colnames, compact=self.compact, fields=self.fields) removed = [] i = 0 while i < len(self): row = self[i] if f(row): removed.append(self.records[i]) del self.records[i] else: i += 1 return self.__class__( self.db, removed, self.colnames, compact=self.compact, fields=self.fields) def sort(self, f, reverse=False): """ Returns a list of sorted elements (not sorted in place) """ rows = self.__class__( self.db, [], self.colnames, compact=self.compact, fields=self.fields) # When compact=True, iterating over self modifies each record, # so when sorting self, it is necessary to return a sorted # version of self.records rather than the sorted self directly. rows.records = [r for (r, s) in sorted(zip(self.records, self), key=lambda r: f(r[1]), reverse=reverse)] return rows def join(self, field, name=None, constraint=None, fields=[], orderby=None): if len(self) == 0: return self mode = 'referencing' if field.type == 'id' else 'referenced' func = lambda ids: field.belongs(ids) db, ids, maps = self.db, [], {} if not fields: fields = [f for f in field._table if f.readable] if mode == 'referencing': # try all refernced field names names = [name] if name else list(set( f.name for f in field._table._referenced_by if f.name in self[0])) # get all the ids ids = [row.get(name) for row in self for name in names] # filter out the invalid ids ids = filter(lambda id: str(id).isdigit(), ids) # build the query query = func(ids) if constraint: query = query & constraint tmp = not field.name in [f.name for f in fields] if tmp: fields.append(field) other = db(query).select(*fields, orderby=orderby, cacheable=True) for row in other: id = row[field.name] maps[id] = row for row in self: for name in names: row[name] = maps.get(row[name]) if mode == 'referenced': if not name: name = field._tablename # build the query query = func([row.id for row in self]) if constraint: query = query & constraint name = name or field._tablename tmp = not field.name in [f.name for f in fields] if tmp: fields.append(field) other = db(query).select(*fields, orderby=orderby, cacheable=True) for row in other: id = row[field] if not id in maps: maps[id] = [] if tmp: try: del row[field.name] except: del row[field.tablename][field.name] if not row[field.tablename] and len(row.keys())==2: del row[field.tablename] row = row[row.keys()[0]] maps[id].append(row) for row in self: row[name] = maps.get(row.id, []) return self def group_by_value(self, *fields, **args): """ Regroups the rows, by one of the fields """ one_result = False if 'one_result' in args: one_result = args['one_result'] def build_fields_struct(row, fields, num, groups): """ helper function: """ if num > len(fields) - 1: if one_result: return row else: return [row] key = fields[num] value = row[key] if value not in groups: groups[value] = build_fields_struct(row, fields, num + 1, {}) else: struct = build_fields_struct( row, fields, num + 1, groups[value]) # still have more grouping to do if isinstance(struct, dict): groups[value].update() # no more grouping, first only is off elif isinstance(struct, list): groups[value] += struct # no more grouping, first only on else: groups[value] = struct return groups if len(fields) == 0: return self # if select returned no results if not self.records: return {} grouped_row_group = dict() # build the struct for row in self: build_fields_struct(row, fields, 0, grouped_row_group) return grouped_row_group def render(self, i=None, fields=None): """ Takes an index and returns a copy of the indexed row with values transformed via the "represent" attributes of the associated fields. Args: i: index. If not specified, a generator is returned for iteration over all the rows. fields: a list of fields to transform (if None, all fields with "represent" attributes will be transformed) """ if i is None: return (self.render(i, fields=fields) for i in range(len(self))) if not self.db.has_representer('rows_render'): raise RuntimeError("Rows.render() needs a `rows_render` \ representer in DAL instance") row = copy.deepcopy(self.records[i]) keys = list(row.keys()) if not fields: fields = [f for f in self.fields if isinstance(f, Field) and f.represent] for field in fields: row[field._tablename][field.name] = self.db.represent( 'rows_render', field, row[field._tablename][field.name], row[field._tablename]) if self.compact and len(keys) == 1 and keys[0] != '_extra': return row[keys[0]] return row def __getstate__(self): ret = self.__dict__.copy() del ret['fields'] return ret def _restore_fields(self, fields): if not hasattr(self, 'fields'): self.fields = fields return self @implements_iterator class IterRows(BasicRows): def __init__(self, db, sql, fields, colnames, blob_decode, cacheable): self.db = db self.fields = fields self.colnames = colnames self.blob_decode = blob_decode self.cacheable = cacheable (self.fields_virtual, self.fields_lazy, self.tmps) = \ self.db._adapter._parse_expand_colnames(fields) self.cursor = self.db._adapter.cursor self.db._adapter.execute(sql) self.db._adapter.lock_cursor(self.cursor) self._head = None self.last_item = None self.last_item_id = None self.compact = True self.sql = sql def __next__(self): db_row = self.cursor.fetchone() if db_row is None: raise StopIteration row = self.db._adapter._parse(db_row, self.tmps, self.fields, self.colnames, self.blob_decode, self.cacheable, self.fields_virtual, self.fields_lazy) if self.compact: # The following is to translate # <Row {'t0': {'id': 1L, 'name': 'web2py'}}> # in # <Row {'id': 1L, 'name': 'web2py'}> # normally accomplished by Rows.__get_item__ keys = list(row.keys()) if len(keys) == 1 and keys[0] != '_extra': row = row[keys[0]] return row def __iter__(self): if self._head: yield self._head try: row = next(self) while row is not None: yield row row = next(self) except StopIteration: # Iterator is over, adjust the cursor logic self.db._adapter.close_cursor(self.cursor) raise StopIteration return def first(self): if self._head is None: try: self._head = next(self) except StopIteration: # TODO should I raise something? return None return self._head def __getitem__(self, key): if not isinstance(key, (int, long)): raise TypeError if key == self.last_item_id: return self.last_item n_to_drop = key if self.last_item_id is not None: if self.last_item_id < key: n_to_drop -= (self.last_item_id + 1) else: raise IndexError # fetch and drop the first key - 1 elements for i in xrange(n_to_drop): self.cursor._fetchone() row = next(self) if row is None: raise IndexError else: self.last_item_id = key self.last_item = row return row # # rowcount it doesn't seem to be reliable on all drivers # def __len__(self): # return self.db._adapter.cursor.rowcount
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['EnvironmentArgs', 'Environment'] @pulumi.input_type class EnvironmentArgs: def __init__(__self__, *, application: pulumi.Input[str], cname_prefix: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, platform_arn: Optional[pulumi.Input[str]] = None, poll_interval: Optional[pulumi.Input[str]] = None, settings: Optional[pulumi.Input[Sequence[pulumi.Input['EnvironmentSettingArgs']]]] = None, solution_stack_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, template_name: Optional[pulumi.Input[str]] = None, tier: Optional[pulumi.Input[str]] = None, version: Optional[pulumi.Input[str]] = None, wait_for_ready_timeout: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a Environment resource. :param pulumi.Input[str] application: Name of the application that contains the version to be deployed :param pulumi.Input[str] cname_prefix: Prefix to use for the fully qualified DNS name of the Environment. :param pulumi.Input[str] description: Short description of the Environment :param pulumi.Input[str] name: A unique name for this Environment. This name is used in the application URL :param pulumi.Input[str] platform_arn: The [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) of the Elastic Beanstalk [Platform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-platformarn) to use in deployment :param pulumi.Input[str] poll_interval: The time between polling the AWS API to check if changes have been applied. Use this to adjust the rate of API calls for any `create` or `update` action. Minimum `10s`, maximum `180s`. Omit this to use the default behavior, which is an exponential backoff :param pulumi.Input[Sequence[pulumi.Input['EnvironmentSettingArgs']]] settings: Option settings to configure the new Environment. These override specific values that are set as defaults. The format is detailed below in Option Settings :param pulumi.Input[str] solution_stack_name: A solution stack to base your environment off of. Example stacks can be found in the [Amazon API documentation](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html) :param pulumi.Input[str] template_name: The name of the Elastic Beanstalk Configuration template to use in deployment :param pulumi.Input[str] tier: Elastic Beanstalk Environment tier. Valid values are `Worker` or `WebServer`. If tier is left blank `WebServer` will be used. :param pulumi.Input[str] version: The name of the Elastic Beanstalk Application Version to use in deployment. :param pulumi.Input[str] wait_for_ready_timeout: The maximum [duration](https://golang.org/pkg/time/#ParseDuration) that this provider should wait for an Elastic Beanstalk Environment to be in a ready state before timing out. """ pulumi.set(__self__, "application", application) if cname_prefix is not None: pulumi.set(__self__, "cname_prefix", cname_prefix) if description is not None: pulumi.set(__self__, "description", description) if name is not None: pulumi.set(__self__, "name", name) if platform_arn is not None: pulumi.set(__self__, "platform_arn", platform_arn) if poll_interval is not None: pulumi.set(__self__, "poll_interval", poll_interval) if settings is not None: pulumi.set(__self__, "settings", settings) if solution_stack_name is not None: pulumi.set(__self__, "solution_stack_name", solution_stack_name) if tags is not None: pulumi.set(__self__, "tags", tags) if template_name is not None: pulumi.set(__self__, "template_name", template_name) if tier is not None: pulumi.set(__self__, "tier", tier) if version is not None: pulumi.set(__self__, "version", version) if wait_for_ready_timeout is not None: pulumi.set(__self__, "wait_for_ready_timeout", wait_for_ready_timeout) @property @pulumi.getter def application(self) -> pulumi.Input[str]: """ Name of the application that contains the version to be deployed """ return pulumi.get(self, "application") @application.setter def application(self, value: pulumi.Input[str]): pulumi.set(self, "application", value) @property @pulumi.getter(name="cnamePrefix") def cname_prefix(self) -> Optional[pulumi.Input[str]]: """ Prefix to use for the fully qualified DNS name of the Environment. """ return pulumi.get(self, "cname_prefix") @cname_prefix.setter def cname_prefix(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "cname_prefix", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: """ Short description of the Environment """ return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ A unique name for this Environment. This name is used in the application URL """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter(name="platformArn") def platform_arn(self) -> Optional[pulumi.Input[str]]: """ The [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) of the Elastic Beanstalk [Platform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-platformarn) to use in deployment """ return pulumi.get(self, "platform_arn") @platform_arn.setter def platform_arn(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "platform_arn", value) @property @pulumi.getter(name="pollInterval") def poll_interval(self) -> Optional[pulumi.Input[str]]: """ The time between polling the AWS API to check if changes have been applied. Use this to adjust the rate of API calls for any `create` or `update` action. Minimum `10s`, maximum `180s`. Omit this to use the default behavior, which is an exponential backoff """ return pulumi.get(self, "poll_interval") @poll_interval.setter def poll_interval(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "poll_interval", value) @property @pulumi.getter def settings(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['EnvironmentSettingArgs']]]]: """ Option settings to configure the new Environment. These override specific values that are set as defaults. The format is detailed below in Option Settings """ return pulumi.get(self, "settings") @settings.setter def settings(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['EnvironmentSettingArgs']]]]): pulumi.set(self, "settings", value) @property @pulumi.getter(name="solutionStackName") def solution_stack_name(self) -> Optional[pulumi.Input[str]]: """ A solution stack to base your environment off of. Example stacks can be found in the [Amazon API documentation](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html) """ return pulumi.get(self, "solution_stack_name") @solution_stack_name.setter def solution_stack_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "solution_stack_name", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) @property @pulumi.getter(name="templateName") def template_name(self) -> Optional[pulumi.Input[str]]: """ The name of the Elastic Beanstalk Configuration template to use in deployment """ return pulumi.get(self, "template_name") @template_name.setter def template_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "template_name", value) @property @pulumi.getter def tier(self) -> Optional[pulumi.Input[str]]: """ Elastic Beanstalk Environment tier. Valid values are `Worker` or `WebServer`. If tier is left blank `WebServer` will be used. """ return pulumi.get(self, "tier") @tier.setter def tier(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "tier", value) @property @pulumi.getter def version(self) -> Optional[pulumi.Input[str]]: """ The name of the Elastic Beanstalk Application Version to use in deployment. """ return pulumi.get(self, "version") @version.setter def version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "version", value) @property @pulumi.getter(name="waitForReadyTimeout") def wait_for_ready_timeout(self) -> Optional[pulumi.Input[str]]: """ The maximum [duration](https://golang.org/pkg/time/#ParseDuration) that this provider should wait for an Elastic Beanstalk Environment to be in a ready state before timing out. """ return pulumi.get(self, "wait_for_ready_timeout") @wait_for_ready_timeout.setter def wait_for_ready_timeout(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "wait_for_ready_timeout", value) @pulumi.input_type class _EnvironmentState: def __init__(__self__, *, all_settings: Optional[pulumi.Input[Sequence[pulumi.Input['EnvironmentAllSettingArgs']]]] = None, application: Optional[pulumi.Input[str]] = None, arn: Optional[pulumi.Input[str]] = None, autoscaling_groups: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, cname: Optional[pulumi.Input[str]] = None, cname_prefix: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, endpoint_url: Optional[pulumi.Input[str]] = None, instances: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, launch_configurations: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, load_balancers: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]] = None, platform_arn: Optional[pulumi.Input[str]] = None, poll_interval: Optional[pulumi.Input[str]] = None, queues: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, settings: Optional[pulumi.Input[Sequence[pulumi.Input['EnvironmentSettingArgs']]]] = None, solution_stack_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, tags_all: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, template_name: Optional[pulumi.Input[str]] = None, tier: Optional[pulumi.Input[str]] = None, triggers: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, version: Optional[pulumi.Input[str]] = None, wait_for_ready_timeout: Optional[pulumi.Input[str]] = None): """ Input properties used for looking up and filtering Environment resources. :param pulumi.Input[Sequence[pulumi.Input['EnvironmentAllSettingArgs']]] all_settings: List of all option settings configured in this Environment. These are a combination of default settings and their overrides from `setting` in the configuration. :param pulumi.Input[str] application: Name of the application that contains the version to be deployed :param pulumi.Input[Sequence[pulumi.Input[str]]] autoscaling_groups: The autoscaling groups used by this Environment. :param pulumi.Input[str] cname: Fully qualified DNS name for this Environment. :param pulumi.Input[str] cname_prefix: Prefix to use for the fully qualified DNS name of the Environment. :param pulumi.Input[str] description: Short description of the Environment :param pulumi.Input[str] endpoint_url: The URL to the Load Balancer for this Environment :param pulumi.Input[Sequence[pulumi.Input[str]]] instances: Instances used by this Environment. :param pulumi.Input[Sequence[pulumi.Input[str]]] launch_configurations: Launch configurations in use by this Environment. :param pulumi.Input[Sequence[pulumi.Input[str]]] load_balancers: Elastic load balancers in use by this Environment. :param pulumi.Input[str] name: A unique name for this Environment. This name is used in the application URL :param pulumi.Input[str] platform_arn: The [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) of the Elastic Beanstalk [Platform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-platformarn) to use in deployment :param pulumi.Input[str] poll_interval: The time between polling the AWS API to check if changes have been applied. Use this to adjust the rate of API calls for any `create` or `update` action. Minimum `10s`, maximum `180s`. Omit this to use the default behavior, which is an exponential backoff :param pulumi.Input[Sequence[pulumi.Input[str]]] queues: SQS queues in use by this Environment. :param pulumi.Input[Sequence[pulumi.Input['EnvironmentSettingArgs']]] settings: Option settings to configure the new Environment. These override specific values that are set as defaults. The format is detailed below in Option Settings :param pulumi.Input[str] solution_stack_name: A solution stack to base your environment off of. Example stacks can be found in the [Amazon API documentation](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html) :param pulumi.Input[str] template_name: The name of the Elastic Beanstalk Configuration template to use in deployment :param pulumi.Input[str] tier: Elastic Beanstalk Environment tier. Valid values are `Worker` or `WebServer`. If tier is left blank `WebServer` will be used. :param pulumi.Input[Sequence[pulumi.Input[str]]] triggers: Autoscaling triggers in use by this Environment. :param pulumi.Input[str] version: The name of the Elastic Beanstalk Application Version to use in deployment. :param pulumi.Input[str] wait_for_ready_timeout: The maximum [duration](https://golang.org/pkg/time/#ParseDuration) that this provider should wait for an Elastic Beanstalk Environment to be in a ready state before timing out. """ if all_settings is not None: pulumi.set(__self__, "all_settings", all_settings) if application is not None: pulumi.set(__self__, "application", application) if arn is not None: pulumi.set(__self__, "arn", arn) if autoscaling_groups is not None: pulumi.set(__self__, "autoscaling_groups", autoscaling_groups) if cname is not None: pulumi.set(__self__, "cname", cname) if cname_prefix is not None: pulumi.set(__self__, "cname_prefix", cname_prefix) if description is not None: pulumi.set(__self__, "description", description) if endpoint_url is not None: pulumi.set(__self__, "endpoint_url", endpoint_url) if instances is not None: pulumi.set(__self__, "instances", instances) if launch_configurations is not None: pulumi.set(__self__, "launch_configurations", launch_configurations) if load_balancers is not None: pulumi.set(__self__, "load_balancers", load_balancers) if name is not None: pulumi.set(__self__, "name", name) if platform_arn is not None: pulumi.set(__self__, "platform_arn", platform_arn) if poll_interval is not None: pulumi.set(__self__, "poll_interval", poll_interval) if queues is not None: pulumi.set(__self__, "queues", queues) if settings is not None: pulumi.set(__self__, "settings", settings) if solution_stack_name is not None: pulumi.set(__self__, "solution_stack_name", solution_stack_name) if tags is not None: pulumi.set(__self__, "tags", tags) if tags_all is not None: pulumi.set(__self__, "tags_all", tags_all) if template_name is not None: pulumi.set(__self__, "template_name", template_name) if tier is not None: pulumi.set(__self__, "tier", tier) if triggers is not None: pulumi.set(__self__, "triggers", triggers) if version is not None: pulumi.set(__self__, "version", version) if wait_for_ready_timeout is not None: pulumi.set(__self__, "wait_for_ready_timeout", wait_for_ready_timeout) @property @pulumi.getter(name="allSettings") def all_settings(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['EnvironmentAllSettingArgs']]]]: """ List of all option settings configured in this Environment. These are a combination of default settings and their overrides from `setting` in the configuration. """ return pulumi.get(self, "all_settings") @all_settings.setter def all_settings(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['EnvironmentAllSettingArgs']]]]): pulumi.set(self, "all_settings", value) @property @pulumi.getter def application(self) -> Optional[pulumi.Input[str]]: """ Name of the application that contains the version to be deployed """ return pulumi.get(self, "application") @application.setter def application(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "application", value) @property @pulumi.getter def arn(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "arn") @arn.setter def arn(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "arn", value) @property @pulumi.getter(name="autoscalingGroups") def autoscaling_groups(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ The autoscaling groups used by this Environment. """ return pulumi.get(self, "autoscaling_groups") @autoscaling_groups.setter def autoscaling_groups(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "autoscaling_groups", value) @property @pulumi.getter def cname(self) -> Optional[pulumi.Input[str]]: """ Fully qualified DNS name for this Environment. """ return pulumi.get(self, "cname") @cname.setter def cname(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "cname", value) @property @pulumi.getter(name="cnamePrefix") def cname_prefix(self) -> Optional[pulumi.Input[str]]: """ Prefix to use for the fully qualified DNS name of the Environment. """ return pulumi.get(self, "cname_prefix") @cname_prefix.setter def cname_prefix(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "cname_prefix", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: """ Short description of the Environment """ return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter(name="endpointUrl") def endpoint_url(self) -> Optional[pulumi.Input[str]]: """ The URL to the Load Balancer for this Environment """ return pulumi.get(self, "endpoint_url") @endpoint_url.setter def endpoint_url(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "endpoint_url", value) @property @pulumi.getter def instances(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ Instances used by this Environment. """ return pulumi.get(self, "instances") @instances.setter def instances(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "instances", value) @property @pulumi.getter(name="launchConfigurations") def launch_configurations(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ Launch configurations in use by this Environment. """ return pulumi.get(self, "launch_configurations") @launch_configurations.setter def launch_configurations(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "launch_configurations", value) @property @pulumi.getter(name="loadBalancers") def load_balancers(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ Elastic load balancers in use by this Environment. """ return pulumi.get(self, "load_balancers") @load_balancers.setter def load_balancers(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "load_balancers", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ A unique name for this Environment. This name is used in the application URL """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter(name="platformArn") def platform_arn(self) -> Optional[pulumi.Input[str]]: """ The [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) of the Elastic Beanstalk [Platform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-platformarn) to use in deployment """ return pulumi.get(self, "platform_arn") @platform_arn.setter def platform_arn(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "platform_arn", value) @property @pulumi.getter(name="pollInterval") def poll_interval(self) -> Optional[pulumi.Input[str]]: """ The time between polling the AWS API to check if changes have been applied. Use this to adjust the rate of API calls for any `create` or `update` action. Minimum `10s`, maximum `180s`. Omit this to use the default behavior, which is an exponential backoff """ return pulumi.get(self, "poll_interval") @poll_interval.setter def poll_interval(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "poll_interval", value) @property @pulumi.getter def queues(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ SQS queues in use by this Environment. """ return pulumi.get(self, "queues") @queues.setter def queues(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "queues", value) @property @pulumi.getter def settings(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['EnvironmentSettingArgs']]]]: """ Option settings to configure the new Environment. These override specific values that are set as defaults. The format is detailed below in Option Settings """ return pulumi.get(self, "settings") @settings.setter def settings(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['EnvironmentSettingArgs']]]]): pulumi.set(self, "settings", value) @property @pulumi.getter(name="solutionStackName") def solution_stack_name(self) -> Optional[pulumi.Input[str]]: """ A solution stack to base your environment off of. Example stacks can be found in the [Amazon API documentation](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html) """ return pulumi.get(self, "solution_stack_name") @solution_stack_name.setter def solution_stack_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "solution_stack_name", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) @property @pulumi.getter(name="tagsAll") def tags_all(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: return pulumi.get(self, "tags_all") @tags_all.setter def tags_all(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags_all", value) @property @pulumi.getter(name="templateName") def template_name(self) -> Optional[pulumi.Input[str]]: """ The name of the Elastic Beanstalk Configuration template to use in deployment """ return pulumi.get(self, "template_name") @template_name.setter def template_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "template_name", value) @property @pulumi.getter def tier(self) -> Optional[pulumi.Input[str]]: """ Elastic Beanstalk Environment tier. Valid values are `Worker` or `WebServer`. If tier is left blank `WebServer` will be used. """ return pulumi.get(self, "tier") @tier.setter def tier(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "tier", value) @property @pulumi.getter def triggers(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ Autoscaling triggers in use by this Environment. """ return pulumi.get(self, "triggers") @triggers.setter def triggers(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "triggers", value) @property @pulumi.getter def version(self) -> Optional[pulumi.Input[str]]: """ The name of the Elastic Beanstalk Application Version to use in deployment. """ return pulumi.get(self, "version") @version.setter def version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "version", value) @property @pulumi.getter(name="waitForReadyTimeout") def wait_for_ready_timeout(self) -> Optional[pulumi.Input[str]]: """ The maximum [duration](https://golang.org/pkg/time/#ParseDuration) that this provider should wait for an Elastic Beanstalk Environment to be in a ready state before timing out. """ return pulumi.get(self, "wait_for_ready_timeout") @wait_for_ready_timeout.setter def wait_for_ready_timeout(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "wait_for_ready_timeout", value) class Environment(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, application: Optional[pulumi.Input[str]] = None, cname_prefix: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, platform_arn: Optional[pulumi.Input[str]] = None, poll_interval: Optional[pulumi.Input[str]] = None, settings: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['EnvironmentSettingArgs']]]]] = None, solution_stack_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, template_name: Optional[pulumi.Input[str]] = None, tier: Optional[pulumi.Input[str]] = None, version: Optional[pulumi.Input[str]] = None, wait_for_ready_timeout: Optional[pulumi.Input[str]] = None, __props__=None): """ Provides an Elastic Beanstalk Environment Resource. Elastic Beanstalk allows you to deploy and manage applications in the AWS cloud without worrying about the infrastructure that runs those applications. Environments are often things such as `development`, `integration`, or `production`. ## Example Usage ```python import pulumi import pulumi_aws as aws tftest = aws.elasticbeanstalk.Application("tftest", description="tf-test-desc") tfenvtest = aws.elasticbeanstalk.Environment("tfenvtest", application=tftest.name, solution_stack_name="64bit Amazon Linux 2015.03 v2.0.3 running Go 1.4") ``` ## Option Settings Some options can be stack-specific, check [AWS Docs](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html) for supported options and examples. The `setting` and `all_settings` mappings support the following format: * `namespace` - unique namespace identifying the option's associated AWS resource * `name` - name of the configuration option * `value` - value for the configuration option * `resource` - (Optional) resource name for [scheduled action](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html#command-options-general-autoscalingscheduledaction) ### Example With Options ```python import pulumi import pulumi_aws as aws tftest = aws.elasticbeanstalk.Application("tftest", description="tf-test-desc") tfenvtest = aws.elasticbeanstalk.Environment("tfenvtest", application=tftest.name, solution_stack_name="64bit Amazon Linux 2015.03 v2.0.3 running Go 1.4", settings=[ aws.elasticbeanstalk.EnvironmentSettingArgs( namespace="aws:ec2:vpc", name="VPCId", value="vpc-xxxxxxxx", ), aws.elasticbeanstalk.EnvironmentSettingArgs( namespace="aws:ec2:vpc", name="Subnets", value="subnet-xxxxxxxx", ), ]) ``` ## Import Elastic Beanstalk Environments can be imported using the `id`, e.g. ```sh $ pulumi import aws:elasticbeanstalk/environment:Environment prodenv e-rpqsewtp2j ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] application: Name of the application that contains the version to be deployed :param pulumi.Input[str] cname_prefix: Prefix to use for the fully qualified DNS name of the Environment. :param pulumi.Input[str] description: Short description of the Environment :param pulumi.Input[str] name: A unique name for this Environment. This name is used in the application URL :param pulumi.Input[str] platform_arn: The [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) of the Elastic Beanstalk [Platform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-platformarn) to use in deployment :param pulumi.Input[str] poll_interval: The time between polling the AWS API to check if changes have been applied. Use this to adjust the rate of API calls for any `create` or `update` action. Minimum `10s`, maximum `180s`. Omit this to use the default behavior, which is an exponential backoff :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['EnvironmentSettingArgs']]]] settings: Option settings to configure the new Environment. These override specific values that are set as defaults. The format is detailed below in Option Settings :param pulumi.Input[str] solution_stack_name: A solution stack to base your environment off of. Example stacks can be found in the [Amazon API documentation](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html) :param pulumi.Input[str] template_name: The name of the Elastic Beanstalk Configuration template to use in deployment :param pulumi.Input[str] tier: Elastic Beanstalk Environment tier. Valid values are `Worker` or `WebServer`. If tier is left blank `WebServer` will be used. :param pulumi.Input[str] version: The name of the Elastic Beanstalk Application Version to use in deployment. :param pulumi.Input[str] wait_for_ready_timeout: The maximum [duration](https://golang.org/pkg/time/#ParseDuration) that this provider should wait for an Elastic Beanstalk Environment to be in a ready state before timing out. """ ... @overload def __init__(__self__, resource_name: str, args: EnvironmentArgs, opts: Optional[pulumi.ResourceOptions] = None): """ Provides an Elastic Beanstalk Environment Resource. Elastic Beanstalk allows you to deploy and manage applications in the AWS cloud without worrying about the infrastructure that runs those applications. Environments are often things such as `development`, `integration`, or `production`. ## Example Usage ```python import pulumi import pulumi_aws as aws tftest = aws.elasticbeanstalk.Application("tftest", description="tf-test-desc") tfenvtest = aws.elasticbeanstalk.Environment("tfenvtest", application=tftest.name, solution_stack_name="64bit Amazon Linux 2015.03 v2.0.3 running Go 1.4") ``` ## Option Settings Some options can be stack-specific, check [AWS Docs](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html) for supported options and examples. The `setting` and `all_settings` mappings support the following format: * `namespace` - unique namespace identifying the option's associated AWS resource * `name` - name of the configuration option * `value` - value for the configuration option * `resource` - (Optional) resource name for [scheduled action](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html#command-options-general-autoscalingscheduledaction) ### Example With Options ```python import pulumi import pulumi_aws as aws tftest = aws.elasticbeanstalk.Application("tftest", description="tf-test-desc") tfenvtest = aws.elasticbeanstalk.Environment("tfenvtest", application=tftest.name, solution_stack_name="64bit Amazon Linux 2015.03 v2.0.3 running Go 1.4", settings=[ aws.elasticbeanstalk.EnvironmentSettingArgs( namespace="aws:ec2:vpc", name="VPCId", value="vpc-xxxxxxxx", ), aws.elasticbeanstalk.EnvironmentSettingArgs( namespace="aws:ec2:vpc", name="Subnets", value="subnet-xxxxxxxx", ), ]) ``` ## Import Elastic Beanstalk Environments can be imported using the `id`, e.g. ```sh $ pulumi import aws:elasticbeanstalk/environment:Environment prodenv e-rpqsewtp2j ``` :param str resource_name: The name of the resource. :param EnvironmentArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(EnvironmentArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, application: Optional[pulumi.Input[str]] = None, cname_prefix: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, platform_arn: Optional[pulumi.Input[str]] = None, poll_interval: Optional[pulumi.Input[str]] = None, settings: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['EnvironmentSettingArgs']]]]] = None, solution_stack_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, template_name: Optional[pulumi.Input[str]] = None, tier: Optional[pulumi.Input[str]] = None, version: Optional[pulumi.Input[str]] = None, wait_for_ready_timeout: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = EnvironmentArgs.__new__(EnvironmentArgs) if application is None and not opts.urn: raise TypeError("Missing required property 'application'") __props__.__dict__["application"] = application __props__.__dict__["cname_prefix"] = cname_prefix __props__.__dict__["description"] = description __props__.__dict__["name"] = name __props__.__dict__["platform_arn"] = platform_arn __props__.__dict__["poll_interval"] = poll_interval __props__.__dict__["settings"] = settings __props__.__dict__["solution_stack_name"] = solution_stack_name __props__.__dict__["tags"] = tags __props__.__dict__["template_name"] = template_name __props__.__dict__["tier"] = tier __props__.__dict__["version"] = version __props__.__dict__["wait_for_ready_timeout"] = wait_for_ready_timeout __props__.__dict__["all_settings"] = None __props__.__dict__["arn"] = None __props__.__dict__["autoscaling_groups"] = None __props__.__dict__["cname"] = None __props__.__dict__["endpoint_url"] = None __props__.__dict__["instances"] = None __props__.__dict__["launch_configurations"] = None __props__.__dict__["load_balancers"] = None __props__.__dict__["queues"] = None __props__.__dict__["tags_all"] = None __props__.__dict__["triggers"] = None super(Environment, __self__).__init__( 'aws:elasticbeanstalk/environment:Environment', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, all_settings: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['EnvironmentAllSettingArgs']]]]] = None, application: Optional[pulumi.Input[str]] = None, arn: Optional[pulumi.Input[str]] = None, autoscaling_groups: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, cname: Optional[pulumi.Input[str]] = None, cname_prefix: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, endpoint_url: Optional[pulumi.Input[str]] = None, instances: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, launch_configurations: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, load_balancers: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]] = None, platform_arn: Optional[pulumi.Input[str]] = None, poll_interval: Optional[pulumi.Input[str]] = None, queues: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, settings: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['EnvironmentSettingArgs']]]]] = None, solution_stack_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, tags_all: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, template_name: Optional[pulumi.Input[str]] = None, tier: Optional[pulumi.Input[str]] = None, triggers: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, version: Optional[pulumi.Input[str]] = None, wait_for_ready_timeout: Optional[pulumi.Input[str]] = None) -> 'Environment': """ Get an existing Environment resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['EnvironmentAllSettingArgs']]]] all_settings: List of all option settings configured in this Environment. These are a combination of default settings and their overrides from `setting` in the configuration. :param pulumi.Input[str] application: Name of the application that contains the version to be deployed :param pulumi.Input[Sequence[pulumi.Input[str]]] autoscaling_groups: The autoscaling groups used by this Environment. :param pulumi.Input[str] cname: Fully qualified DNS name for this Environment. :param pulumi.Input[str] cname_prefix: Prefix to use for the fully qualified DNS name of the Environment. :param pulumi.Input[str] description: Short description of the Environment :param pulumi.Input[str] endpoint_url: The URL to the Load Balancer for this Environment :param pulumi.Input[Sequence[pulumi.Input[str]]] instances: Instances used by this Environment. :param pulumi.Input[Sequence[pulumi.Input[str]]] launch_configurations: Launch configurations in use by this Environment. :param pulumi.Input[Sequence[pulumi.Input[str]]] load_balancers: Elastic load balancers in use by this Environment. :param pulumi.Input[str] name: A unique name for this Environment. This name is used in the application URL :param pulumi.Input[str] platform_arn: The [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) of the Elastic Beanstalk [Platform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-platformarn) to use in deployment :param pulumi.Input[str] poll_interval: The time between polling the AWS API to check if changes have been applied. Use this to adjust the rate of API calls for any `create` or `update` action. Minimum `10s`, maximum `180s`. Omit this to use the default behavior, which is an exponential backoff :param pulumi.Input[Sequence[pulumi.Input[str]]] queues: SQS queues in use by this Environment. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['EnvironmentSettingArgs']]]] settings: Option settings to configure the new Environment. These override specific values that are set as defaults. The format is detailed below in Option Settings :param pulumi.Input[str] solution_stack_name: A solution stack to base your environment off of. Example stacks can be found in the [Amazon API documentation](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html) :param pulumi.Input[str] template_name: The name of the Elastic Beanstalk Configuration template to use in deployment :param pulumi.Input[str] tier: Elastic Beanstalk Environment tier. Valid values are `Worker` or `WebServer`. If tier is left blank `WebServer` will be used. :param pulumi.Input[Sequence[pulumi.Input[str]]] triggers: Autoscaling triggers in use by this Environment. :param pulumi.Input[str] version: The name of the Elastic Beanstalk Application Version to use in deployment. :param pulumi.Input[str] wait_for_ready_timeout: The maximum [duration](https://golang.org/pkg/time/#ParseDuration) that this provider should wait for an Elastic Beanstalk Environment to be in a ready state before timing out. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _EnvironmentState.__new__(_EnvironmentState) __props__.__dict__["all_settings"] = all_settings __props__.__dict__["application"] = application __props__.__dict__["arn"] = arn __props__.__dict__["autoscaling_groups"] = autoscaling_groups __props__.__dict__["cname"] = cname __props__.__dict__["cname_prefix"] = cname_prefix __props__.__dict__["description"] = description __props__.__dict__["endpoint_url"] = endpoint_url __props__.__dict__["instances"] = instances __props__.__dict__["launch_configurations"] = launch_configurations __props__.__dict__["load_balancers"] = load_balancers __props__.__dict__["name"] = name __props__.__dict__["platform_arn"] = platform_arn __props__.__dict__["poll_interval"] = poll_interval __props__.__dict__["queues"] = queues __props__.__dict__["settings"] = settings __props__.__dict__["solution_stack_name"] = solution_stack_name __props__.__dict__["tags"] = tags __props__.__dict__["tags_all"] = tags_all __props__.__dict__["template_name"] = template_name __props__.__dict__["tier"] = tier __props__.__dict__["triggers"] = triggers __props__.__dict__["version"] = version __props__.__dict__["wait_for_ready_timeout"] = wait_for_ready_timeout return Environment(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="allSettings") def all_settings(self) -> pulumi.Output[Sequence['outputs.EnvironmentAllSetting']]: """ List of all option settings configured in this Environment. These are a combination of default settings and their overrides from `setting` in the configuration. """ return pulumi.get(self, "all_settings") @property @pulumi.getter def application(self) -> pulumi.Output[str]: """ Name of the application that contains the version to be deployed """ return pulumi.get(self, "application") @property @pulumi.getter def arn(self) -> pulumi.Output[str]: return pulumi.get(self, "arn") @property @pulumi.getter(name="autoscalingGroups") def autoscaling_groups(self) -> pulumi.Output[Sequence[str]]: """ The autoscaling groups used by this Environment. """ return pulumi.get(self, "autoscaling_groups") @property @pulumi.getter def cname(self) -> pulumi.Output[str]: """ Fully qualified DNS name for this Environment. """ return pulumi.get(self, "cname") @property @pulumi.getter(name="cnamePrefix") def cname_prefix(self) -> pulumi.Output[str]: """ Prefix to use for the fully qualified DNS name of the Environment. """ return pulumi.get(self, "cname_prefix") @property @pulumi.getter def description(self) -> pulumi.Output[Optional[str]]: """ Short description of the Environment """ return pulumi.get(self, "description") @property @pulumi.getter(name="endpointUrl") def endpoint_url(self) -> pulumi.Output[str]: """ The URL to the Load Balancer for this Environment """ return pulumi.get(self, "endpoint_url") @property @pulumi.getter def instances(self) -> pulumi.Output[Sequence[str]]: """ Instances used by this Environment. """ return pulumi.get(self, "instances") @property @pulumi.getter(name="launchConfigurations") def launch_configurations(self) -> pulumi.Output[Sequence[str]]: """ Launch configurations in use by this Environment. """ return pulumi.get(self, "launch_configurations") @property @pulumi.getter(name="loadBalancers") def load_balancers(self) -> pulumi.Output[Sequence[str]]: """ Elastic load balancers in use by this Environment. """ return pulumi.get(self, "load_balancers") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ A unique name for this Environment. This name is used in the application URL """ return pulumi.get(self, "name") @property @pulumi.getter(name="platformArn") def platform_arn(self) -> pulumi.Output[str]: """ The [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) of the Elastic Beanstalk [Platform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-platformarn) to use in deployment """ return pulumi.get(self, "platform_arn") @property @pulumi.getter(name="pollInterval") def poll_interval(self) -> pulumi.Output[Optional[str]]: """ The time between polling the AWS API to check if changes have been applied. Use this to adjust the rate of API calls for any `create` or `update` action. Minimum `10s`, maximum `180s`. Omit this to use the default behavior, which is an exponential backoff """ return pulumi.get(self, "poll_interval") @property @pulumi.getter def queues(self) -> pulumi.Output[Sequence[str]]: """ SQS queues in use by this Environment. """ return pulumi.get(self, "queues") @property @pulumi.getter def settings(self) -> pulumi.Output[Optional[Sequence['outputs.EnvironmentSetting']]]: """ Option settings to configure the new Environment. These override specific values that are set as defaults. The format is detailed below in Option Settings """ return pulumi.get(self, "settings") @property @pulumi.getter(name="solutionStackName") def solution_stack_name(self) -> pulumi.Output[str]: """ A solution stack to base your environment off of. Example stacks can be found in the [Amazon API documentation](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html) """ return pulumi.get(self, "solution_stack_name") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: return pulumi.get(self, "tags") @property @pulumi.getter(name="tagsAll") def tags_all(self) -> pulumi.Output[Mapping[str, str]]: return pulumi.get(self, "tags_all") @property @pulumi.getter(name="templateName") def template_name(self) -> pulumi.Output[Optional[str]]: """ The name of the Elastic Beanstalk Configuration template to use in deployment """ return pulumi.get(self, "template_name") @property @pulumi.getter def tier(self) -> pulumi.Output[Optional[str]]: """ Elastic Beanstalk Environment tier. Valid values are `Worker` or `WebServer`. If tier is left blank `WebServer` will be used. """ return pulumi.get(self, "tier") @property @pulumi.getter def triggers(self) -> pulumi.Output[Sequence[str]]: """ Autoscaling triggers in use by this Environment. """ return pulumi.get(self, "triggers") @property @pulumi.getter def version(self) -> pulumi.Output[str]: """ The name of the Elastic Beanstalk Application Version to use in deployment. """ return pulumi.get(self, "version") @property @pulumi.getter(name="waitForReadyTimeout") def wait_for_ready_timeout(self) -> pulumi.Output[Optional[str]]: """ The maximum [duration](https://golang.org/pkg/time/#ParseDuration) that this provider should wait for an Elastic Beanstalk Environment to be in a ready state before timing out. """ return pulumi.get(self, "wait_for_ready_timeout")
#!/usr/bin/env python3 # -*- utf-8 -*- """ An implementation of Hungarian algorithm for solving the assigment problem. An instance of the assigment problem consists of a number of workers along with a number of jobs and a cost matrix which gives the cost of assigning the ith worker to the jth job at position(i, j). The goal is to find an assignment of workers to the jobs so that no job is assigned more than one worker and so that no worker is assigned to more than one job in such a manner so as to minimize the total cost of completing the jobs. In this implementation, we use workers and jobs to stand for the two vertices sets in the bipartite graph and deal with the minimum-cost matching problem. It is easy to transform the minimum problem to the maximum one, just by setting cost(x, y) = M - cost(x, y), where M = max cost(x, y). Reference: http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=hungarianAlgorith http://www.cse.ust.hk/~golin/COMP572/Notes/Matching.pdf https://github.com/KevinStern/software-and-algorithms-cpp """ import numpy as np from numba import jit class Hungarian: def __init__(self, N): self.N = N # labels for jobs and workers self.job_labels = np.empty(self.N, dtype='float64') self.worker_labels = np.empty(self.N, dtype='float64') # matched_workers[w] - job that is matched with w self.matched_workers = np.empty(self.N, dtype='int32') # matched_jobs[j] - worker that is matched with j self.matched_jobs = np.empty(self.N, dtype='int32') # determine whether the worker is on the alternating tree(in S) self.committed_workers = np.empty(self.N, dtype='bool') # determine whether the job is on the alternating tree(in T) self.committed_jobs = np.empty(self.N, dtype='bool') # parent_worker[j] that the worker which is the parent # node of job j on the alternating tree self.parent_worker = np.empty(self.N, dtype='int32') # use to trace the min slack values self.slack = np.empty(self.N, dtype='float64') self.slack_worker = np.empty(self.N, dtype='int32') def execute(self, cost_matrix): m, n = cost_matrix.shape msg = ('cost_matrix should be square matrix of size (%d, %d)' % (self.N, self.N)) assert m == self.N, msg assert n == self.N, msg self.cost = np.copy(cost_matrix) self.reduce() self.initialize_labels() self.greedy_match() worker = self.fetch_free_worker() while worker < self.N: self.initialize_phase(worker) self.execute_phase() worker = self.fetch_free_worker() assignment = np.array([(w, j) for w, j in enumerate(self.matched_workers)]) total_cost = cost_matrix[assignment[:, 0], assignment[:, 1]].sum() return total_cost, assignment def reduce(self): """ Compute the reduced cost matrix. Reduce the cost matrix by subtracting the smallest element of each row from all elements of the row as well as the smallest element of each column from all elements of the column. """ self.cost -= self.cost.min(axis=1, keepdims=True) self.cost -= self.cost.min(axis=0, keepdims=True) def greedy_match(self): """ Find a vaild matching by greedily selecting among zero cost matchings. """ self.matched_workers.fill(-1) self.matched_jobs.fill(-1) greedy_match(self.cost, self.matched_workers, self.matched_jobs, self.worker_labels, self.job_labels) def initialize_labels(self): """ Initialize the labels of workers and jobs by assigning zeros to the jobs and assigning to each worker a label equal to the minimum cost among its adjacent edges. """ self.job_labels.fill(0) self.worker_labels = self.cost.min(axis=1) def fetch_free_worker(self): """ Return first free worker or N if all workers have been assigned a job. """ for w in range(self.N): if self.matched_workers[w] == -1: return w else: return w + 1 def initialize_phase(self, worker): """ Initialization before the new phase of the algorithm. 1. Clear the committed workers(marks for workers in S) and committed jobs(marks for jobs in T). 2. Initialize the slack to the values corresponding to the given worker. """ self.committed_workers.fill(False) self.committed_jobs.fill(False) self.parent_worker.fill(-1) self.committed_workers[worker] = True # cost(w, j) - l(w) - l(j) where w in S and j not in T self.slack = (self.cost[worker] - self.worker_labels[worker] - self.job_labels) # slack_worker[j] - worker that cost(slack_worker[j], j) - # l(slack_worker[j]) - l(j) = slack[j] self.slack_worker.fill(worker) def update_labels(self, delta): """ Update the labels with the given delta value by adding it for all committed workers and by subtracting it for all committed jobs. Besides, update the slack values appropriately. """ # increase the label of worker which is comimtted(in S) self.worker_labels[self.committed_workers] += delta # decrease the label of job which is committed(in T) self.job_labels[self.committed_jobs] -= delta # decrease the slack of free job whose # corresponding worker's label which has been increased self.slack[np.logical_not(self.committed_jobs)] -= delta def execute_phase(self): """ Do one phase of the algorithm. """ cost = self.cost worker_labels = self.worker_labels job_labels = self.job_labels matched_workers = self.matched_workers matched_jobs = self.matched_jobs committed_workers = self.committed_workers committed_jobs = self.committed_jobs slack = self.slack slack_worker = self.slack_worker parent_worker = self.parent_worker N = self.N while True: # try to find N(S) minslack = np.inf minslack_job = -1 for j in range(N): if not committed_jobs[j] and slack[j] < minslack: minslack_job = j minslack = slack[j] minslack_worker = slack_worker[minslack_job] if minslack > 0: # N(S) = T, # update labels to force N(S) != T self.update_labels(minslack) # now N(S) != T and minslack_job in N(S) - T parent_worker[minslack_job] = minslack_worker if matched_jobs[minslack_job] == -1: # minslack_job is free. # augmenting path found! leaf = minslack_job while leaf != -1: parent = parent_worker[leaf] grandparent = matched_workers[parent] matched_workers[parent] = leaf matched_jobs[leaf] = parent leaf = grandparent break else: # minslack_job is not free. # add minslack_job to T, add the worker matched with # minslack_job to S committed_jobs[minslack_job] = True worker = matched_jobs[minslack_job] committed_workers[worker] = True # update slack since we add a new worker to S for j in range(self.N): if not committed_jobs[j]: new_slack = (cost[worker, j] - worker_labels[worker] - job_labels[j]) if new_slack < slack[j]: slack[j] = new_slack slack_worker[j] = worker @jit def greedy_match(cost_matrix, matched_workers, matched_jobs, worker_labels, job_labels): """ Use numba to speed up. """ N = cost_matrix.shape[0] for w in range(N): for j in range(N): if (matched_workers[w] == -1 and matched_jobs[j] == -1 and cost_matrix[w, j] - worker_labels[w] - job_labels[j] == 0): matched_workers[w] = j matched_jobs[j] = w
import{openBlock as n,createBlock as t}from"vue";var e={props:{shape:{type:String,default:"rectangle"},size:{type:String,default:null},width:{type:String,default:"100%"},height:{type:String,default:"1rem"},borderRadius:{type:String,default:null},animation:{type:String,default:"wave"}},computed:{containerClass(){return["p-skeleton p-component",{"p-skeleton-circle":"circle"===this.shape,"p-skeleton-animation-none":"none"===this.animation}]},containerStyle(){return this.size?{width:this.size,height:this.size,borderRadius:this.borderRadius}:{width:this.width,height:this.height,borderRadius:this.borderRadius}}}};!function(n,t){void 0===t&&(t={});var e=t.insertAt;if(n&&"undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.type="text/css","top"===e&&i.firstChild?i.insertBefore(a,i.firstChild):i.appendChild(a),a.styleSheet?a.styleSheet.cssText=n:a.appendChild(document.createTextNode(n))}}('\n.p-skeleton {\n position: relative;\n overflow: hidden;\n}\n.p-skeleton::after {\n content: "";\n -webkit-animation: p-skeleton-animation 1.2s infinite;\n animation: p-skeleton-animation 1.2s infinite;\n height: 100%;\n left: 0;\n position: absolute;\n right: 0;\n top: 0;\n -webkit-transform: translateX(-100%);\n transform: translateX(-100%);\n z-index: 1;\n}\n.p-skeleton.p-skeleton-circle {\n border-radius: 50%;\n}\n.p-skeleton-none::after {\n -webkit-animation: none;\n animation: none;\n}\n@-webkit-keyframes p-skeleton-animation {\nfrom {\n -webkit-transform: translateX(-100%);\n transform: translateX(-100%);\n}\nto {\n -webkit-transform: translateX(100%);\n transform: translateX(100%);\n}\n}\n@keyframes p-skeleton-animation {\nfrom {\n -webkit-transform: translateX(-100%);\n transform: translateX(-100%);\n}\nto {\n -webkit-transform: translateX(100%);\n transform: translateX(100%);\n}\n}\n'),e.render=function(e,i,a,r,o,s){return n(),t("div",{style:s.containerStyle,class:s.containerClass},null,6)};export default e;
/*jslint browser: true, eqeqeq: true, bitwise: true, newcap: true, immed: true, regexp: false */ /** LazyLoad makes it easy and painless to lazily load one or more external JavaScript or CSS files on demand either during or after the rendering of a web page. Supported browsers include Firefox 2+, IE6+, Safari 3+ (including Mobile Safari), Google Chrome, and Opera 9+. Other browsers may or may not work and are not officially supported. Visit https://github.com/rgrove/lazyload/ for more info. Copyright (c) 2011 Ryan Grove <ryan@wonko.com> All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @module lazyload @class LazyLoad @static */ LazyLoad = (function (doc) { // -- Private Variables ------------------------------------------------------ // User agent and feature test information. var env, // Reference to the <head> element (populated lazily). head, // Requests currently in progress, if any. pending = {}, // Number of times we've polled to check whether a pending stylesheet has // finished loading. If this gets too high, we're probably stalled. pollCount = 0, // Queued requests. queue = {css: [], js: []}, // Reference to the browser's list of stylesheets. styleSheets = doc.styleSheets; // -- Private Methods -------------------------------------------------------- /** Creates and returns an HTML element with the specified name and attributes. @method createNode @param {String} name element name @param {Object} attrs name/value mapping of element attributes @return {HTMLElement} @private */ function createNode(name, attrs) { var node = doc.createElement(name), attr; for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(attr, attrs[attr]); } } return node; } /** Called when the current pending resource of the specified type has finished loading. Executes the associated callback (if any) and loads the next resource in the queue. @method finish @param {String} type resource type ('css' or 'js') @private */ function finish(type) { var p = pending[type], callback, urls; if (p) { callback = p.callback; urls = p.urls; urls.shift(); pollCount = 0; // If this is the last of the pending URLs, execute the callback and // start the next request in the queue (if any). if (!urls.length) { callback && callback.call(p.context, p.obj); pending[type] = null; queue[type].length && load(type); } } } /** Populates the <code>env</code> variable with user agent and feature test information. @method getEnv @private */ function getEnv() { var ua = navigator.userAgent; env = { // True if this browser supports disabling async mode on dynamically // created script nodes. See // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order async: doc.createElement('script').async === true }; (env.webkit = /AppleWebKit\//.test(ua)) || (env.ie = /MSIE|Trident/.test(ua)) || (env.opera = /Opera/.test(ua)) || (env.gecko = /Gecko\//.test(ua)) || (env.unknown = true); } /** Loads the specified resources, or the next resource of the specified type in the queue if no resources are specified. If a resource of the specified type is already being loaded, the new request will be queued until the first request has been finished. When an array of resource URLs is specified, those URLs will be loaded in parallel if it is possible to do so while preserving execution order. All browsers support parallel loading of CSS, but only Firefox and Opera support parallel loading of scripts. In other browsers, scripts will be queued and loaded one at a time to ensure correct execution order. @method load @param {String} type resource type ('css' or 'js') @param {String|Array} urls (optional) URL or array of URLs to load @param {Function} callback (optional) callback function to execute when the resource is loaded @param {Object} obj (optional) object to pass to the callback function @param {Object} context (optional) if provided, the callback function will be executed in this object's context @private */ function load(type, urls, callback, obj, context) { var _finish = function () { finish(type); }, isCSS = type === 'css', nodes = [], i, len, node, p, pendingUrls, url; env || getEnv(); if (urls) { // If urls is a string, wrap it in an array. Otherwise assume it's an // array and create a copy of it so modifications won't be made to the // original. urls = typeof urls === 'string' ? [urls] : urls.concat(); // Create a request object for each URL. If multiple URLs are specified, // the callback will only be executed after all URLs have been loaded. // // Sadly, Firefox and Opera are the only browsers capable of loading // scripts in parallel while preserving execution order. In all other // browsers, scripts must be loaded sequentially. // // All browsers respect CSS specificity based on the order of the link // elements in the DOM, regardless of the order in which the stylesheets // are actually downloaded. if (isCSS || env.async || env.gecko || env.opera) { // Load in parallel. queue[type].push({ urls : urls, callback: callback, obj : obj, context : context }); } else { // Load sequentially. for (i = 0, len = urls.length; i < len; ++i) { queue[type].push({ urls : [urls[i]], callback: i === len - 1 ? callback : null, // callback is only added to the last URL obj : obj, context : context }); } } } // If a previous load request of this type is currently in progress, we'll // wait our turn. Otherwise, grab the next item in the queue. if (pending[type] || !(p = pending[type] = queue[type].shift())) { return; } head || (head = doc.head || doc.getElementsByTagName('head')[0]); pendingUrls = p.urls.concat(); for (i = 0, len = pendingUrls.length; i < len; ++i) { url = pendingUrls[i]; if (isCSS) { node = env.gecko ? createNode('style') : createNode('link', { href: url, rel : 'stylesheet' }); } else { node = createNode('script', {src: url}); node.async = false; } node.className = 'lazyload'; node.setAttribute('charset', 'utf-8'); if (env.ie && !isCSS && 'onreadystatechange' in node && !('draggable' in node)) { node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; _finish(); } }; } else if (isCSS && (env.gecko || env.webkit)) { // Gecko and WebKit don't support the onload event on link nodes. if (env.webkit) { // In WebKit, we can poll for changes to document.styleSheets to // figure out when stylesheets have loaded. p.urls[i] = node.href; // resolve relative URLs (or polling won't work) pollWebKit(); } else { // In Gecko, we can import the requested URL into a <style> node and // poll for the existence of node.sheet.cssRules. Props to Zach // Leatherman for calling my attention to this technique. node.innerHTML = '@import "' + url + '";'; pollGecko(node); } } else { node.onload = node.onerror = _finish; } nodes.push(node); } for (i = 0, len = nodes.length; i < len; ++i) { head.appendChild(nodes[i]); } } /** Begins polling to determine when the specified stylesheet has finished loading in Gecko. Polling stops when all pending stylesheets have loaded or after 10 seconds (to prevent stalls). Thanks to Zach Leatherman for calling my attention to the @import-based cross-domain technique used here, and to Oleg Slobodskoi for an earlier same-domain implementation. See Zach's blog for more details: http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ @method pollGecko @param {HTMLElement} node Style node to poll. @private */ function pollGecko(node) { var hasRules; try { // We don't really need to store this value or ever refer to it again, but // if we don't store it, Closure Compiler assumes the code is useless and // removes it. hasRules = !!node.sheet.cssRules; } catch (ex) { // An exception means the stylesheet is still loading. pollCount += 1; if (pollCount < 200) { setTimeout(function () { pollGecko(node); }, 50); } else { // We've been polling for 10 seconds and nothing's happened. Stop // polling and finish the pending requests to avoid blocking further // requests. hasRules && finish('css'); } return; } // If we get here, the stylesheet has loaded. finish('css'); } /** Begins polling to determine when pending stylesheets have finished loading in WebKit. Polling stops when all pending stylesheets have loaded or after 10 seconds (to prevent stalls). @method pollWebKit @private */ function pollWebKit() { var css = pending.css, i; if (css) { i = styleSheets.length; // Look for a stylesheet matching the pending URL. while (--i >= 0) { if (styleSheets[i].href === css.urls[0]) { finish('css'); break; } } pollCount += 1; if (css) { if (pollCount < 200) { setTimeout(pollWebKit, 50); } else { // We've been polling for 10 seconds and nothing's happened, which may // indicate that the stylesheet has been removed from the document // before it had a chance to load. Stop polling and finish the pending // request to prevent blocking further requests. finish('css'); } } } } return { /** Requests the specified CSS URL or URLs and executes the specified callback (if any) when they have finished loading. If an array of URLs is specified, the stylesheets will be loaded in parallel and the callback will be executed after all stylesheets have finished loading. @method css @param {String|Array} urls CSS URL or array of CSS URLs to load @param {Function} callback (optional) callback function to execute when the specified stylesheets are loaded @param {Object} obj (optional) object to pass to the callback function @param {Object} context (optional) if provided, the callback function will be executed in this object's context @static */ css: function (urls, callback, obj, context) { load('css', urls, callback, obj, context); }, /** Requests the specified JavaScript URL or URLs and executes the specified callback (if any) when they have finished loading. If an array of URLs is specified and the browser supports it, the scripts will be loaded in parallel and the callback will be executed after all scripts have finished loading. Currently, only Firefox and Opera support parallel loading of scripts while preserving execution order. In other browsers, scripts will be queued and loaded one at a time to ensure correct execution order. @method js @param {String|Array} urls JS URL or array of JS URLs to load @param {Function} callback (optional) callback function to execute when the specified scripts are loaded @param {Object} obj (optional) object to pass to the callback function @param {Object} context (optional) if provided, the callback function will be executed in this object's context @static */ js: function (urls, callback, obj, context) { load('js', urls, callback, obj, context); } }; })(this.document);
from twitter_api.api import TwitterAPI from twitter_api.utils import Utils class Friends(TwitterAPI): """API 'friends/' フォロー関係のデータを取り扱うエンドポイント. * GET friends/ids 対象ユーザーがフォローしているユーザーを、IDの一覧で取得する。 * GET friends/list 対象ユーザーがフォローしているユーザーを、オブジェクトの一覧で取得する。 """ def __init__(self, consumer_key: str, consumer_secret: str, access_token: str, access_secret: str): super().__init__(consumer_key, consumer_secret, access_token, access_secret) self.GET = self._GET(self.api) self.POST = self._POST(self.api) # inner class for GET methods class _GET: def __init__(self, api): self.method = 'GET' self.api = api # inner class for POST methods class _POST: def __init__(self, api): self.method = 'POST' self.api = api
import numpy as np from Computer.NN_Trainer.NormalizationMethod import NormalizationMethod from sklearn.model_selection import train_test_split from random import random, shuffle def normalize_zero_to_one(xList): return np.divide(xList, 255) def normalize_negOne_to_one(xList): return np.subtract(np.divide(xList, 127.5), 1) def normalizeData(data, normalizationMethod): if(normalizationMethod.value == NormalizationMethod.zero_to_one.value): return normalize_zero_to_one(data) elif(normalizationMethod.value == NormalizationMethod.negOne_to_one.value): return normalize_negOne_to_one(data) elif(normalizationMethod.value == NormalizationMethod.none.value): return data else: raise ValueError("Unknown Value for NormalizationMethod, from Dataset.py > __normalizeData(),\n normalizationMethod={}".format(normalizationMethod)) def splitTrainTestVal(x, y, testVal_size): ''' splits data into train, test, and validation data sets :param x: input data :param y: output data :return: (x_train, x_test, x_val, _train, y_test, y_val) ''' x_train, x_testVal, y_train, y_testVal = train_test_split(x, y, test_size=testVal_size, random_state=42) x_test, x_val, y_test, y_val = train_test_split(x_testVal, y_testVal, test_size=0.5,random_state=53) # split the testVal into test and validation sets return x_train, x_test, x_val, y_train, y_test, y_val def splitTrainTest(x, y, test_size): x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_size, random_state=42) return x_train, x_test, y_train, y_test def getRandomSample(xList, yList, size): '''returns new_xList, new_yList''' if (len(xList) != len(yList)): # must be same size raise Exception else: max_index = random.randint(size, len( xList) - 1) # lower bound of max index is the size, and upperbound is the size of list return xList[max_index - size:max_index], yList[max_index - size:max_index] def convert_index_to_oneHotEncoded(index, length): onehot = np.zeros(length) onehot[index] = 1; return onehot def unzipXY(inputList): '''gets seperate list of images and seperate list of cmds from a list of (img,cmd)''' xList = list(zip(*inputList))[0] #unzip and get the first list in ilst (imgs) yList = list(zip(*inputList))[1] return xList, yList
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: Money.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='Money.proto', package='', syntax='proto3', serialized_options=None, create_key=_descriptor._internal_create_key, serialized_pb=b'\n\x0bMoney.proto\"O\n\x05Money\x12\x15\n\rcurrency_code\x18\x01 \x01(\t\x12\x17\n\x0fintegral_amount\x18\x02 \x01(\x03\x12\x16\n\x0e\x64\x65\x63imal_amount\x18\x03 \x01(\x05\x62\x06proto3' ) _MONEY = _descriptor.Descriptor( name='Money', full_name='Money', filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='currency_code', full_name='Money.currency_code', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='integral_amount', full_name='Money.integral_amount', index=1, number=2, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='decimal_amount', full_name='Money.decimal_amount', index=2, number=3, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=15, serialized_end=94, ) DESCRIPTOR.message_types_by_name['Money'] = _MONEY _sym_db.RegisterFileDescriptor(DESCRIPTOR) Money = _reflection.GeneratedProtocolMessageType('Money', (_message.Message,), { 'DESCRIPTOR' : _MONEY, '__module__' : 'Money_pb2' # @@protoc_insertion_point(class_scope:Money) }) _sym_db.RegisterMessage(Money) # @@protoc_insertion_point(module_scope)
const expect = require('chai').expect; const InspireTree = require('../../' + (process.env.DIST ? 'dist' : 'build') + '/inspire-tree'); describe('TreeNodes.prototype.context', function() { let tree; before(function() { // Create tree tree = new InspireTree({ data: [{ text: 'A', id: 1, children: [{ text: 'AA' }] }] }); }); it('exists', function() { expect(tree.nodes().context).to.be.a('function'); }); it('returns the tree as the root context', function() { expect(tree.nodes().context()).to.equal(tree); }); it('returns parent node for a child context', function() { const node = tree.node(1); expect(node.getChildren().context()).to.equal(node); }); });
const axios = require('axios'); const TestRailCache = require('./testrail-cache'); class TestRailApi { constructor(options) { this.options = options; this.base = `${this.options.host}/index.php?/api/v2`; this.runId; this.planId = this.options.planId } async createPlan(name, description, milestoneId) { var suiteIds = this.options.suiteIds; var entries = []; for (var i = 0; i < suiteIds.length; i++) { var entry = { suite_id: suiteIds[i], name: `${name} - Suite ${suiteIds[i]}`, include_all: true } entries.push(entry); } var data = { name: name, description: description, entries: entries }; if (milestoneId) { data['milestone_id'] = milestoneId; } try { var plan = await this._post('add_plan', this.options.projectId.toString(), data); this.planId = plan.id; } catch (e) { console.error(e); }; }; async createPlanEntry(name, description, testcaseIds) { var data = { suite_id: this.options.suiteId, name: name, description: description, assignedto_id: this.options.assignedToId, case_ids: testcaseIds, include_all: false, runs: [{ case_ids: testcaseIds, include_all: false }] }; try { var planEntry = await this._post('add_plan_entry', this.planId.toString(), data); this.runId = planEntry.runs[0].id; } catch (e) { console.error(e); }; }; async createRun(name, description, testcaseIds) { try { var run = await this._post('add_run', this.options.projectId.toString(), { suite_id: this.options.suiteId, name: name, description: description, assignedto_id: this.options.assignedToId, include_all: false, case_ids: testcaseIds }); this.runId = run.id; } catch (e) { console.error(e); } }; async deleteReport() { try { if (this.options.usePlan === true) { await this._post('delete_plan', this.planId.toString()); } else { await this._post('delete_run', this.runId.toString()); } } catch (e) { console.error(e); }; }; async publishResults(results) { try { await this._post('add_results_for_cases', this.runId.toString(), { results: results }); } catch (e) { console.error(e); }; }; /** * sends a GET request to TestRail's API with the passed in action and urlData * @param {String} action the URL path to be appended to the Base * @param {String} urlData the additional URL variables to be included */ async _get(action, urlData) { return await this._makeRequest('GET', action, urlData); }; /** * sends a POST request to TestRail's API with the passed in action and urlData and a request * body from the serialised data * @param {String} action the URL path to be appended to the Base * @param {String} urlData the additional URL variables to be included * @param {any} data a JavaScript object to be serialised out and sent with the request */ async _post(action, urlData, data) { return await this._makeRequest('POST', action, urlData, data); }; _getAuth() { return { username: this.options.username, password: this.options.password, }; }; _getHeaders() { return { 'Content-Type': 'application/json' }; }; async _makeRequest(method, action, urlData, data) { var config = { // AxiosRequestConfig method: method, url: `${this.base}/${action}/${urlData}`, headers: this._getHeaders(), auth: this._getAuth() }; if (data) { config['data'] = JSON.stringify(data); } var responseObj; try { var resp = await axios(config); if (resp.data && resp.data.error) { if (new String(resp.data.error).includes('API Rate Limit Exceeded')) { // API RATE LIMIT REACHED: wait one minute and then retry request console.log('TestRail API Rate Limit reached: waiting one minute and then retrying request...') await new Promise((resolve, reject) => { setTimeout(resolve, 60000); }); responseObj = await this._makeRequest(method, action, urlData, data); } else { throw new Error(resp.data.error); } } else { responseObj = resp.data; } } catch (e) { console.error(e); } return responseObj; }; } module.exports = TestRailApi;
""" Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch) @author: tstandley Adapted by cadene Creates an Xception Model as defined in: Francois Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Keras implementation. Achieves the following performance on the validation set: Loss:0.9173 Prec@1:78.892 Prec@5:94.292 REMEMBER to set your image size to 3x299x299 for both test and validation normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) The resize parameter of the validation transform should be 333, and make sure to center crop at 299x299 """ from __future__ import print_function, division, absolute_import import math import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo from torch.nn import init __all__ = ['xception'] pretrained_settings = { 'xception': { 'imagenet': { 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/xception-b5690688.pth', 'input_space': 'RGB', 'input_size': [3, 299, 299], 'input_range': [0, 1], 'mean': [0.5, 0.5, 0.5], 'std': [0.5, 0.5, 0.5], 'num_classes': 1000, 'scale': 0.8975 # The resize parameter of the validation transform should be 333, and make sure to center crop at 299x299 } } } class SeparableConv2d(nn.Module): def __init__(self,in_channels,out_channels,kernel_size=1,stride=1,padding=0,dilation=1,bias=False): super(SeparableConv2d,self).__init__() self.conv1 = nn.Conv2d(in_channels,in_channels,kernel_size,stride,padding,dilation,groups=in_channels,bias=bias) self.pointwise = nn.Conv2d(in_channels,out_channels,1,1,0,1,1,bias=bias) def forward(self,x): x = self.conv1(x) x = self.pointwise(x) return x class Block(nn.Module): def __init__(self,in_filters,out_filters,reps,strides=1,start_with_relu=True,grow_first=True): super(Block, self).__init__() if out_filters != in_filters or strides!=1: self.skip = nn.Conv2d(in_filters,out_filters,1,stride=strides, bias=False) self.skipbn = nn.BatchNorm2d(out_filters) else: self.skip=None self.relu = nn.ReLU(inplace=True) rep=[] filters=in_filters if grow_first: rep.append(self.relu) rep.append(SeparableConv2d(in_filters,out_filters,3,stride=1,padding=1,bias=False)) rep.append(nn.BatchNorm2d(out_filters)) filters = out_filters for i in range(reps-1): rep.append(self.relu) rep.append(SeparableConv2d(filters,filters,3,stride=1,padding=1,bias=False)) rep.append(nn.BatchNorm2d(filters)) if not grow_first: rep.append(self.relu) rep.append(SeparableConv2d(in_filters,out_filters,3,stride=1,padding=1,bias=False)) rep.append(nn.BatchNorm2d(out_filters)) if not start_with_relu: rep = rep[1:] else: rep[0] = nn.ReLU(inplace=False) if strides != 1: rep.append(nn.MaxPool2d(3,strides,1)) self.rep = nn.Sequential(*rep) def forward(self,inp): x = self.rep(inp) if self.skip is not None: skip = self.skip(inp) skip = self.skipbn(skip) else: skip = inp x+=skip return x class Xception(nn.Module): """ Xception optimized for the ImageNet dataset, as specified in https://arxiv.org/pdf/1610.02357.pdf """ def __init__(self, num_classes=1000): """ Constructor Args: num_classes: number of classes """ super(Xception, self).__init__() self.num_classes = num_classes self.conv1 = nn.Conv2d(3, 32, 3,2, 0, bias=False) self.bn1 = nn.BatchNorm2d(32) self.relu = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(32,64,3,bias=False) self.bn2 = nn.BatchNorm2d(64) #do relu here self.block1=Block(64,128,2,2,start_with_relu=False,grow_first=True) self.block2=Block(128,256,2,2,start_with_relu=True,grow_first=True) self.block3=Block(256,728,2,2,start_with_relu=True,grow_first=True) self.block4=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block5=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block6=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block7=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block8=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block9=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block10=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block11=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block12=Block(728,1024,2,2,start_with_relu=True,grow_first=False) self.conv3 = SeparableConv2d(1024,1536,3,1,1) self.bn3 = nn.BatchNorm2d(1536) #do relu here self.conv4 = SeparableConv2d(1536,2048,3,1,1) self.bn4 = nn.BatchNorm2d(2048) self.fc = nn.Linear(2048, num_classes) # #------- init weights -------- # for m in self.modules(): # if isinstance(m, nn.Conv2d): # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels # m.weight.data.normal_(0, math.sqrt(2. / n)) # elif isinstance(m, nn.BatchNorm2d): # m.weight.data.fill_(1) # m.bias.data.zero_() # #----------------------------- def features(self, input): x = self.conv1(input) x = self.bn1(x) x = self.relu(x) x = self.conv2(x) x = self.bn2(x) x = self.relu(x) x = self.block1(x) x = self.block2(x) x = self.block3(x) x = self.block4(x) x = self.block5(x) x = self.block6(x) x = self.block7(x) x = self.block8(x) x = self.block9(x) x = self.block10(x) x = self.block11(x) x = self.block12(x) x = self.conv3(x) x = self.bn3(x) x = self.relu(x) x = self.conv4(x) x = self.bn4(x) return x def logits(self, features): x = self.relu(features) x = F.adaptive_avg_pool2d(x, (1, 1)) x = x.view(x.size(0), -1) x = self.last_linear(x) return x def forward(self, input): x = self.features(input) x = self.logits(x) return x def xception(num_classes=1000, pretrained='imagenet'): model = Xception(num_classes=num_classes) if pretrained: settings = pretrained_settings['xception'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model = Xception(num_classes=num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] # TODO: ugly model.last_linear = model.fc del model.fc return model
function Util(){}if(Util.hasClass=function(e,t){return e.classList.contains(t)},Util.addClass=function(e,t){var n=t.split(" ");e.classList.add(n[0]),1<n.length&&Util.addClass(e,n.slice(1).join(" "))},Util.removeClass=function(e,t){var n=t.split(" ");e.classList.remove(n[0]),1<n.length&&Util.removeClass(e,n.slice(1).join(" "))},Util.toggleClass=function(e,t,n){n?Util.addClass(e,t):Util.removeClass(e,t)},Util.setAttributes=function(e,t){for(var n in t)e.setAttribute(n,t[n])},Util.getChildrenByClassName=function(e,t){for(var n=e.children,o=[],s=0;s<n.length;s++)Util.hasClass(n[s],t)&&o.push(n[s]);return o},Util.is=function(e,t){if(t.nodeType)return e===t;for(var n="string"==typeof t?document.querySelectorAll(t):t,o=n.length;o--;)if(n[o]===e)return!0;return!1},Util.setHeight=function(o,s,i,r,l,a){var c=s-o,d=null,u=function(e){d||(d=e);var t=e-d;r<t&&(t=r);var n=parseInt(t/r*c+o);a&&(n=Math[a](t,o,s-o,r)),i.style.height=n+"px",t<r?window.requestAnimationFrame(u):l&&l()};i.style.height=o+"px",window.requestAnimationFrame(u)},Util.scrollTo=function(o,s,i,e){var r=e||window,l=r.scrollTop||document.documentElement.scrollTop,a=null;e||(l=window.scrollY||document.documentElement.scrollTop);var c=function(e){a||(a=e);var t=e-a;s<t&&(t=s);var n=Math.easeInOutQuad(t,l,o-l,s);r.scrollTo(0,n),t<s?window.requestAnimationFrame(c):i&&i()};window.requestAnimationFrame(c)},Util.moveFocus=function(e){e||(e=document.getElementsByTagName("body")[0]),e.focus(),document.activeElement!==e&&(e.setAttribute("tabindex","-1"),e.focus())},Util.getIndexInArray=function(e,t){return Array.prototype.indexOf.call(e,t)},Util.cssSupports=function(e,t){return"CSS"in window?CSS.supports(e,t):e.replace(/-([a-z])/g,function(e){return e[1].toUpperCase()})in document.body.style},Util.extend=function(){var n={},o=!1,e=0,t=arguments.length;"[object Boolean]"===Object.prototype.toString.call(arguments[0])&&(o=arguments[0],e++);for(var s=function(e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&(o&&"[object Object]"===Object.prototype.toString.call(e[t])?n[t]=extend(!0,n[t],e[t]):n[t]=e[t])};e<t;e++){s(arguments[e])}return n},Util.osHasReducedMotion=function(){if(!window.matchMedia)return!1;var e=window.matchMedia("(prefers-reduced-motion: reduce)");return!!e&&e.matches},Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){var t=this;if(!document.documentElement.contains(t))return null;do{if(t.matches(e))return t;t=t.parentElement||t.parentNode}while(null!==t&&1===t.nodeType);return null}),"function"!=typeof window.CustomEvent){function CustomEvent(e,t){t=t||{bubbles:!1,cancelable:!1,detail:void 0};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),n}CustomEvent.prototype=window.Event.prototype,window.CustomEvent=CustomEvent}function resetFocusTabsStyle(){window.dispatchEvent(new CustomEvent("initFocusTabs"))}Math.easeInOutQuad=function(e,t,n,o){return(e/=o/2)<1?n/2*e*e+t:-n/2*(--e*(e-2)-1)+t},Math.easeInQuart=function(e,t,n,o){return n*(e/=o)*e*e*e+t},Math.easeOutQuart=function(e,t,n,o){return e/=o,-n*(--e*e*e*e-1)+t},Math.easeInOutQuart=function(e,t,n,o){return(e/=o/2)<1?n/2*e*e*e*e+t:-n/2*((e-=2)*e*e*e-2)+t},Math.easeOutElastic=function(e,t,n,o){var s=1.70158,i=.7*o,r=n;if(0==e)return t;if(1==(e/=o))return t+n;if(i||(i=.3*o),r<Math.abs(n)){r=n;s=i/4}else s=i/(2*Math.PI)*Math.asin(n/r);return r*Math.pow(2,-10*e)*Math.sin((e*o-s)*(2*Math.PI)/i)+n+t},function(){var o=document.getElementsByClassName("js-tab-focus"),e=!1,t=!1,n=!1;function s(){0<o.length&&(r(!1),window.addEventListener("keydown",i)),window.removeEventListener("mousedown",s),n=!(t=!1)}function i(e){9===e.keyCode&&(r(!0),window.removeEventListener("keydown",i),window.addEventListener("mousedown",s),t=!0)}function r(e){for(var t=e?"":"none",n=0;n<o.length;n++)o[n].style.setProperty("outline",t)}function l(){e?n&&r(t):(e=0<o.length,window.addEventListener("mousedown",s))}l(),window.addEventListener("initFocusTabs",l)}(),function(){var e=function(e){this.element=e,this.select=this.element.getElementsByTagName("select")[0],this.optGroups=this.select.getElementsByTagName("optgroup"),this.options=this.select.getElementsByTagName("option"),this.selectedOption=function(e){var t="";t="selectedIndex"in e.select?e.options[e.select.selectedIndex].text:e.select.querySelector("option[selected]").text;return t}(this),this.selectId=this.select.getAttribute("id"),this.trigger=!1,this.dropdown=!1,this.customOptions=!1,this.arrowIcon=this.element.getElementsByTagName("svg"),this.label=document.querySelector('[for="'+this.selectId+'"]'),this.optionIndex=0,function(e){e.element.insertAdjacentHTML("beforeend",function(e){var t=e.element.getAttribute("data-trigger-class")?" "+e.element.getAttribute("data-trigger-class"):"",n=e.options[e.select.selectedIndex].innerHTML+", "+e.label.textContent,o='<button type="button" class="js-select__button select__button'+t+'" aria-label="'+n+'" aria-expanded="false" aria-controls="'+e.selectId+'-dropdown"><span aria-hidden="true" class="js-select__label select__label">'+e.selectedOption+"</span>";if(0<e.arrowIcon.length&&e.arrowIcon[0].outerHTML){var s=e.arrowIcon[0].cloneNode(!0);Util.removeClass(s,"select__icon"),o+=s.outerHTML}return o+"</button>"}(e)+function(e){var t,n='<div class="js-select__dropdown select__dropdown" aria-describedby="'+e.selectId+'-description" id="'+e.selectId+'-dropdown">';if(n+=(t=e).label?'<p class="sr-only" id="'+t.selectId+'-description">'+t.label.textContent+"</p>":"",0<e.optGroups.length)for(var o=0;o<e.optGroups.length;o++){var s=e.optGroups[o].getElementsByTagName("option"),i='<li><span class="select__item select__item--optgroup">'+e.optGroups[o].getAttribute("label")+"</span></li>";n=n+'<ul class="select__list" role="listbox">'+i+l(e,s)+"</ul>"}else n=n+'<ul class="select__list" role="listbox">'+l(e,e.options)+"</ul>";return n}(e)),e.dropdown=e.element.getElementsByClassName("js-select__dropdown")[0],e.trigger=e.element.getElementsByClassName("js-select__button")[0],e.customOptions=e.dropdown.getElementsByClassName("js-select__item"),Util.addClass(e.select,"is-hidden"),0<e.arrowIcon.length&&(e.arrowIcon[0].style.display="none");i(e)}(this),function(t){n=t,n.dropdown.addEventListener("click",function(e){var t=e.target.closest(".js-select__item");t&&function(e,t){if(t.hasAttribute("aria-selected")&&"true"==t.getAttribute("aria-selected"))e.trigger.setAttribute("aria-expanded","false");else{var n=e.dropdown.querySelector('[aria-selected="true"]');n&&n.setAttribute("aria-selected","false"),t.setAttribute("aria-selected","true"),e.trigger.getElementsByClassName("js-select__label")[0].textContent=t.textContent,e.trigger.setAttribute("aria-expanded","false"),o=e,s=t.getAttribute("data-index"),o.select.selectedIndex=s,o.select.dispatchEvent(new CustomEvent("change",{bubbles:!0})),r(e)}var o,s;e.trigger.focus()}(n,t)}),t.trigger.addEventListener("click",function(){s(t,!1)}),t.label&&t.label.addEventListener("click",function(){Util.moveFocus(t.trigger)});var n;t.dropdown.addEventListener("keydown",function(e){e.keyCode&&38==e.keyCode||e.key&&"arrowup"==e.key.toLowerCase()?o(t,"prev",e):(e.keyCode&&40==e.keyCode||e.key&&"arrowdown"==e.key.toLowerCase())&&o(t,"next",e)}),t.element.addEventListener("select-updated",function(e){!function(e){var t=e.dropdown.querySelector('[aria-selected="true"]');t&&t.setAttribute("aria-selected","false");var n=e.dropdown.querySelector('.js-select__item[data-index="'+e.select.selectedIndex+'"]');n.setAttribute("aria-selected","true"),e.trigger.getElementsByClassName("js-select__label")[0].textContent=n.textContent,e.trigger.setAttribute("aria-expanded","false"),r(e)}(t)})}(this)};function s(t,e){var n,o;if(n=e||("true"==t.trigger.getAttribute("aria-expanded")?"false":"true"),t.trigger.setAttribute("aria-expanded",n),"true"==n){var s=(o=t).dropdown.querySelector('[aria-selected="true"]')||o.dropdown.getElementsByClassName("js-select__item")[0];Util.moveFocus(s),t.dropdown.addEventListener("transitionend",function e(){Util.moveFocus(s),t.dropdown.removeEventListener("transitionend",e)}),i(t)}}function i(e){Util.removeClass(e.dropdown,"select__dropdown--right select__dropdown--up");var t=e.trigger.getBoundingClientRect();Util.toggleClass(e.dropdown,"select__dropdown--right",document.documentElement.clientWidth-5<t.left+e.dropdown.offsetWidth);var n=window.innerHeight-t.bottom-5<t.top;Util.toggleClass(e.dropdown,"select__dropdown--up",n);var o=n?t.top-20:window.innerHeight-t.bottom-20;e.dropdown.setAttribute("style","max-height: "+o+"px; width: "+t.width+"px;")}function o(e,t,n){n.preventDefault();var o=Util.getIndexInArray(e.customOptions,document.activeElement);(o="next"==t?o+1:o-1)<0&&(o=e.customOptions.length-1),o>=e.customOptions.length&&(o=0),Util.moveFocus(e.customOptions[o])}function r(e){e.trigger.setAttribute("aria-label",e.options[e.select.selectedIndex].innerHTML+", "+e.label.textContent)}function l(e,t){for(var n="",o=0;o<t.length;o++){var s=t[o].hasAttribute("selected")?' aria-selected="true"':' aria-selected="false"';n=n+'<li><button type="button" class="reset js-select__item select__item select__item--option" role="option" data-value="'+t[o].value+'" '+s+' data-index="'+e.optionIndex+'">'+t[o].text+"</button></li>",e.optionIndex=e.optionIndex+1}return n}var t,n=document.getElementsByClassName("js-select");if(0<n.length){for(var a=[],c=0;c<n.length;c++)t=c,a.push(new e(n[t]));window.addEventListener("keyup",function(e){(e.keyCode&&27==e.keyCode||e.key&&"escape"==e.key.toLowerCase())&&a.forEach(function(e){var t;t=e,document.activeElement.closest(".js-select")&&t.trigger.focus(),s(e,"false")})}),window.addEventListener("click",function(o){a.forEach(function(e){var t,n;t=e,n=o.target,t.element.contains(n)||s(t,"false")})})}}(),function(){function n(e){var t=getComputedStyle(e,":before").getPropertyValue("content").replace(/\'|"/g,"");Util.toggleClass(e,s,"collapsed"!=t)}var o=document.getElementsByClassName("js-table"),s="table--expanded";if(0<o.length){for(var e=0,i=0;i<o.length;i++){var t=getComputedStyle(o[i],":before").getPropertyValue("content");t&&""!=t&&"none"!=t?(!function(e){var t;n(t=o[i]),Util.addClass(t,"table--loaded"),t.addEventListener("update-table",function(e){n(t)})}(),e+=1):Util.addClass(o[i],"table--loaded")}if(0<e){var r=!1,l=new CustomEvent("update-table");function a(){for(var e=0;e<o.length;e++)o[e].dispatchEvent(l)}window.addEventListener("resize",function(e){clearTimeout(r),r=setTimeout(a,300)}),window.requestAnimationFrame?window.requestAnimationFrame(a):a()}}}(),function(){var e=function(e){this.element=e,this.triggers=document.querySelector(".style-guide__header-control"),this.list=this.element.getElementsByClassName("style-guide__nav-list")[0],this.anchors=this.list.querySelectorAll('a[href^="#"]'),this.indicator=this.element.getElementsByClassName("style-guide__nav-indicator")[0],this.sections=function(e){for(var t=[],n=0;n<e.anchors.length;n++){var o=document.getElementById(e.anchors[n].getAttribute("href").replace("#",""));o&&t.push(o)}return t}(this),this.firstFocusable=this.element.querySelector("[href]"),this.selectedTrigger=null,this.showClass="style-guide__header--is-visible",this.clickScrolling=!1,this.intervalID=!1,this.select=document.getElementById("select-theme"),this.main=document.getElementsByClassName("style-guide")[0],function(t){o=t,o.triggers&&(o.triggers.addEventListener("click",function(e){var n,t;o.element.classList.contains(o.showClass)?r(o,e):(n=o,(t=e).preventDefault(),n.selectedTrigger=n.triggers,t.target.setAttribute("aria-expanded","true"),n.element.classList.add(n.showClass),n.firstFocusable.focus(),n.element.addEventListener("transitionend",function e(t){n.element.removeEventListener("transitionend",e),n.firstFocusable.focus()}))}),window.addEventListener("keyup",function(e){(e.keyCode&&27==e.keyCode||e.key&&"escape"==e.key.toLowerCase())&&r(o,e),(e.keyCode&&9==e.keyCode||e.key&&"tab"==e.key.toLowerCase())&&(document.activeElement.closest(".style-guide__header")||r(o,e,!0))})),i=t,l(i,i.anchors[0]),i.list.addEventListener("click",function(e){var t,n,o,s=e.target.closest('a[href^="#"]');s&&!s.classList.contains("style-guide__nav-link--current")&&(i.clickScrolling?e.preventDefault():(i.clickScrolling=!0,l(i,s),r(i,!1,!0),t=document.documentElement.offsetHeight,n=window.innerHeight,o=window.scrollY||window.pageYOffset||document.body.scrollTop+(document.documentElement&&document.documentElement.scrollTop||0),t-2<=n+o&&window.dispatchEvent(new CustomEvent("scroll"))))}),a&&function(n){for(var e=new IntersectionObserver(function(e,t){e.forEach(function(e){n.clickScrolling||s(n)})},{rootMargin:"0px 0px -50% 0px"}),t=0;t<n.sections.length;t++)e.observe(n.sections[t]);n.element.addEventListener("fixed-nav-scroll",function(e){n.clickScrolling||s(n),n.clickScrolling=!1})}(t);var i;var o;t.select.addEventListener("change",function(e){t.main.setAttribute("data-theme",t.select.options[t.select.selectedIndex].value)})}(this)};function r(e,t,n){e.element.classList.contains(e.showClass)&&(t&&t.preventDefault(),e.element.classList.remove(e.showClass),e.selectedTrigger&&(e.selectedTrigger.setAttribute("aria-expanded","false"),n||e.selectedTrigger.focus(),e.selectedTrigger=!1))}function l(e,t){if(a){for(var n=0;n<e.anchors.length;n++)e.anchors[n].classList.remove("style-guide__nav-link--current");var o;t&&(t.classList.add("style-guide__nav-link--current"),o=t,e.indicator.style.transform="translateX("+o.offsetLeft+"px) scaleX("+o.offsetWidth+")")}}function s(o){o.intervalID||(o.intervalID=setTimeout(function(){for(var e=window.innerHeight/2,t=-1,n=0;n<o.sections.length;n++){o.sections[n].getBoundingClientRect().top<e&&(t=n)}-1<t&&l(o,o.anchors[t]),o.intervalID=!1},100))}var t,n=document.getElementsByClassName("style-guide__header"),a="IntersectionObserver"in window&&"IntersectionObserverEntry"in window&&"intersectionRatio"in window.IntersectionObserverEntry.prototype,o=[];if(0<n.length){for(var i=0;i<n.length;i++)t=i,o.push(new e(n[t]));var c=!1,d=new CustomEvent("fixed-nav-scroll");function u(){for(var e=0;e<o.length;e++)o[e].element.dispatchEvent(d)}window.addEventListener("scroll",function(){clearTimeout(c),c=setTimeout(u,100)})}}();
angular.module('adminApp').directive('defaultDatatable', function ($compile) { return { restrict: 'E', scope: { id: '=', ctrl: '=' }, template: '<div></div>', link: function ($scope, element, attrs) { let temp = `<table id="` + $scope.id + `" datatable="" dt-options="ctrl.dtOptions" dt-columns="ctrl.dtColumns" dt-instance="ctrl.dtInstance" class="table table-bordered table-striped"></table>`; $(element).html($compile(temp)($scope)) } }; });
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from flask import Flask, request, render_template, send_from_directory, jsonify, session, send_file from werkzeug.utils import secure_filename from flask_cors import CORS import argparse from os import path as osp import os import time import json import sys import multiprocessing as mp from . import workspace_pb2 as w from .utils import CustomEncoder, ShareData, is_pic, get_logger, TaskStatus, get_ip from paddlex_restful.restful.dataset.utils import get_encoding import numpy as np app = Flask(__name__) CORS(app, supports_credentials=True) SESSION_TYPE = 'filesystem' app.config.from_object(__name__) SD = ShareData() def init(dirname, logger): #初始化工作空间 from .workspace import init_workspace from .system import get_system_info SD.workspace = w.Workspace(path=dirname) init_workspace(SD.workspace, dirname, logger) SD.workspace_dir = dirname get_system_info(SD.machine_info) @app.errorhandler(Exception) def handle_exception(e): ret = {"status": -1, 'message': repr(e)} return ret @app.route('/workspace', methods=['GET', 'PUT']) def workspace(): """ methods=='GET':获取工作目录中项目、数据集、任务的属性 Args: struct(str):结构类型,可以是'dataset', 'project'或'task', id(str):结构类型对应的id attr_list(list):需要获取的属性的列表 Return: attr(dict):key为属性,value为属性的值, status methods=='PUT':修改工作目录中项目、数据集、任务的属性 Args: struct(str):结构类型,可以是'dataset', 'project'或'task', id(str):结构类型对应的id attr_dict(dict):key:需要修改的属性,value:需要修改属性的值 Return: status """ data = request.get_json() if data is None: data = request.args if request.method == 'GET': if data: from .workspace import get_attr ret = get_attr(data, SD.workspace) return ret return {'status': 1, 'dirname': SD.workspace_dir} if request.method == 'PUT': from .workspace import set_attr ret = set_attr(data, SD.workspace) return ret @app.route('/dataset', methods=['GET', 'POST', 'PUT', 'DELETE']) def dataset(): """ methods=='GET':获取所有数据集或者单个数据集的信息 Args: did(str, optional):数据集id(可选),如果存在就返回数据集id对应数据集的信息 Ruturn: status if 'did' in Args: id(str):数据集id, dataset_status(int):数据集状态(DatasetStatus)枚举变量的值 message(str):数据集状态信息 attr(dict):数据集属性 else: datasets(list):所有数据集属性的列表 methods=='POST':创建一个新的数据集 Args: name(str):数据集名字 desc(str):数据集描述 dataset_type(str):数据集类型,可以是['classification', 'detection', 'segmentation','instance_segmentation','remote_segmentation'] Return: did(str):数据集id status methods=='PUT':异步,向数据集导入数据,支持分类、检测、语义分割、实例分割、摇杆分割数据集类型 Args: did(str):数据集id path(str):数据集路径 Return: status methods=='DELETE':删除已有的某个数据集 Args: did(str):数据集id Return: status """ data = request.get_json() if data is None: data = request.args if request.method == 'GET': if 'did' in data: from .dataset.dataset import get_dataset_status ret = get_dataset_status(data, SD.workspace) return ret from .dataset.dataset import list_datasets ret = list_datasets(SD.workspace) return ret if request.method == 'POST': from .dataset.dataset import create_dataset ret = create_dataset(data, SD.workspace) return ret if request.method == 'PUT': from .dataset.dataset import import_dataset ret = import_dataset(data, SD.workspace, SD.monitored_processes, SD.load_demo_proc_dict) return ret if request.method == 'DELETE': from .dataset.dataset import delete_dataset ret = delete_dataset(data, SD.workspace) return ret @app.route('/dataset/details', methods=['GET']) def dataset_details(): """ methods=='GET':获取某个数据集的详细信息 Args: did(str):数据集id Return: details(dict):数据集详细信息, status """ data = request.get_json() if data is None: data = request.args if request.method == 'GET': from .dataset.dataset import get_dataset_details ret = get_dataset_details(data, SD.workspace) return ret @app.route('/dataset/split', methods=['PUT']) def dataset_split(): """ Args: did(str):数据集id val_split(float): 验证集比例 test_split(float): 测试集比例 Return: status """ data = request.get_json() if request.method == 'PUT': from .dataset.dataset import split_dataset ret = split_dataset(data, SD.workspace) return ret @app.route('/dataset/image', methods=['GET']) def dataset_img_base64(): """ Args: GET: 获取图片base64数据,参数:'path' 图片绝对路径 """ data = request.get_json() if request.method == 'GET': from .dataset.dataset import img_base64 ret = img_base64(data) return ret @app.route('/dataset/file', methods=['GET']) def get_image_file(): """ Args: GET: 获取文件数据,参数:'path' 文件绝对路径 """ data = request.get_json() if request.method == 'GET': ret = data['path'] assert os.path.abspath(ret).startswith( os.path.abspath(SD.workspace_dir) ) and ".." not in ret, "Illegal path {}.".format(ret) return send_file(ret) @app.route('/dataset/npy', methods=['GET']) def get_npyfile(): """ Args: GET: 获取文件数据,参数:'path' npy文件绝对路径 """ data = request.get_json() if request.method == 'GET': npy = np.load(data['path'], allow_pickle=True).tolist() npy['gt_bbox'] = npy['gt_bbox'].tolist() return npy @app.route('/file', methods=['GET']) def get_file(): """ Args: path'(str):文件在服务端的路径 Return: #数据为图片 img_data(str): base64图片数据 status #数据为xml文件 ret:数据流 #数据为log文件 ret:json数据 """ data = request.get_json() if data is None: data = request.args if request.method == 'GET': path = data['path'] if not os.path.exists(path): return {'status': -1} if is_pic(path): from .dataset.dataset import img_base64 ret = img_base64(data, SD.workspace) return ret file_type = path[(path.rfind('.') + 1):] if file_type in ['xml', 'npy', 'log']: return send_file(path) else: pass @app.route('/project', methods=['GET', 'POST', 'DELETE']) def project(): """ methods=='GET':获取指定项目id的信息 Args: 'id'(str, optional):项目id,可选,如果存在就返回项目id对应项目的信息 Return: status, if 'id' in Args: attr(dict):项目属性 else: projects(list):所有项目属性 methods=='POST':创建一个项目 Args: name(str): 项目名 desc(str):项目描述 project_type(str):项目类型 Return: pid(str):项目id status methods=='DELETE':删除一个项目,以及项目相关的task Args: pid(str):项目id Return: status """ data = request.get_json() if data is None: data = request.args if request.method == 'GET': from .project.project import list_projects from .project.project import get_project if 'id' in data: ret = get_project(data, SD.workspace) return ret ret = list_projects(SD.workspace) return ret if request.method == 'POST': from .project.project import create_project ret = create_project(data, SD.workspace) return ret if request.method == 'DELETE': from .project.project import delete_project ret = delete_project(data, SD.workspace) return ret @app.route('/project/task', methods=['GET', 'POST', 'DELETE']) def task(): """ methods=='GET':#获取某个任务的信息或者所有任务的信息 Args: tid(str, optional):任务id,可选,若存在即返回id对应任务的信息 resume(str, optional):获取是否可以恢复训练的状态,可选,需在存在tid的情况下才生效 pid(str, optional):项目id,可选,若存在即返回该项目id下所有任务信息 Return: status if 'tid' in Args: task_status(int):任务状态(TaskStatus)枚举变量的值 message(str):任务状态信息 type:任务类型包括{'classification', 'detection', 'segmentation', 'instance_segmentation'} resumable(bool):仅Args中存在resume时返回,任务训练是否可以恢复 max_saved_epochs(int):仅Args中存在resume时返回,当前训练模型保存的最大epoch else: tasks(list):所有任务属性 methods=='POST':#创建任务(训练或者裁剪) Args: pid(str):项目id train(dict):训练参数 desc(str, optional):任务描述,可选 parent_id(str, optional):可选,若存在即表示新建的任务为裁剪任务,parent_id的值为裁剪任务对应的训练任务id Return: tid(str):任务id status methods=='DELETE':#删除任务 Args: tid(str):任务id Return: status """ data = request.get_json() if data is None: data = request.args if request.method == 'GET': if data: if 'pid' not in data: from .project.task import get_task_status ret = get_task_status(data, SD.workspace) return ret from .project.task import list_tasks ret = list_tasks(data, SD.workspace) return ret if request.method == 'POST': from .project.task import create_task ret = create_task(data, SD.workspace) return ret if request.method == 'DELETE': from .project.task import delete_task ret = delete_task(data, SD.workspace) return ret @app.route('/project/task/params', methods=['GET', 'POST']) def task_params(): """ methods=='GET':#获取任务id对应的参数,或者获取项目默认参数 Args: tid(str, optional):获取任务对应的参数 pid(str,optional):获取项目对应的默认参数 model_type(str,optional):pid存在下有效,对应项目下获取指定模型的默认参数 gpu_list(list,optional):pid存在下有效,默认值为[0],使用指定的gpu并获取相应的默认参数 Return: train(dict):训练或者裁剪的参数 status methods=='POST':#设置任务参数,将前端用户设置训练参数dict保存在后端的pkl文件中 Args: tid(str):任务id train(dict):训练参数 Return: status """ data = request.get_json() if data is None: data = request.args if request.method == 'GET': if 'tid' in data: from .project.task import get_task_params ret = get_task_params(data, SD.workspace) ret['train'] = CustomEncoder().encode(ret['train']) ret['train'] = json.loads(ret['train']) return ret if 'pid' in data: from .project.task import get_default_params ret = get_default_params(data, SD.workspace, SD.machine_info) return ret if request.method == 'POST': from .project.task import set_task_params ret = set_task_params(data, SD.workspace) return ret @app.route('/project/task/metrics', methods=['GET']) def task_metrics(): """ methods=='GET':#获取日志数据 Args: tid(str):任务id type(str):可以获取日志的类型,[train,eval,sensitivities,prune],包括训练,评估,敏感度与模型裁剪率关系图,裁剪的日志 Return: status if type == 'train': train_log(dict): 训练日志 elif type == 'eval': eval_metrics(dict): 评估结果 elif type == 'sensitivities': sensitivities_loss_img(dict): 敏感度与模型裁剪率关系图 elif type == 'prune': prune_log(dict):裁剪日志 """ data = request.get_json() if data is None: data = request.args if request.method == 'GET': if data['type'] == 'train': from .project.task import get_train_metrics ret = get_train_metrics(data, SD.workspace) return ret if data['type'] == 'eval': from .project.task import get_eval_metrics ret = get_eval_metrics(data, SD.workspace) return ret if data['type'] == 'eval_all': from .project.task import get_eval_all_metrics ret = get_eval_all_metrics(data, SD.workspace) return ret if data['type'] == 'sensitivities': from .project.task import get_sensitivities_loss_img ret = get_sensitivities_loss_img(data, SD.workspace) return ret if data['type'] == 'prune': from .project.task import get_prune_metrics ret = get_prune_metrics(data, SD.workspace) return ret @app.route('/project/task/train', methods=['POST', 'PUT']) def task_train(): """ methods=='POST':#异步,启动训练或者裁剪任务 Args: tid(str):任务id eval_metric_loss(int,optional):可选,裁剪任务时可用,裁剪任务所需的评估loss Return: status methods=='PUT':#改变任务训练的状态,即终止训练或者恢复训练 Args: tid(str):任务id act(str):[stop,resume]暂停或者恢复 epoch(int):(resume下可以设置)恢复训练的起始轮数 Return: status """ data = request.get_json() if request.method == 'POST': from .project.task import start_train_task ret = start_train_task(data, SD.workspace, SD.monitored_processes) return ret if request.method == 'PUT': if data['act'] == 'resume': from .project.task import resume_train_task ret = resume_train_task(data, SD.workspace, SD.monitored_processes) return ret if data['act'] == 'stop': from .project.task import stop_train_task ret = stop_train_task(data, SD.workspace) return ret @app.route('/project/task/train/file', methods=['GET']) def log_file(): data = request.get_json() if request.method == 'GET': path = data['path'] if not os.path.exists(path): return {'status': -1} logs = open(path, encoding='utf-8').readlines() if len(logs) < 50: return {'status': 1, 'log': logs} else: logs = logs[-50:] return {'status': 1, 'log': logs} @app.route('/project/task/prune', methods=['GET', 'POST', 'PUT']) def task_prune(): """ methods=='GET':#获取裁剪任务的状态 Args: tid(str):任务id Return: prune_status(int): 裁剪任务状态(PruneStatus)枚举变量的值 status methods=='POST':#异步,创建一个裁剪分析,对于启动裁剪任务前需要先启动裁剪分析 Args: tid(str):任务id Return: status methods=='PUT':#改变裁剪分析任务的状态 Args: tid(str):任务id act(str):[stop],目前仅支持停止一个裁剪分析任务 Return status """ data = request.get_json() if data is None: data = request.args if request.method == 'GET': from .project.task import get_prune_status ret = get_prune_status(data, SD.workspace) return ret if request.method == 'POST': from .project.task import start_prune_analysis ret = start_prune_analysis(data, SD.workspace, SD.monitored_processes) return ret if request.method == 'PUT': if data['act'] == 'stop': from .project.task import stop_prune_analysis ret = stop_prune_analysis(data, SD.workspace) return ret @app.route('/project/task/evaluate', methods=['GET', 'POST']) def task_evaluate(): ''' methods=='GET':#获取模型评估的结果 Args: tid(str):任务id Return: evaluate_status(int): 任务状态(TaskStatus)枚举变量的值 message(str):描述评估任务的信息 result(dict):如果评估成功,返回评估结果的dict,否则为None status methods=='POST':#异步,创建一个评估任务 Args: tid(str):任务id epoch(int,optional):需要评估的epoch,如果为None则会评估训练时指标最好的epoch topk(int,optional):分类任务topk指标,如果为None默认输入为5 score_thresh(float):检测任务类别的score threshhold值,如果为None默认输入为0.5 overlap_thresh(float):实例分割任务IOU threshhold值,如果为None默认输入为0.3 Return: status ''' data = request.get_json() if data is None: data = request.args if request.method == 'GET': from .project.task import get_evaluate_result ret = get_evaluate_result(data, SD.workspace) if ret['evaluate_status'] == TaskStatus.XEVALUATED and ret[ 'result'] is not None: if 'Confusion_Matrix' in ret['result']: ret['result']['Confusion_Matrix'] = ret['result'][ 'Confusion_Matrix'].tolist() ret['result'] = CustomEncoder().encode(ret['result']) ret['result'] = json.loads(ret['result']) ret['evaluate_status'] = ret['evaluate_status'].value return ret if request.method == 'POST': from .project.task import evaluate_model ret = evaluate_model(data, SD.workspace, SD.monitored_processes) return ret @app.route('/project/task/evaluate/file', methods=['GET']) def task_evaluate_file(): data = request.get_json() if request.method == 'GET': if 'path' in data: ret = data['path'] assert os.path.abspath(ret).startswith( os.path.abspath(SD.workspace_dir) ) and ".." not in ret, "Illegal path {}.".format(ret) return send_file(ret) else: from .project.task import get_evaluate_result from .project.task import import_evaluate_excel ret = get_evaluate_result(data, SD.workspace) if ret['evaluate_status'] == TaskStatus.XEVALUATED and ret[ 'result'] is not None: result = ret['result'] excel_ret = dict() excel_ret = import_evaluate_excel(data, result, SD.workspace) return excel_ret else: excel_ret = dict() excel_ret['path'] = None excel_ret['status'] = -1 excel_ret['message'] = "评估尚未完成或评估失败" return excel_ret @app.route('/project/task/predict', methods=['GET', 'POST', 'PUT']) def task_predict(): ''' methods=='GET':#获取预测状态 Args: tid(str):任务id Return: predict_status(int): 预测任务状态(PredictStatus)枚举变量的值 message(str): 预测信息 status methods=='POST':#创建预测任务,目前仅支持单张图片的预测 Args: tid(str):任务id image_data(str):base64编码的image数据 score_thresh(float,optional):可选,检测任务时有效,检测类别的score threashold值默认是0.5 epoch(int,float,optional):可选,选择需要做预测的ephoch,默认为评估指标最好的那一个epoch Return: path(str):服务器上保存预测结果图片的路径 status ''' data = request.get_json() if data is None: data = request.args if request.method == 'GET': from .project.task import get_predict_status ret = get_predict_status(data, SD.workspace) return ret if request.method == 'POST': from .project.task import predict_test_pics ret = predict_test_pics(data, SD.workspace, SD.monitored_processes) if 'img_list' in data: del ret['path'] return ret return ret if request.method == 'PUT': from .project.task import stop_predict_task ret = stop_predict_task(data, SD.workspace) return ret @app.route('/project/task/export', methods=['GET', 'POST', 'PUT']) def task_export(): ''' methods=='GET':#获取导出模型的状态 Args: tid(str):任务id quant(str,optional)可选,[log,result],导出量模型导出状态,若值为log则返回量化的日志;若值为result则返回量化的结果 Return: status if quant == 'log': quant_log(dict):量化日志 if quant == 'result' quant_result(dict):量化结果 if quant not in Args: export_status(int):模型导出状态(PredictStatus)枚举变量的值 message(str):模型导出提示信息 methods=='POST':#导出inference模型或者导出lite模型 Args: tid(str):任务id type(str):保存模型的类别[infer,lite],支持inference模型导出和lite的模型导出 save_dir(str):保存模型的路径 epoch(str,optional)可选,指定导出的epoch数默认为评估效果最好的epoch quant(bool,optional)可选,type为infer有效,是否导出量化后的模型,默认为False model_path(str,optional)可选,type为lite时有效,inference模型的地址 Return: status if type == 'infer': save_dir:模型保存路径 if type == 'lite': message:模型保存信息 methods=='PUT':#停止导出模型 Args: tid(str):任务id Return: export_status(int):模型导出状态(PredictStatus)枚举变量的值 message(str):停止模型导出提示信息 status ''' data = request.get_json() if data is None: data = request.args if request.method == 'GET': if 'quant' in data: if data['quant'] == 'log': from .project.task import get_quant_progress ret = get_quant_progress(data, SD.workspace) return ret if data['quant'] == 'result': from .project.task import get_quant_result ret = get_quant_result(data, SD.workspace) return ret from .project.task import get_export_status ret = get_export_status(data, SD.workspace) ret['export_status'] = ret['export_status'].value return ret if request.method == 'POST': if data['type'] == 'infer': from .project.task import export_infer_model ret = export_infer_model(data, SD.workspace, SD.monitored_processes) return ret if data['type'] == 'lite': from .project.task import export_lite_model ret = export_lite_model(data, SD.workspace) return ret if request.method == 'PUT': from .project.task import stop_export_task stop_export_task(data, SD.workspace) return ret @app.route('/project/task/vdl', methods=['GET']) def task_vdl(): ''' methods=='GET':#打开某个任务的可视化分析工具(VisualDL) Args: tid(str):任务id Return: url(str):vdl地址 status ''' data = request.get_json() if data is None: data = request.args if request.method == 'GET': from .project.task import open_vdl ret = open_vdl(data, SD.workspace, SD.current_port, SD.monitored_processes, SD.running_boards) return ret @app.route('/system', methods=['GET', 'DELETE']) def system(): ''' methods=='GET':#获取系统GPU、CPU信息 Args: type(str):[machine_info,gpu_memory_size]选择需要获取的系统信息 Return: status if type=='machine_info' info(dict):服务端信息 if type=='gpu_memory_size' gpu_mem_infos(list):GPU内存信息 ''' data = request.get_json() if data is None: data = request.args if request.method == 'GET': if data['type'] == 'machine_info': '''if 'path' not in data: data['path'] = None from .system import get_machine_info ret = get_machine_info(data, SD.machine_info)''' from .system import get_system_info ret = get_system_info(SD.machine_info) return ret if data['type'] == 'gpu_memory_size': #from .system import get_gpu_memory_size from .system import get_gpu_memory_info ret = get_gpu_memory_info(SD.machine_info) return ret if request.method == 'DELETE': from .system import exit_system ret = exit_system(SD.monitored_processes) return ret @app.route('/demo', methods=['GET', 'POST', 'PUT']) def demo(): ''' methods=='GET':#获取demo下载进度 Args: prj_type(int):项目类型ProjectType枚举变量的int值 Return: status attr(dict):demo下载信息 methods=='POST':#下载或创建demo工程 Args: type(str):{download,load}下载或者创建样例 prj_type(int):项目类型ProjectType枚举变量的int值 Return: status if type=='load': did:数据集id pid:项目id methods=='PUT':#停止下载或创建demo工程 Args: prj_type(int):项目类型ProjectType枚举变量的int值 Return: status ''' data = request.get_json() if data is None: data = request.args if request.method == 'GET': from .demo import get_download_demo_progress ret = get_download_demo_progress(data, SD.workspace) return ret if request.method == 'POST': if data['type'] == 'download': from .demo import download_demo_dataset ret = download_demo_dataset(data, SD.workspace, SD.load_demo_proc_dict) return ret if data['type'] == 'load': from .demo import load_demo_project ret = load_demo_project(data, SD.workspace, SD.monitored_processes, SD.load_demo_proj_data_dict, SD.load_demo_proc_dict) return ret if request.method == 'PUT': from .demo import stop_import_demo ret = stop_import_demo(data, SD.workspace, SD.load_demo_proc_dict, SD.load_demo_proj_data_dict) return ret @app.route('/model', methods=['GET', 'POST', 'DELETE']) def model(): ''' methods=='GET':#获取一个或者所有模型的信息 Args: mid(str,optional)可选,若存在则返回某个模型的信息 type(str,optional)可选,[pretrained,exported].若存在则返回对应类型下所有的模型信息 Return: status if mid in Args: dataset_attr(dict):数据集属性 task_params(dict):模型训练参数 eval_result(dict):模型评估结果 if type in Args and type == 'pretrained': pretrained_models(list):所有预训练模型信息 if type in Args and type == 'exported': exported_models(list):所有inference模型的信息 methods=='POST':#创建一个模型 Args: pid(str):项目id tid(str):任务id name(str):模型名字 type(str):创建模型的类型,[pretrained,exported],pretrained代表创建预训练模型、exported代表创建inference或者lite模型 source_path(str):仅type为pretrained时有效,训练好的模型的路径 path(str):仅type为exported时有效,inference或者lite模型的路径 exported_type(int):0为inference模型,1为lite模型 eval_results(dict,optional):可选,仅type为pretrained时有效,模型评估的指标 Return: status if type == 'pretrained': pmid(str):预训练模型id if type == 'exported': emid(str):inference模型id methods=='DELETE':删除一个模型 Args: type(str):删除模型的类型,[pretrained,exported],pretrained代表创建预训练模型、exported代表创建inference或者lite模型 if type='pretrained': pmid:预训练模型id if type='exported': emid:inference或者lite模型id Return: status ''' data = request.get_json() if data is None: data = request.args if request.method == 'GET': if 'type' in data: if data['type'] == 'pretrained': from .model import list_pretrained_models ret = list_pretrained_models(SD.workspace) return ret if data['type'] == 'exported': from .model import list_exported_models ret = list_exported_models(SD.workspace) return ret from .model import get_model_details ret = get_model_details(data, SD.workspace) ret['eval_result']['Confusion_Matrix'] = ret['eval_result'][ 'Confusion_Matrix'].tolist() ret['eval_result'] = CustomEncoder().encode(ret['eval_result']) ret['task_params'] = CustomEncoder().encode(ret['task_params']) return ret if request.method == 'POST': if data['type'] == 'pretrained': if 'eval_results' in data: data['eval_results']['Confusion_Matrix'] = np.array(data[ 'eval_results']['Confusion_Matrix']) from .model import create_pretrained_model ret = create_pretrained_model(data, SD.workspace, SD.monitored_processes) return ret if data['type'] == 'exported': from .model import create_exported_model ret = create_exported_model(data, SD.workspace) return ret if request.method == 'DELETE': if data['type'] == 'pretrained': from .model import delete_pretrained_model ret = delete_pretrained_model(data, SD.workspace) return ret if data['type'] == 'exported': from .model import delete_exported_model ret = delete_exported_model(data, SD.workspace) return ret @app.route('/model/file', methods=['GET']) def model_file(): data = request.get_json() if request.method == 'GET': ret = data['path'] assert os.path.abspath(ret).startswith( os.path.abspath(SD.workspace_dir) ) and ".." not in ret, "Illegal path {}.".format(ret) return send_file(ret) @app.route('/', methods=['GET']) def gui(): if request.method == 'GET': file_path = osp.join( osp.dirname(__file__), 'templates', 'paddlex_restful_demo.html') ip = get_ip() url = 'var str_srv_url = "http://' + ip + ':' + str(SD.port) + '";' f = open(file_path, 'r+', encoding=get_encoding(file_path)) lines = f.readlines() for i, line in enumerate(lines): if '0.0.0.0:8080' in line: lines[i] = url break f.close() f = open(file_path, 'w+', encoding=get_encoding(file_path)) f.writelines(lines) f.close() return render_template('/paddlex_restful_demo.html') def run(port, workspace_dir): if workspace_dir is None: user_home = os.path.expanduser('~') dirname = osp.join(user_home, "paddlex_workspace") else: dirname = workspace_dir if not osp.exists(dirname): os.makedirs(dirname) else: if not osp.isdir(dirname): os.remove(dirname) os.makedirs(dirname) logger = get_logger(osp.join(dirname, "mcessages.log")) init(dirname, logger) SD.port = port ip = get_ip() url = ip + ':' + str(port) try: logger.info("RESTful服务启动成功后,您可以在浏览器打开 {} 使用WEB版本GUI".format(url)) app.run(host='0.0.0.0', port=port, threaded=True) except: print("服务启动不成功,请确保端口号:{}未被防火墙限制".format(port))
import unittest from yearfrac import act_afb class Test_ActAfb(unittest.TestCase): def test1(self): x = act_afb(2018, 12, 15, 2019, 3, 1) self.assertEquals(round(x, 15), 0.208219178082192) self.assertEquals(round(x, 8), 0.20821918) def test2(self): x = act_afb(2018, 12, 31, 2019, 1, 1) self.assertEquals(round(x, 8), round(1. / 365., 8)) def test3(self): x = act_afb(1994, 6, 30, 1997, 6, 30) self.assertEquals(round(x, 8), 3.0) def test4(self): x = act_afb(1994, 2, 10, 1994, 6, 30) self.assertEquals(round(x, 8), round(140. / 365., 8)) # run if __name__ == '__main__': unittest.main()
from setuptools import setup, find_packages import django_nvd3 import os import re def read(*parts): return open(os.path.join(os.path.dirname(__file__), *parts)).read() def parse_requirements(file_name): requirements = [] for line in open(file_name, 'r').read().split('\n'): if re.match(r'(\s*#)|(\s*$)', line): continue if re.match(r'\s*-e\s+', line): requirements.append(re.sub(r'\s*-e\s+.*#egg=(.*)$', r'\1', line)) elif re.match(r'(\s*git)|(\s*hg)', line): pass else: requirements.append(line) return requirements def parse_dependency_links(file_name): dependency_links = [] for line in open(file_name, 'r').read().split('\n'): if re.match(r'\s*-[ef]\s+', line): dependency_links.append(re.sub(r'\s*-[ef]\s+', '', line)) return dependency_links setup( name='django-nvd3', version=django_nvd3.__version__, description="Django NVD3", long_description=read('README.rst'), keywords='django, nvd3, chart, graph, d3', url='http://github.com/areski/django-nvd3', author='Belaid Arezqui', author_email='areski@gmail.com', license='MIT License', zip_safe=False, packages=find_packages(exclude=["tests", "demoproject", "docs"]), include_package_data=True, package_data={}, install_requires=parse_requirements('requirements.txt'), dependency_links=parse_dependency_links('requirements.txt'), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ], )
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftMASGUIONleftASTERISCOBARRAPORCENTAJEleftPOTENCIArightUMENOSUMASABS ACOS ACOSD ACOSH ADD ALL ALTER AMPERSON AND ANY AS ASIN ASIND ASINH ASTERISCO ATAN ATAND ATANDOS ATANDOSD ATANH AVG BARRA BETWEEN BIGINT BOLEANO BUCKET BY BYTEA CADENA CASE CBRT CEIL CEILING CHAR CHARACTER CHECK COLUMN COMA CONSTRAINT CONVERT COS COSD COSH COT COTD COUNT CREATE CURRENTDATE CURRENTTIME CURRENT_USER DATABASE DATABASES DATE DATEPART DAY DECIMAL DECODE DEFAULT DEGREES DELETE DIFERENTELL DISTINCT DIV DOSPUNTOS DOUBLE DROP ELSE ENCODE END ENTERO ENUM EXCEPT EXCEPTION EXCEPTION1 EXECUTE EXISTS EXP EXTRACT FACTORIAL FALSE FECHA FEED FIRST FLOOR FOREIGN FOUND FROM FULL GCD GETBYTE GREATEST GROUP GUION HAVING HOUR ID IF IGUAL ILIKE IN INHERITS INNER INSERT INTEGER INTERSECT INTERVAL INTO IS ISNULL JOIN KEY LAST LCM LEAST LEFT LENGTH LIKE LIMIT LLAVEDER LLAVEIZQ LN LOG MAS MAX MAYORIGUALQUE MAYORQUE MD5 MENORIGUALQUE MENORQUE MIN MINSCALE MINUTE MOD MODE MONEY MONTH NATURAL NEWLINE NOT NOTNULL NOW NO_DATA_FOUND NULL NULLS NUMERAL NUMERIC OF OFFSET ON ONLY OR OUTER OWNER PARENDER PARENIZQ PERFORM PI PLECA PORCENTAJE POTENCIA POWER PRECISION PRIMARY PRINT_STRICT_PARAMS PTCOMA PUNTO RADIANS RAISE RANDOM REAL REFERENCES RENAME REPLACE RETURN RETURNING RIGHT ROUND SCALE SECOND SELECT SESSION_USER SET SETBYTE SETSEED SHA SHOW SIGN SIMILAR SIN SIND SINH SMALLINT SOME SQRT STRICT SUBSTR SUBSTRING SUM SYMMETRIC TAB TABLE TAN TAND TANH TEXT THEN TIME TIMESTAMP TO TOO_MANY_ROWS TRIM TRUE TRUNC TYPE UNION UNIQUE UNKNOWN UPDATE USE USING VALUES VARCHAR VARYING VIRGULILLA WHEN WHERE YEARinit : instruccionesinstrucciones : instrucciones instruccioninstrucciones : instruccioninstruccion : CREATE create\n | USE use\n | SHOW show\n | DROP drop\n | DELETE delete\n | INSERT insert\n | UPDATE updateinstruccion : ALTER alterinstruccion : select PTCOMAinstruccion : querysinstruccion : probleminstruccion : pl_asignacioninstruccion : pl_performinstruccion : pl_if_not_foundinstruccion : pl_w_excepcioninstruccion : p_print_strictinstruccion : pl_returninstruccion : pl_executeproblem : error PTCOMAquerys : select UNION allopcional select\n | select INTERSECT allopcional select\n | select EXCEPT allopcional selectallopcional : ALLallopcional : select : SELECT parametrosselect fromopcionalselect : problemfromopcional : FROM parametrosfrom whereopcional fromopcional : FROM parametrosfrom groupbyopcional fromopcional : whereopcional : WHERE condiciones groupbyopcionalwhereopcional : groupbyopcional : GROUP BY listaids havingsgroupbyopcional : GROUP BY listanumeros havingshavings : HAVING condicioneshavings : listanumeros : listanumeros COMA ENTEROlistanumeros : ENTEROgroupbyopcional : parametrosfrom : parametrosfrom COMA parametrosfromr asopcionalparametrosfrom : parametrosfromr asopcionalparametrosfromr : ID\n | PARENIZQ select PARENDERparametrosselect : DISTINCT listadeseleccionparametrosselect : listadeseleccionlistadeseleccion : listadeseleccion COMA listadeseleccionados asopcionallistadeseleccion : listadeseleccionados asopcionallistadeseleccionados : PARENIZQ select PARENDER\n | ASTERISCO\n | GREATEST PARENIZQ listadeargumentos PARENDER\n | LEAST PARENIZQ listadeargumentos PARENDER\n | CASE cases END ID listadeseleccionados : funcionesmatematicassimples\n | funcionestrigonometricas\n | funcionesmatematicas\n | funcionesdefechas\n | funcionesbinarias\n | operadoresselectlistadeargumentos : listadeargumentos COMA argumentlistadeargumentos : argument cases : cases case elsecasecases : case elsecasecase : WHEN condiciones THEN argumentelsecase : ELSE argument elsecase : operadoresselect : PLECA argumentodeoperadores\n | VIRGULILLA argumentodeoperadores operadoresselect : PLECA PLECA argumentodeoperadoresoperadoresselect : argumentodeoperadores AMPERSON argumentodeoperadores\n | argumentodeoperadores PLECA argumentodeoperadores\n | argumentodeoperadores NUMERAL argumentodeoperadores\n | argumentodeoperadores MENORQUE MENORQUE argumentodeoperadores\n | argumentodeoperadores MAYORQUE MAYORQUE argumentodeoperadoresargumentodeoperadores : argumentodeoperadores MAS argumentodeoperadores\n | argumentodeoperadores GUION argumentodeoperadores\n | argumentodeoperadores BARRA argumentodeoperadores\n | argumentodeoperadores ASTERISCO argumentodeoperadores\n | argumentodeoperadores PORCENTAJE argumentodeoperadores\n | argumentodeoperadores POTENCIA argumentodeoperadoresargumentodeoperadores : DECIMALargumentodeoperadores : ENTEROargumentodeoperadores : IDfuncionesmatematicassimples : COUNT PARENIZQ argument PARENDER\n | MAX PARENIZQ argument PARENDER\n | SUM PARENIZQ argument PARENDER\n | AVG PARENIZQ argument PARENDER\n | MIN PARENIZQ argument PARENDERfuncionesbinarias : LENGTH PARENIZQ argument PARENDER\n | SUBSTRING PARENIZQ argument COMA ENTERO COMA ENTERO PARENDER\n | TRIM PARENIZQ argument PARENDER\n | MD5 PARENIZQ argument PARENDER\n | SHA PARENIZQ argument PARENDER\n | SUBSTR PARENIZQ argument COMA ENTERO COMA ENTERO PARENDER\n | GETBYTE PARENIZQ argument DOSPUNTOS DOSPUNTOS BYTEA COMA argument PARENDER\n | SETBYTE PARENIZQ argument DOSPUNTOS DOSPUNTOS BYTEA COMA argument COMA argument PARENDER\n | CONVERT PARENIZQ argument AS tipo\n | ENCODE PARENIZQ argument DOSPUNTOS DOSPUNTOS BYTEA COMA CADENA PARENDER\n | DECODE PARENIZQ argument COMA CADENA PARENDER funcionesmatematicas : PI PARENIZQ PARENDER\n | RANDOM PARENIZQ PARENDERfuncionesmatematicas : ABS PARENIZQ argument PARENDER\n | CBRT PARENIZQ argument PARENDER\n | CEIL PARENIZQ argument PARENDER\n | CEILING PARENIZQ argument PARENDER\n | DEGREES PARENIZQ argument PARENDER\n | EXP PARENIZQ argument PARENDER\n | FLOOR PARENIZQ argument PARENDER\n | LN PARENIZQ argument PARENDER\n | LOG PARENIZQ argument PARENDER\n | RADIANS PARENIZQ argument PARENDER\n | SCALE PARENIZQ argument PARENDER\n | SIGN PARENIZQ argument PARENDER\n | SQRT PARENIZQ argument PARENDER\n | TRUNC PARENIZQ argument PARENDERfuncionesmatematicas : DIV PARENIZQ argument COMA argument PARENDER\n | GCD PARENIZQ argument COMA argument PARENDER\n | MOD PARENIZQ argument COMA argument PARENDER\n | POWER PARENIZQ argument COMA argument PARENDERfuncionesmatematicas : ROUND PARENIZQ argument tipoderound PARENDERtipoderound : COMA argumenttipoderound :funcionesmatematicas : BUCKET PARENIZQ argument COMA argument COMA argument COMA argument PARENDERfuncionestrigonometricas : ACOS PARENIZQ argument PARENDER\n | ASIN PARENIZQ argument PARENDER\n | ACOSD PARENIZQ argument PARENDER\n | ASIND PARENIZQ argument PARENDER\n | ATAN PARENIZQ argument PARENDER\n | ATAND PARENIZQ argument PARENDER\n | ATANDOS PARENIZQ argument COMA argument PARENDER\n | ATANDOSD PARENIZQ argument COMA argument PARENDER\n | COS PARENIZQ argument PARENDER\n | COSD PARENIZQ argument PARENDER\n | COT PARENIZQ argument PARENDER\n | COTD PARENIZQ argument PARENDER\n | SIN PARENIZQ argument PARENDER\n | SIND PARENIZQ argument PARENDER\n | TAN PARENIZQ argument PARENDER\n | TAND PARENIZQ argument PARENDER\n | SINH PARENIZQ argument PARENDER\n | COSH PARENIZQ argument PARENDER\n | TANH PARENIZQ argument PARENDER\n | ASINH PARENIZQ argument PARENDER\n | ACOSH PARENIZQ argument PARENDER\n | ATANH PARENIZQ argument PARENDER funcionesdefechas : EXTRACT PARENIZQ partedelafecha FROM TIMESTAMP argument PARENDER\n | DATEPART PARENIZQ argument COMA INTERVAL argument PARENDER\n | NOW PARENIZQ PARENDER\n | CURRENTDATE\n | CURRENTTIME\n | TIMESTAMP argument partedelafecha : YEAR\n | MONTH\n | DAY\n | HOUR\n | MINUTE\n | SECONDlistadeseleccionados : IDlistadeseleccionados : ID PUNTO IDlistadeseleccionados : ID PUNTO ASTERISCOasopcional : AS ID asopcional : IDasopcional : AS CADENA asopcional : CADENAasopcional : argument : funcionesmatematicassimples\n | funcionestrigonometricas\n | funcionesmatematicas\n | funcionesdefechas\n | funcionesbinariascreate : TYPE createenum\n | TABLE createtable\n | OR REPLACE DATABASE createdatabase\n | DATABASE createdatabasecreate : problemcreateenum : ID AS ENUM PARENIZQ listacadenas PARENDER PTCOMAlistacadenas : listacadenas COMA CADENAlistacadenas : CADENAcreatedatabase : IF NOT EXISTS ID databaseowner\n | ID databaseownerdatabaseowner : OWNER IGUAL tipoowner databasemode\n | OWNER tipoowner databasemodetipoowner : IDtipoowner : CADENAdatabaseowner : databasemodedatabasemode : MODE IGUAL ENTERO PTCOMA\n | MODE ENTERO PTCOMA\n | PTCOMAcreatetable : ID PARENIZQ tabledescriptions PARENDER tableherenciatableherencia : INHERITS PARENIZQ ID PARENDER PTCOMA\n | PTCOMAtabledescriptions : tabledescriptions COMA tabledescriptiontabledescriptions : tabledescriptiontabledescription : ID tipo tablekey\n | PRIMARY KEY PARENIZQ listaids PARENDER\n | FOREIGN KEY PARENIZQ listaids PARENDER REFERENCES ID PARENIZQ listaids PARENDER\n | CONSTRAINT ID CHECK finalconstraintcheck\n | CHECK finalconstraintcheck\n | UNIQUE finaluniquetablekey : PRIMARY KEY tabledefault\n | REFERENCES ID PARENIZQ ID PARENDER tabledefaulttablekey : REFERENCES ID tabledefaulttablekey : tabledefaultcolumnreferences : columnreferences COMA IDcolumnreferences : IDtabledefault : DEFAULT value tablenulltabledefault : tablenulltablenull : NOT NULL tableconstraintunique\n | NULL tableconstraintuniquetablenull : tableconstraintuniquetableconstraintunique : CONSTRAINT ID UNIQUE tableconstraintcheck\n | UNIQUE tableconstraintchecktableconstraintunique : tableconstraintchecktableconstraintcheck : CONSTRAINT ID CHECK PARENIZQ condiciones PARENDER\n | CHECK PARENIZQ condiciones PARENDERtableconstraintcheck : finalconstraintcheck : PARENIZQ condiciones PARENDERfinalunique : PARENIZQ listaids PARENDERlistaids : listaids COMA IDlistaids : IDlistaidcts : listaidcts COMA ID PUNTO IDlistaidcts : listaidcts COMA IDlistaidcts : ID PUNTO IDlistaidcts : IDtipo : SMALLINT\n | INTEGER\n | BIGINT\n | DECIMAL\n | NUMERIC\n | REAL\n | DOUBLE PRECISION\n | MONEY\n | CHARACTER tipochar\n | VARCHAR PARENIZQ ENTERO PARENDER\n | CHAR PARENIZQ ENTERO PARENDER\n | TEXT\n | TIMESTAMP precision\n | TIME precision\n | DATE\n | INTERVAL fields precision\n | BOLEANO\n | IDtipochar : VARYING PARENIZQ ENTERO PARENDER\n | PARENIZQ ENTERO PARENDERprecision : PARENIZQ ENTERO PARENDERprecision :fields : MONTH\n | HOUR\n | MINUTE\n | SECOND\n | YEARfields :use : DATABASE ID PTCOMA\n | ID PTCOMAuse : problemshow : DATABASES likeopcionalshow : problemlikeopcional : LIKE CADENA PTCOMA\n | PTCOMA drop : DATABASE dropdb PTCOMA\n | TABLE ID PTCOMAdrop : problemdropdb : IF EXISTS ID\n | IDalter : DATABASE ID alterdbs PTCOMA\n | TABLE ID altertables PTCOMAalter : problemalterdbs : alterdbs COMA alterdbalterdbs : alterdbalterdb : RENAME TO ID\n | OWNER TO tipodeownertipodeowner : ID\n | CURRENT_USER\n | SESSION_USERaltertables : altertables COMA altertablealtertables : altertablealtertable : ADD alteraddc\n | ALTER COLUMN ID SET opcionesalterset\n | DROP tipodedrop\n | RENAME COLUMN ID TO IDaltertable : RENAME ID TO IDaltertable : ALTER COLUMN ID TYPE tipoalteraddc : CONSTRAINT ID UNIQUE PARENIZQ listaidcts PARENDER\n | COLUMN ID tipoalteraddc : CONSTRAINT ID alteraddalteraddc : alteraddalteradd : CHECK PARENIZQ condiciones PARENDER\n | FOREIGN KEY PARENIZQ listaids PARENDER REFERENCES ID PARENIZQ listaids PARENDER\n | PRIMARY KEY PARENIZQ listaids PARENDERopcionesalterset : NOT NULL\n | NULL tipodedrop : COLUMN ID\n | CONSTRAINT ID\n | PRIMARY KEY PARENIZQ listaids PARENDER\n | FOREIGN KEY PARENIZQ listaids PARENDERdelete : FROM ID condicionesops PTCOMAdelete : probleminsert : INTO ID VALUES PARENIZQ values PARENDER PTCOMAinsert : problemvalues : values COMA valuevalues : valuevalue : ENTEROvalue : DECIMALvalue : CADENAvalue : boleanovalue : MD5 PARENIZQ argument PARENDERvalue : NOW PARENIZQ PARENDERvalue : TRIM PARENIZQ argument PARENDERvalue : SUBSTRING PARENIZQ argument COMA ENTERO COMA ENTERO PARENDERvalue : SUBSTR PARENIZQ argument COMA ENTERO COMA ENTERO PARENDERupdate : ID SET asignaciones condicionesops PTCOMAupdate : problemasignaciones : asignaciones COMA ID IGUAL argumentasignaciones : ID IGUAL argumentcondicionesops : WHERE condicionescondicionesops : condiciones : condiciones comparacionlogica condicioncondiciones : condicioncomparacionlogica : AND\n | ORcondicion : NOT condicion\n | condicionscondicions : argument MENORQUE argument\n | argument MAYORQUE argument\n | argument IGUAL argument\n | argument MENORIGUALQUE argument\n | argument MAYORIGUALQUE argument\n | argument DIFERENTELL argument\n | argument BETWEEN betweenopcion\n | argument ISNULL\n | argument NOTNULL\n | argument IS isopcion\n | argument IN PARENIZQ select PARENDER\n | argument NOT BETWEEN betweenopcion\n | argument NOT IN PARENIZQ select PARENDER\n | argument ANY PARENIZQ select PARENDER\n | argument ALL PARENIZQ select PARENDER\n | argument SOME PARENIZQ select PARENDERcondicions : EXISTS PARENIZQ select PARENDERbetweenopcion : symm argument AND argument\n | argument AND argumentsymm : SYMMETRICisopcion : DISTINCT FROM argument\n | NULL\n | TRUE\n | FALSE\n | UNKNOWN\n | NOT isnotoptionsisnotoptions : FALSE\n | UNKNOWN\n | TRUE\n | NULL\n | DISTINCT FROM argumentargument : argument MAS argument\n | argument GUION argument\n | argument BARRA argument\n | argument ASTERISCO argument\n | argument PORCENTAJE argument\n | argument POTENCIA argumentargument : boleanoargument : MAS argument %prec UMAS\n | GUION argument %prec UMENOSargument : PARENIZQ argument PARENDERargument : ENTEROargument : DECIMALargument : CADENAargument : IDargument : ID PUNTO IDlistadeseleccionados : ID INTO IDlistadeseleccionados : ID INTO STRICT IDlistadeseleccionados : ASTERISCO INTO IDlistadeseleccionados : ASTERISCO INTO STRICT IDboleano : TRUE\n | FALSEpl_asignacion : ID DOSPUNTOS IGUAL argument PTCOMApl_asignacion : ID PUNTO ID DOSPUNTOS IGUAL argument PTCOMApl_asignacion : ID IGUAL argument PTCOMApl_asignacion : ID PUNTO ID IGUAL argument PTCOMApl_perform : PERFORM ID PARENIZQ listadeargumentos PARENDER PTCOMApl_perform : PERFORM ID PARENIZQ PARENDER PTCOMAperform : problempl_if_not_found : IF NOT FOUND THEN raiseexception END IF PTCOMAraiseexception : RAISE EXCEPTION argument COMA argument PTCOMAraiseexception : RAISE EXCEPTION argument PTCOMApl_w_excepcion : EXCEPTION instrucciones1instrucciones1 : instrucciones1 instruccion2instrucciones1 : instruccion2instruccion2 : WHEN NO_DATA_FOUND THEN raiseexceptioninstruccion2 : WHEN TOO_MANY_ROWS THEN raiseexceptionp_print_strict : NUMERAL PRINT_STRICT_PARAMS ONpl_return : RETURN argument PTCOMApl_execute : EXECUTE argument INTO STRICT ID USING listaidcts PTCOMApl_execute : EXECUTE argument INTO ID USING listaidcts PTCOMApl_execute : EXECUTE argument USING listaidcts PTCOMApl_execute : EXECUTE argument PTCOMApl_execute : EXECUTE argument INTO STRICT ID PTCOMApl_execute : EXECUTE argument INTO ID PTCOMA' _lr_action_items = {'CREATE':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[4,4,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'USE':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[5,5,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'SHOW':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[6,6,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'DROP':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,201,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,517,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[7,7,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,353,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,353,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'DELETE':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[8,8,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'INSERT':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[9,9,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'UPDATE':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[10,10,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'ALTER':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,201,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,517,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[11,11,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,352,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,352,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'SELECT':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,63,64,65,66,68,69,70,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,202,203,204,205,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,361,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,568,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,739,742,743,744,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,853,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[22,22,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-27,-27,-27,-32,-47,-166,22,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,22,-26,22,22,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,22,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,22,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,22,22,22,22,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,22,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'error':([0,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,63,64,65,66,68,69,70,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,202,203,204,205,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,361,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,568,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,739,742,743,744,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,853,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[23,23,-3,23,23,23,23,23,23,23,23,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-27,-27,-27,-32,-47,-166,23,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,23,-26,23,23,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,23,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,23,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,23,23,23,23,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,23,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'ID':([0,2,3,5,10,13,14,15,16,17,18,19,20,21,22,25,29,30,31,32,33,34,36,37,38,39,41,42,44,45,46,47,48,49,50,51,52,53,54,55,57,58,59,60,61,62,66,67,68,69,71,75,76,77,78,79,80,81,132,135,136,139,149,151,152,153,155,156,159,160,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,180,182,185,189,190,192,199,206,207,208,209,210,211,212,213,215,216,217,218,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,274,275,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,296,297,298,299,300,301,302,303,306,308,311,312,313,314,315,316,317,318,319,320,322,323,324,325,327,328,330,331,332,334,335,337,338,339,341,354,355,356,357,358,359,360,362,363,364,365,366,367,371,374,377,378,379,381,382,383,384,412,413,442,454,455,456,457,458,459,460,461,462,463,464,465,467,469,475,476,477,478,479,480,481,482,483,488,493,496,497,498,504,506,509,511,512,514,515,516,519,520,525,527,528,531,533,534,535,536,538,540,541,542,543,544,545,548,549,550,551,552,553,554,555,556,557,558,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,616,617,620,622,623,624,628,631,632,633,634,637,640,641,643,644,645,646,647,649,651,652,653,654,655,656,658,662,663,664,665,666,667,669,674,676,679,681,694,704,705,714,715,716,717,718,721,722,723,724,725,726,727,729,730,731,732,734,735,736,737,740,752,755,756,761,765,766,768,769,770,779,785,789,790,795,797,798,799,800,801,802,803,804,806,808,809,813,814,815,816,819,821,822,823,824,829,830,832,833,834,835,837,838,839,840,841,842,844,845,846,847,848,849,852,857,858,859,860,861,862,863,864,872,873,877,878,888,889,895,896,902,903,911,922,923,924,926,927,928,929,930,932,933,934,936,937,940,941,943,944,945,946,948,951,960,961,962,963,967,978,979,980,981,982,983,984,985,992,994,996,1000,1002,1003,1004,1005,1008,1013,1017,1020,1021,],[24,24,-3,40,56,-13,-14,-15,-16,-17,-18,-19,-20,-21,75,157,176,176,-2,-4,181,183,187,-176,-5,188,-256,-6,-258,-7,195,196,-263,-8,197,-298,-9,198,-300,-10,-313,-11,200,201,-268,-12,-32,75,-47,212,-51,-159,-55,-56,-57,-58,-59,-60,176,-150,-151,-83,290,290,-82,-22,176,305,-386,-388,-167,-168,-169,-170,-171,176,176,-361,176,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,343,-28,360,-46,75,-49,363,-163,-165,-29,366,176,176,176,381,383,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,176,-152,176,176,176,176,176,176,176,176,176,176,176,176,290,-68,-84,290,290,290,290,290,290,290,290,290,-69,176,176,-387,-391,-392,176,176,176,176,176,176,-362,-363,482,484,486,-396,488,187,-181,500,-186,-189,-254,-261,505,-262,176,532,-23,-24,-25,-34,212,-44,212,-162,-164,-50,-372,541,545,176,-319,176,-323,-160,-161,-370,569,-101,-102,-149,-70,-71,-72,-73,290,290,-76,-77,-78,-79,-80,-81,-378,176,-355,-356,-357,-358,-359,-360,-364,-369,642,649,672,-174,677,500,-259,-297,176,695,-266,697,699,-267,703,704,708,709,710,713,-30,-31,360,176,-43,-48,-373,-52,176,-53,-54,176,176,-320,-321,176,176,176,176,176,176,176,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,176,176,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,176,176,176,176,176,176,-90,-92,-93,-94,649,-74,-75,-376,176,-381,-389,-390,486,-398,-395,772,773,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,488,176,813,-183,-188,-312,649,176,836,212,-41,813,-45,-318,-324,-325,-326,-327,-328,-329,-330,176,-343,-333,-345,-346,-347,-348,176,-121,176,176,-98,-379,-380,176,486,-397,882,886,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,813,813,-221,-180,-182,-187,176,176,176,176,176,813,813,649,813,813,921,-42,-33,-38,-38,-40,176,176,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,176,-100,-377,-394,947,957,176,-241,964,967,-299,486,-35,176,-36,-342,176,-344,176,-334,-337,-338,-339,-147,-148,176,176,-383,176,-385,-393,-177,990,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,176,-91,-95,176,-244,1009,1012,-96,176,-99,-384,-191,-124,813,813,-97,]),'PERFORM':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[25,25,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'IF':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,36,37,38,41,42,44,45,46,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,328,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,767,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[26,26,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,186,-176,-5,-256,-6,-258,-7,194,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,186,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,874,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'EXCEPTION':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,639,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[27,27,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,768,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'NUMERAL':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,150,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[28,28,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-84,-55,-56,-57,-58,-59,-60,-150,-151,-83,293,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'RETURN':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[29,29,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'EXECUTE':([0,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[30,30,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'$end':([1,2,3,13,14,15,16,17,18,19,20,21,31,32,37,38,41,42,44,45,48,49,51,52,54,55,57,58,61,62,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,159,160,164,165,166,167,168,171,173,174,175,176,177,178,180,182,185,189,190,192,206,208,210,212,213,215,274,289,290,302,308,311,312,319,320,325,330,332,334,335,337,339,355,356,357,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,467,475,476,477,478,479,480,481,482,496,504,506,512,516,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,633,637,640,641,644,645,649,651,652,653,654,655,656,658,662,663,664,665,666,667,679,681,694,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,765,766,770,789,790,795,797,798,799,800,801,802,803,804,806,813,814,815,816,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,873,877,895,903,922,924,926,928,930,932,933,934,936,937,943,945,946,948,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1005,1008,1013,1021,],[0,-1,-3,-13,-14,-15,-16,-17,-18,-19,-20,-21,-2,-4,-176,-5,-256,-6,-258,-7,-263,-8,-298,-9,-300,-10,-313,-11,-268,-12,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-386,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-172,-173,-175,-255,-257,-260,-28,-46,-49,-163,-165,-29,-152,-68,-84,-69,-387,-391,-392,-362,-363,-396,-181,-186,-189,-254,-261,-262,-23,-24,-25,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-378,-355,-356,-357,-358,-359,-360,-364,-369,-174,-259,-297,-266,-267,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-376,-381,-389,-390,-398,-395,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-183,-188,-312,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-379,-380,-397,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-190,-192,-221,-180,-182,-187,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-377,-394,-241,-299,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-383,-385,-393,-177,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-384,-191,-124,-97,]),'TYPE':([4,708,],[33,832,]),'TABLE':([4,7,11,],[34,47,60,]),'OR':([4,135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,375,377,379,412,413,442,475,476,477,478,479,480,481,482,507,559,560,567,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,716,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,789,790,795,797,798,799,800,801,802,803,811,828,845,846,847,848,849,852,857,858,859,860,861,862,863,872,895,926,928,930,932,933,934,936,937,958,960,961,962,963,978,980,981,982,984,985,994,1002,1004,1007,1013,1021,],[35,-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,551,-319,-323,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,551,-331,-332,-322,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,551,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,551,551,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-241,-342,-344,-334,-337,-338,-339,-147,-148,551,-245,-235,-236,-246,551,-341,-354,-336,-91,-95,-244,-96,-99,551,-124,-97,]),'DATABASE':([4,5,7,11,184,],[36,39,46,59,328,]),'DATABASES':([6,],[43,]),'FROM':([8,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,164,165,166,167,168,171,173,174,175,176,177,178,208,210,212,213,274,289,290,302,319,320,362,363,364,365,366,381,382,383,412,413,434,435,436,437,438,439,440,442,454,455,456,457,460,461,462,463,464,465,475,476,477,478,479,480,481,482,540,541,542,544,545,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,649,651,652,653,654,655,656,658,662,663,664,665,666,667,733,752,761,789,790,795,797,798,799,800,801,802,803,850,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[50,207,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-46,-49,-163,-165,-152,-68,-84,-69,-362,-363,-166,-162,-164,-50,-372,-160,-161,-370,-101,-102,618,-153,-154,-155,-156,-157,-158,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-355,-356,-357,-358,-359,-360,-364,-369,-48,-373,-52,-53,-54,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,844,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,929,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'INTO':([9,71,75,135,136,164,165,166,167,168,171,173,174,175,176,177,178,179,274,319,320,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[53,216,223,-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,323,-152,-362,-363,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'PTCOMA':([12,14,23,40,43,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,163,164,165,166,167,168,171,173,174,175,176,177,178,179,187,188,193,195,196,197,206,208,210,212,213,274,289,290,302,304,319,320,336,340,344,345,346,349,350,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,466,471,475,476,477,478,479,480,481,482,484,485,486,499,500,501,503,505,507,510,518,521,526,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,635,636,642,649,651,652,653,654,655,656,658,662,663,664,665,666,667,668,677,678,680,693,696,697,698,699,700,701,702,709,710,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,764,771,772,773,789,790,795,797,798,799,800,801,802,803,813,817,826,827,836,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,874,875,876,879,895,910,912,915,917,918,921,922,924,926,928,930,932,933,934,936,937,947,960,961,962,963,967,974,975,976,977,978,979,980,981,982,984,985,989,994,995,999,1002,1004,1013,1021,1027,],[62,-29,153,189,192,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,312,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,325,334,335,337,-265,339,-317,-28,-46,-49,-163,-165,-152,-68,-84,-69,467,-362,-363,504,506,-317,512,-270,516,-277,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,633,637,-355,-356,-357,-358,-359,-360,-364,-369,644,645,-225,334,-184,-185,681,-264,-316,694,-278,-287,-280,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,765,766,770,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,806,334,334,816,-315,-269,-271,-272,-273,-274,-275,-276,-293,-294,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,873,877,-223,-224,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-221,903,-286,-285,-282,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,943,945,946,948,-241,-314,-288,-279,-292,-283,-281,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-222,-245,-235,-236,-246,-220,-290,-291,-295,-296,-37,-39,-341,-354,-336,-91,-95,1005,-244,1008,-284,-96,-99,-124,-97,-289,]),'UNION':([12,14,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,164,165,166,167,168,171,173,174,175,176,177,178,206,208,210,212,213,274,289,290,302,319,320,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,475,476,477,478,479,480,481,482,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,649,651,652,653,654,655,656,658,662,663,664,665,666,667,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,789,790,795,797,798,799,800,801,802,803,813,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,895,922,924,926,928,930,932,933,934,936,937,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1013,1021,],[63,-29,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-28,-46,-49,-163,-165,-152,-68,-84,-69,-362,-363,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-355,-356,-357,-358,-359,-360,-364,-369,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-221,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-241,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-124,-97,]),'INTERSECT':([12,14,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,164,165,166,167,168,171,173,174,175,176,177,178,206,208,210,212,213,274,289,290,302,319,320,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,475,476,477,478,479,480,481,482,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,649,651,652,653,654,655,656,658,662,663,664,665,666,667,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,789,790,795,797,798,799,800,801,802,803,813,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,895,922,924,926,928,930,932,933,934,936,937,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1013,1021,],[64,-29,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-28,-46,-49,-163,-165,-152,-68,-84,-69,-362,-363,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-355,-356,-357,-358,-359,-360,-364,-369,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-221,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-241,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-124,-97,]),'EXCEPT':([12,14,66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,164,165,166,167,168,171,173,174,175,176,177,178,206,208,210,212,213,274,289,290,302,319,320,358,359,360,362,363,364,365,366,377,379,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,475,476,477,478,479,480,481,482,533,534,538,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,649,651,652,653,654,655,656,658,662,663,664,665,666,667,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,789,790,795,797,798,799,800,801,802,803,813,837,838,839,840,841,845,846,847,848,849,852,857,858,859,860,861,862,863,872,895,922,924,926,928,930,932,933,934,936,937,960,961,962,963,967,978,979,980,981,982,984,985,994,1002,1004,1013,1021,],[65,-29,-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-28,-46,-49,-163,-165,-152,-68,-84,-69,-362,-363,-34,-166,-44,-166,-162,-164,-50,-372,-319,-323,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-355,-356,-357,-358,-359,-360,-364,-369,-30,-31,-43,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-166,-41,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-221,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-241,-35,-36,-342,-344,-334,-337,-338,-339,-147,-148,-245,-235,-236,-246,-220,-37,-39,-341,-354,-336,-91,-95,-244,-96,-99,-124,-97,]),'DISTINCT':([22,561,738,],[67,733,850,]),'PARENIZQ':([22,29,30,67,72,73,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,137,138,140,141,142,143,144,145,146,147,148,155,157,169,170,172,183,207,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,342,374,378,380,469,487,494,495,509,522,535,536,543,548,549,550,551,552,553,554,555,556,557,558,562,564,565,566,581,582,611,612,613,614,616,617,634,659,660,661,663,664,666,670,671,674,688,689,690,691,692,705,706,707,711,712,730,731,740,741,755,756,768,788,791,798,799,800,801,802,803,805,810,819,821,822,823,824,825,842,844,864,882,889,923,927,929,940,941,944,956,983,992,1003,1009,1012,],[70,172,172,70,217,218,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,172,275,276,277,278,279,280,281,282,283,284,285,286,287,172,306,172,172,172,327,361,70,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,508,172,172,568,172,648,674,676,172,705,361,172,172,172,172,-320,-321,172,172,172,172,172,172,172,739,742,743,744,172,172,172,172,172,172,172,172,172,792,793,794,796,796,-253,808,809,172,819,820,821,822,823,172,829,830,833,834,172,-343,172,853,172,172,172,889,890,796,-248,-249,-250,-251,-252,896,674,172,172,172,172,172,911,172,172,172,951,172,172,172,172,172,172,172,992,172,172,172,1017,1020,]),'ASTERISCO':([22,67,75,135,136,139,150,152,163,164,165,166,167,168,171,173,174,175,176,177,178,179,209,222,274,289,290,302,304,319,320,321,369,376,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,460,461,462,463,464,465,466,475,476,477,478,479,480,481,482,547,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,635,649,651,652,653,654,655,656,658,662,663,664,665,666,667,693,719,720,722,723,724,725,726,727,728,746,747,748,749,750,751,752,753,754,761,764,789,790,795,797,798,799,800,801,802,803,843,858,859,860,861,862,863,865,866,872,875,895,905,907,908,909,910,926,928,935,936,937,960,961,962,963,980,981,984,985,986,987,989,994,1001,1002,1004,1013,1014,1021,],[71,71,-84,-150,-151,-83,299,-82,316,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,316,71,382,316,299,-84,299,316,-362,-363,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,-101,-102,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,-149,316,316,316,316,316,316,316,316,316,316,316,299,299,299,299,299,299,-78,-79,-80,-81,316,316,316,-357,-358,-359,-360,-364,-369,316,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,299,299,316,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,-121,316,316,-98,316,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,316,-131,-132,-117,-118,-119,-120,316,316,-100,316,-241,316,316,316,316,316,316,316,316,-147,-148,-245,-235,-236,-246,316,316,-91,-95,316,316,316,-244,316,-96,-99,-124,316,-97,]),'GREATEST':([22,67,209,],[72,72,72,]),'LEAST':([22,67,209,],[73,73,73,]),'CASE':([22,67,209,],[74,74,74,]),'COUNT':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,-320,-321,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,-343,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,]),'MAX':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,-320,-321,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,-343,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,]),'SUM':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,-320,-321,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,-343,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,]),'AVG':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,-320,-321,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,-343,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,]),'MIN':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,-320,-321,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,-343,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,]),'ACOS':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,-320,-321,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,-343,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,]),'ASIN':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,-320,-321,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,-343,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,]),'ACOSD':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,-320,-321,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,-343,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,]),'ASIND':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,-320,-321,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,-343,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,]),'ATAN':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,-320,-321,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,-343,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,]),'ATAND':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,-320,-321,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,-343,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,]),'ATANDOS':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,-320,-321,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,-343,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,]),'ATANDOSD':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,-320,-321,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,-343,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,94,]),'COS':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,-320,-321,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,-343,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,]),'COSD':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,-320,-321,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,-343,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,96,]),'COT':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,-320,-321,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,-343,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,]),'COTD':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,-320,-321,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,-343,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,]),'SIN':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,-320,-321,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,-343,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,]),'SIND':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,-320,-321,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,-343,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,]),'TAN':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,-320,-321,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,-343,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,101,]),'TAND':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,-320,-321,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,-343,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,]),'SINH':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,-320,-321,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,-343,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,103,]),'COSH':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,-320,-321,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,-343,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,104,]),'TANH':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,-320,-321,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,-343,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,]),'ASINH':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,-320,-321,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,-343,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,]),'ACOSH':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,-320,-321,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,-343,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,107,]),'ATANH':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,-320,-321,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,-343,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,]),'PI':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,-320,-321,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,-343,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,]),'RANDOM':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,-320,-321,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,-343,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,]),'ABS':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,-320,-321,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,-343,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,]),'CBRT':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,-320,-321,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,-343,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,]),'CEIL':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,-320,-321,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,-343,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,113,]),'CEILING':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,-320,-321,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,-343,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,]),'DEGREES':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,-320,-321,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,-343,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,115,]),'EXP':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,-320,-321,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,-343,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,]),'FLOOR':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,-320,-321,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,-343,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,117,]),'LN':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,-320,-321,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,-343,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,118,]),'LOG':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,-320,-321,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,-343,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,119,]),'RADIANS':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,-320,-321,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,-343,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,]),'SCALE':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,-320,-321,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,-343,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,]),'SIGN':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,-320,-321,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,-343,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,]),'SQRT':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,-320,-321,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,-343,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,]),'TRUNC':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,-320,-321,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,-343,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,]),'DIV':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,-320,-321,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,-343,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,]),'GCD':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,-320,-321,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,-343,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,]),'MOD':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,-320,-321,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,-343,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,]),'POWER':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,-320,-321,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,-343,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,]),'ROUND':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,-320,-321,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,-343,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,]),'BUCKET':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,-320,-321,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,-343,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,]),'EXTRACT':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,-320,-321,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,-343,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,]),'DATEPART':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,-320,-321,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,-343,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,133,]),'NOW':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,508,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,780,818,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,689,134,134,134,134,134,-320,-321,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,-343,134,134,134,134,689,689,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,134,]),'CURRENTDATE':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,-320,-321,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,-343,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,]),'CURRENTTIME':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,-320,-321,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,-343,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,]),'TIMESTAMP':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,488,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,618,628,634,674,704,705,730,731,740,755,756,768,819,821,822,823,824,832,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,663,132,132,132,132,132,-320,-321,132,132,132,132,132,132,132,132,132,132,132,132,132,132,132,755,663,132,132,663,132,132,-343,132,132,132,132,132,132,132,132,132,663,132,132,132,132,132,132,132,132,132,132,132,132,132,]),'LENGTH':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,-320,-321,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,-343,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,137,]),'SUBSTRING':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,508,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,780,818,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,691,138,138,138,138,138,-320,-321,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,-343,138,138,138,138,691,691,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,138,]),'TRIM':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,508,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,780,818,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,690,140,140,140,140,140,-320,-321,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,-343,140,140,140,140,690,690,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,]),'MD5':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,508,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,780,818,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,688,141,141,141,141,141,-320,-321,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,-343,141,141,141,141,688,688,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,141,]),'SHA':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,-320,-321,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,-343,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,142,]),'SUBSTR':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,508,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,780,818,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,692,143,143,143,143,143,-320,-321,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,-343,143,143,143,143,692,692,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,143,]),'GETBYTE':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,-320,-321,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,-343,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,144,]),'SETBYTE':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,-320,-321,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,-343,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,145,]),'CONVERT':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,-320,-321,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,-343,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,146,]),'ENCODE':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,-320,-321,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,-343,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,147,]),'DECODE':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,731,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,-320,-321,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,-343,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,148,]),'PLECA':([22,67,75,139,149,150,152,209,290,460,461,462,463,464,465,],[149,149,-84,-83,288,292,-82,149,-84,-76,-77,-78,-79,-80,-81,]),'VIRGULILLA':([22,67,209,],[151,151,151,]),'DECIMAL':([22,29,30,67,132,149,151,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,288,291,292,293,296,297,298,299,300,301,303,306,313,314,315,316,317,318,341,374,378,458,459,469,488,508,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,628,634,674,704,705,730,731,740,755,756,768,780,818,819,821,822,823,824,832,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[152,174,174,152,174,152,152,174,174,174,174,152,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,152,152,152,152,152,152,152,152,152,152,174,174,174,174,174,174,174,174,174,174,174,152,152,174,654,685,174,174,174,174,174,-320,-321,174,174,174,174,174,174,174,174,174,174,174,174,174,174,174,654,174,174,654,174,174,-343,174,174,174,174,685,685,174,174,174,174,174,654,174,174,174,174,174,174,174,174,174,174,174,174,174,]),'ENTERO':([22,29,30,67,132,149,151,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,288,291,292,293,296,297,298,299,300,301,303,306,313,314,315,316,317,318,333,341,374,378,458,459,469,502,508,509,536,543,548,549,550,551,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,621,625,634,674,705,717,730,731,740,755,756,768,780,792,793,794,796,818,819,821,822,823,824,842,844,864,867,868,889,890,923,925,927,929,940,941,944,970,971,983,992,1003,1010,1011,],[139,173,173,139,173,139,139,173,173,173,173,139,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,139,139,139,139,139,139,139,139,139,139,173,173,173,173,173,173,173,173,503,173,173,173,139,139,173,680,684,173,173,173,173,173,-320,-321,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,757,758,173,173,173,841,173,-343,173,173,173,173,684,891,892,893,894,684,173,173,173,173,173,173,173,173,938,939,173,959,173,979,173,173,173,173,173,997,998,173,173,173,1018,1019,]),'DOSPUNTOS':([24,135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,305,319,320,412,413,442,449,450,452,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,626,627,629,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[154,-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,468,-362,-363,-101,-102,-149,626,627,629,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,759,760,762,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'PUNTO':([24,75,176,486,772,],[156,222,322,647,878,]),'IGUAL':([24,135,136,154,164,165,166,167,168,171,173,174,175,176,177,178,274,305,319,320,331,333,343,376,412,413,442,468,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,695,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[155,-150,-151,303,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,469,-362,-363,498,502,509,554,-101,-102,-149,634,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,824,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'NOT':([26,135,136,164,165,166,167,168,171,173,174,175,176,177,178,186,221,274,319,320,341,376,378,412,413,442,475,476,477,478,479,480,481,482,536,549,550,551,561,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,650,651,652,653,654,655,656,658,662,663,664,665,666,667,674,684,685,686,687,705,752,761,789,790,795,797,798,799,800,801,802,803,831,858,859,860,861,862,863,872,881,882,883,889,895,906,923,936,937,960,961,962,963,968,969,984,985,992,994,1002,1004,1006,1013,1021,1023,1024,],[158,-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,329,378,-152,-362,-363,378,563,378,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,378,378,-320,-321,738,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,782,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,378,-303,-304,-305,-306,378,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,916,-131,-132,-117,-118,-119,-120,-100,782,782,782,378,-241,-308,378,-147,-148,-245,-235,-236,-246,-307,-309,-91,-95,378,-244,-96,-99,782,-124,-97,-310,-311,]),'WHEN':([27,74,135,136,159,160,164,165,166,167,168,171,173,174,175,176,177,178,219,220,274,308,319,320,372,373,412,413,442,475,476,477,478,479,480,481,482,546,547,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,640,641,649,651,652,653,654,655,656,658,662,663,664,665,666,667,720,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,945,960,961,962,963,984,985,994,1002,1004,1005,1013,1021,],[161,221,-150,-151,161,-388,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,221,-67,-152,-387,-362,-363,-67,-64,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-63,-66,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-389,-390,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-65,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-385,-245,-235,-236,-246,-91,-95,-244,-96,-99,-384,-124,-97,]),'PRINT_STRICT_PARAMS':([28,],[162,]),'MAS':([29,30,75,132,135,136,139,150,152,155,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,274,275,277,278,279,280,281,282,283,284,285,286,287,289,290,302,303,304,306,313,314,315,316,317,318,319,320,321,341,369,374,376,378,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,460,461,462,463,464,465,466,469,475,476,477,478,479,480,481,482,509,536,543,547,548,549,550,551,552,553,554,555,556,557,558,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,616,617,620,622,623,624,631,632,634,635,649,651,652,653,654,655,656,658,662,663,664,665,666,667,674,693,705,719,720,722,723,724,725,726,727,728,730,731,740,746,747,748,749,750,751,752,753,754,755,756,761,764,768,789,790,795,797,798,799,800,801,802,803,819,821,822,823,824,842,843,844,858,859,860,861,862,863,864,865,866,872,875,889,895,905,907,908,909,910,923,926,927,928,929,935,936,937,940,941,944,960,961,962,963,980,981,983,984,985,986,987,989,992,994,1001,1002,1003,1004,1013,1014,1021,],[169,169,-84,169,-150,-151,-83,296,-82,169,313,-167,-168,-169,-170,-171,169,169,-361,169,-365,-366,-367,-368,-374,-375,313,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,169,313,169,169,169,169,169,169,169,169,169,169,169,169,296,-84,296,169,313,169,169,169,169,169,169,169,-362,-363,313,169,313,169,313,169,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,-101,-102,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,313,-149,313,313,313,313,313,313,313,313,313,313,313,296,296,296,296,-76,-77,-78,-79,-80,-81,313,169,-355,-356,-357,-358,-359,-360,-364,-369,169,169,169,313,169,169,-320,-321,169,169,169,169,169,169,169,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,169,169,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,169,169,169,169,169,169,-90,-92,-93,-94,296,296,169,313,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,169,313,169,313,313,313,313,313,313,313,313,313,169,-343,169,313,313,313,313,313,313,-121,313,313,169,169,-98,313,169,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,169,169,169,169,169,169,313,169,-131,-132,-117,-118,-119,-120,169,313,313,-100,313,169,-241,313,313,313,313,313,169,313,169,313,169,313,-147,-148,169,169,169,-245,-235,-236,-246,313,313,169,-91,-95,313,313,313,169,-244,313,-96,169,-99,-124,313,-97,]),'GUION':([29,30,75,132,135,136,139,150,152,155,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,274,275,277,278,279,280,281,282,283,284,285,286,287,289,290,302,303,304,306,313,314,315,316,317,318,319,320,321,341,369,374,376,378,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,460,461,462,463,464,465,466,469,475,476,477,478,479,480,481,482,509,536,543,547,548,549,550,551,552,553,554,555,556,557,558,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,616,617,620,622,623,624,631,632,634,635,649,651,652,653,654,655,656,658,662,663,664,665,666,667,674,693,705,719,720,722,723,724,725,726,727,728,730,731,740,746,747,748,749,750,751,752,753,754,755,756,761,764,768,789,790,795,797,798,799,800,801,802,803,819,821,822,823,824,842,843,844,858,859,860,861,862,863,864,865,866,872,875,889,895,905,907,908,909,910,923,926,927,928,929,935,936,937,940,941,944,960,961,962,963,980,981,983,984,985,986,987,989,992,994,1001,1002,1003,1004,1013,1014,1021,],[170,170,-84,170,-150,-151,-83,297,-82,170,314,-167,-168,-169,-170,-171,170,170,-361,170,-365,-366,-367,-368,-374,-375,314,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,314,170,170,170,170,170,170,170,170,170,170,170,170,297,-84,297,170,314,170,170,170,170,170,170,170,-362,-363,314,170,314,170,314,170,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,-101,-102,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,-149,314,314,314,314,314,314,314,314,314,314,314,297,297,297,297,-76,-77,-78,-79,-80,-81,314,170,-355,-356,-357,-358,-359,-360,-364,-369,170,170,170,314,170,170,-320,-321,170,170,170,170,170,170,170,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,170,170,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,170,170,170,170,170,170,-90,-92,-93,-94,297,297,170,314,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,170,314,170,314,314,314,314,314,314,314,314,314,170,-343,170,314,314,314,314,314,314,-121,314,314,170,170,-98,314,170,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,170,170,170,170,170,170,314,170,-131,-132,-117,-118,-119,-120,170,314,314,-100,314,170,-241,314,314,314,314,314,170,314,170,314,170,314,-147,-148,170,170,170,-245,-235,-236,-246,314,314,170,-91,-95,314,314,314,170,-244,314,-96,170,-99,-124,314,-97,]),'CADENA':([29,30,69,71,75,76,77,78,79,80,81,132,135,136,139,152,155,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,191,211,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,274,275,277,278,279,280,281,282,283,284,285,286,287,289,290,302,303,306,313,314,315,316,317,318,319,320,331,341,359,360,362,365,366,374,378,381,382,383,412,413,442,454,455,456,457,460,461,462,463,464,465,469,475,476,477,478,479,480,481,482,498,508,509,536,541,542,543,544,545,548,549,550,551,552,553,554,555,556,557,558,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,616,617,620,622,623,624,630,631,632,634,648,649,651,652,653,654,655,656,658,662,663,664,665,666,667,674,705,715,718,730,731,740,752,755,756,761,768,780,789,790,795,797,798,799,800,801,802,803,818,819,821,822,823,824,842,844,858,859,860,861,862,863,864,872,880,889,895,923,927,929,936,937,940,941,942,944,960,961,962,963,983,984,985,992,994,1002,1003,1004,1013,1021,],[175,175,213,-51,-159,-55,-56,-57,-58,-59,-60,175,-150,-151,-83,-82,175,-167,-168,-169,-170,-171,175,175,-361,175,-365,-366,-367,-368,-374,-375,336,364,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,-152,175,175,175,175,175,175,175,175,175,175,175,175,-68,-84,-69,175,175,175,175,175,175,175,175,-362,-363,501,175,213,-44,213,-50,-372,175,175,-160,-161,-370,-101,-102,-149,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,175,-355,-356,-357,-358,-359,-360,-364,-369,501,686,175,175,-373,-52,175,-53,-54,175,175,-320,-321,175,175,175,175,175,175,175,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,175,175,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,175,175,175,175,175,175,-90,-92,-93,-94,763,-74,-75,175,775,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,175,175,213,-45,175,-343,175,-121,175,175,-98,175,686,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,686,175,175,175,175,175,175,175,-131,-132,-117,-118,-119,-120,175,-100,949,175,-241,175,175,175,-147,-148,175,175,988,175,-245,-235,-236,-246,175,-91,-95,175,-244,-96,175,-99,-124,-97,]),'TRUE':([29,30,132,155,169,170,172,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,508,509,536,543,548,549,550,551,552,553,554,555,556,557,558,561,581,582,611,612,613,614,616,617,634,674,705,730,731,738,740,755,756,768,780,818,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,-320,-321,177,177,177,177,177,177,177,735,177,177,177,177,177,177,177,177,177,177,177,177,-343,848,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,]),'FALSE':([29,30,132,155,169,170,172,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,508,509,536,543,548,549,550,551,552,553,554,555,556,557,558,561,581,582,611,612,613,614,616,617,634,674,705,730,731,738,740,755,756,768,780,818,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,-320,-321,178,178,178,178,178,178,178,736,178,178,178,178,178,178,178,178,178,178,178,178,-343,846,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,]),'REPLACE':([35,],[184,]),'LIKE':([43,],[191,]),'SET':([56,708,],[199,831,]),'ALL':([63,64,65,135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[203,203,203,-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,565,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'PARENDER':([66,68,69,71,75,76,77,78,79,80,81,135,136,139,152,153,164,165,166,167,168,171,173,174,175,176,177,178,206,208,210,212,213,214,215,251,252,274,276,289,290,302,306,319,320,321,358,359,360,362,363,364,365,366,368,369,370,377,379,381,382,383,385,386,387,388,389,390,391,392,393,394,395,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,432,442,443,445,446,447,454,455,456,457,460,461,462,463,464,465,470,475,476,477,478,479,480,481,482,486,489,490,533,534,538,539,540,541,542,544,545,559,560,567,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,615,620,622,623,624,631,632,649,650,651,652,653,654,655,656,658,662,663,664,665,666,667,673,675,682,683,684,685,686,687,715,716,718,719,721,722,723,724,725,726,727,729,732,734,735,736,737,745,746,747,748,749,750,751,752,753,761,763,772,773,774,775,776,778,781,783,784,786,787,789,790,795,797,798,799,800,801,802,803,807,811,812,813,820,828,837,838,839,840,841,845,846,847,848,849,851,852,854,855,856,857,858,859,860,861,862,863,865,866,872,881,882,883,884,885,887,891,892,893,894,895,897,898,899,900,901,904,905,906,907,913,914,919,920,922,924,926,928,930,931,932,933,934,936,937,938,939,947,949,950,952,953,954,955,958,959,960,961,962,963,964,965,967,968,969,972,978,979,980,981,982,984,985,986,988,990,991,993,994,1001,1002,1004,1006,1007,1013,1014,1015,1016,1018,1019,1021,1022,1023,1024,1025,1026,],[-32,-47,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-22,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-28,-46,-49,-163,-165,365,-29,412,413,-152,442,-68,-84,-69,471,-362,-363,481,-34,-166,-44,-166,-162,-164,-50,-372,542,-62,544,-319,-323,-160,-161,-370,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,-101,-102,597,598,599,600,601,602,603,604,605,606,607,608,609,610,-123,-149,620,622,623,624,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,636,-355,-356,-357,-358,-359,-360,-364,-369,-225,668,-194,-30,-31,-43,718,-48,-373,-52,-53,-54,-331,-332,-322,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,752,-90,-92,-93,-94,-74,-75,-243,-217,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-199,-200,817,-302,-303,-304,-305,-306,-166,-41,-45,-61,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,857,858,859,860,861,862,863,-121,-122,-98,872,-223,-224,879,-179,-195,-204,-208,-217,-211,-217,-214,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-193,900,901,-221,906,912,-42,-33,-38,-38,-40,-349,-350,-351,-352,-353,930,-335,932,933,934,-340,-131,-132,-117,-118,-119,-120,936,937,-100,-217,-217,-217,-217,-210,-213,960,961,962,963,-241,965,966,-198,-218,-219,-301,968,-308,969,973,974,976,977,-35,-36,-342,-344,-334,982,-337,-338,-339,-147,-148,984,985,-222,-178,-201,-203,-207,-209,-217,993,994,-245,-235,-236,-246,995,-196,-220,-307,-309,999,-37,-39,-341,-354,-336,-91,-95,1002,1004,1006,-212,-216,-244,1013,-96,-99,-217,1016,-124,1021,-202,-215,1023,1024,-97,1026,-310,-311,1027,-197,]),'COMA':([68,69,71,75,76,77,78,79,80,81,135,136,139,152,164,165,166,167,168,171,173,174,175,176,177,178,208,210,212,213,274,289,290,302,319,320,344,345,346,349,350,358,359,360,362,363,364,365,366,368,369,370,381,382,383,396,397,412,413,428,429,430,431,432,433,441,442,444,448,453,454,455,456,457,460,461,462,463,464,465,470,475,476,477,478,479,480,481,482,485,486,489,490,518,521,526,538,540,541,542,544,545,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,649,650,651,652,653,654,655,656,658,662,663,664,665,666,667,673,675,682,683,684,685,686,687,693,696,697,698,699,700,701,702,709,710,715,718,719,752,754,757,758,761,771,772,773,774,775,776,778,781,783,784,786,787,789,790,795,797,798,799,800,801,802,803,807,812,813,826,827,836,837,839,840,841,858,859,860,861,862,863,869,870,871,872,875,876,881,882,883,884,885,887,895,897,898,899,900,901,904,906,908,909,910,912,913,914,915,917,918,919,920,921,935,936,937,947,949,950,952,953,954,955,960,961,962,963,965,967,968,969,972,974,975,976,977,979,984,985,987,991,993,994,997,998,999,1002,1004,1006,1013,1015,1016,1021,1022,1023,1024,1025,1026,1027,],[209,-166,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,209,-49,-163,-165,-152,-68,-84,-69,-362,-363,511,513,-270,517,-277,535,-166,-44,-166,-162,-164,-50,-372,543,-62,543,-160,-161,-370,581,582,-101,-102,611,612,613,614,616,617,619,-149,621,625,630,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,543,-355,-356,-357,-358,-359,-360,-364,-369,646,-225,669,-194,-278,-287,-280,-43,-48,-373,-52,-53,-54,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-243,-217,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-199,-200,818,-302,-303,-304,-305,-306,-315,-269,-271,-272,-273,-274,-275,-276,-293,-294,-166,-45,-61,-121,864,867,868,-98,646,-223,-224,880,-179,-195,-204,-208,-217,-211,-217,-214,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-193,902,-221,-286,-285,-282,-42,902,925,-40,-131,-132,-117,-118,-119,-120,940,941,942,-100,944,646,-217,-217,-217,-217,-210,-213,-241,902,902,-198,-218,-219,-301,-308,970,971,-314,-288,902,902,-279,-292,-283,902,902,-281,983,-147,-148,-222,-178,-201,-203,-207,-209,-217,-245,-235,-236,-246,-196,-220,-307,-309,646,-290,-291,-295,-296,-39,-91,-95,1003,-212,-216,-244,1010,1011,-284,-96,-99,-217,-124,-202,-215,-97,902,-310,-311,902,-197,-289,]),'AS':([69,71,75,76,77,78,79,80,81,135,136,139,152,164,165,166,167,168,171,173,174,175,176,177,178,181,274,289,290,302,319,320,359,360,362,365,366,381,382,383,412,413,442,451,454,455,456,457,460,461,462,463,464,465,475,476,477,478,479,480,481,482,541,542,544,545,569,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,649,651,652,653,654,655,656,658,662,663,664,665,666,667,715,718,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[211,-51,-159,-55,-56,-57,-58,-59,-60,-150,-151,-83,-82,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,326,-152,-68,-84,-69,-362,-363,211,-44,211,-50,-372,-160,-161,-370,-101,-102,-149,628,-70,-71,-72,-73,-76,-77,-78,-79,-80,-81,-355,-356,-357,-358,-359,-360,-364,-369,-373,-52,-53,-54,-371,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-74,-75,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,211,-45,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'AMPERSON':([75,139,150,152,290,460,461,462,463,464,465,],[-84,-83,291,-82,-84,-76,-77,-78,-79,-80,-81,]),'MENORQUE':([75,135,136,139,150,152,164,165,166,167,168,171,173,174,175,176,177,178,274,290,294,319,320,376,412,413,442,460,461,462,463,464,465,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-84,-150,-151,-83,294,-82,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-84,458,-362,-363,552,-101,-102,-149,-76,-77,-78,-79,-80,-81,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'MAYORQUE':([75,135,136,139,150,152,164,165,166,167,168,171,173,174,175,176,177,178,274,290,295,319,320,376,412,413,442,460,461,462,463,464,465,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-84,-150,-151,-83,295,-82,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-84,459,-362,-363,553,-101,-102,-149,-76,-77,-78,-79,-80,-81,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'BARRA':([75,135,136,139,150,152,163,164,165,166,167,168,171,173,174,175,176,177,178,179,274,289,290,302,304,319,320,321,369,376,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,460,461,462,463,464,465,466,475,476,477,478,479,480,481,482,547,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,635,649,651,652,653,654,655,656,658,662,663,664,665,666,667,693,719,720,722,723,724,725,726,727,728,746,747,748,749,750,751,752,753,754,761,764,789,790,795,797,798,799,800,801,802,803,843,858,859,860,861,862,863,865,866,872,875,895,905,907,908,909,910,926,928,935,936,937,960,961,962,963,980,981,984,985,986,987,989,994,1001,1002,1004,1013,1014,1021,],[-84,-150,-151,-83,298,-82,315,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,315,315,298,-84,298,315,-362,-363,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,-101,-102,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,-149,315,315,315,315,315,315,315,315,315,315,315,298,298,298,298,298,298,-78,-79,-80,-81,315,315,315,-357,-358,-359,-360,-364,-369,315,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,298,298,315,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,-121,315,315,-98,315,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,315,-131,-132,-117,-118,-119,-120,315,315,-100,315,-241,315,315,315,315,315,315,315,315,-147,-148,-245,-235,-236,-246,315,315,-91,-95,315,315,315,-244,315,-96,-99,-124,315,-97,]),'PORCENTAJE':([75,135,136,139,150,152,163,164,165,166,167,168,171,173,174,175,176,177,178,179,274,289,290,302,304,319,320,321,369,376,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,460,461,462,463,464,465,466,475,476,477,478,479,480,481,482,547,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,635,649,651,652,653,654,655,656,658,662,663,664,665,666,667,693,719,720,722,723,724,725,726,727,728,746,747,748,749,750,751,752,753,754,761,764,789,790,795,797,798,799,800,801,802,803,843,858,859,860,861,862,863,865,866,872,875,895,905,907,908,909,910,926,928,935,936,937,960,961,962,963,980,981,984,985,986,987,989,994,1001,1002,1004,1013,1014,1021,],[-84,-150,-151,-83,300,-82,317,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,317,317,300,-84,300,317,-362,-363,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,-101,-102,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,-149,317,317,317,317,317,317,317,317,317,317,317,300,300,300,300,300,300,-78,-79,-80,-81,317,317,317,-357,-358,-359,-360,-364,-369,317,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,300,300,317,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,-121,317,317,-98,317,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,317,-131,-132,-117,-118,-119,-120,317,317,-100,317,-241,317,317,317,317,317,317,317,317,-147,-148,-245,-235,-236,-246,317,317,-91,-95,317,317,317,-244,317,-96,-99,-124,317,-97,]),'POTENCIA':([75,135,136,139,150,152,163,164,165,166,167,168,171,173,174,175,176,177,178,179,274,289,290,302,304,319,320,321,369,376,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,460,461,462,463,464,465,466,475,476,477,478,479,480,481,482,547,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,631,632,635,649,651,652,653,654,655,656,658,662,663,664,665,666,667,693,719,720,722,723,724,725,726,727,728,746,747,748,749,750,751,752,753,754,761,764,789,790,795,797,798,799,800,801,802,803,843,858,859,860,861,862,863,865,866,872,875,895,905,907,908,909,910,926,928,935,936,937,960,961,962,963,980,981,984,985,986,987,989,994,1001,1002,1004,1013,1014,1021,],[-84,-150,-151,-83,301,-82,318,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,318,318,301,-84,301,318,-362,-363,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,-101,-102,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,-149,318,318,318,318,318,318,318,318,318,318,318,301,301,301,301,301,301,301,301,301,-81,318,318,318,318,318,318,-360,-364,-369,318,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,301,301,318,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,318,-121,318,318,-98,318,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,318,-131,-132,-117,-118,-119,-120,318,318,-100,318,-241,318,318,318,318,318,318,318,318,-147,-148,-245,-235,-236,-246,318,318,-91,-95,318,318,318,-244,318,-96,-99,-124,318,-97,]),'USING':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,179,274,319,320,412,413,442,475,476,477,478,479,480,481,482,484,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,642,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,324,-152,-362,-363,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,643,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,769,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'MENORIGUALQUE':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,555,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'MAYORIGUALQUE':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,556,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'DIFERENTELL':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,557,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'BETWEEN':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,563,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,558,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,740,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'ISNULL':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,559,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'NOTNULL':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,560,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'IS':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,561,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'IN':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,563,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,562,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,741,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'ANY':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,564,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'SOME':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,376,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,566,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'END':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,219,220,274,319,320,372,373,412,413,442,475,476,477,478,479,480,481,482,546,547,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,638,649,651,652,653,654,655,656,658,662,663,664,665,666,667,720,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,945,960,961,962,963,984,985,994,1002,1004,1005,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,371,-67,-152,-362,-363,-67,-64,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-63,-66,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,767,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-65,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-385,-245,-235,-236,-246,-91,-95,-244,-96,-99,-384,-124,-97,]),'WHERE':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,197,212,213,274,319,320,344,358,359,360,363,364,412,413,442,475,476,477,478,479,480,481,482,538,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,693,715,718,752,761,789,790,795,797,798,799,800,801,802,803,837,858,859,860,861,862,863,872,895,910,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,341,-163,-165,-152,-362,-363,341,536,-166,-44,-162,-164,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-43,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-315,-166,-45,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-42,-131,-132,-117,-118,-119,-120,-100,-241,-314,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'ELSE':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,220,274,319,320,372,412,413,442,475,476,477,478,479,480,481,482,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,720,752,761,789,790,795,797,798,799,800,801,802,803,858,859,860,861,862,863,872,895,936,937,960,961,962,963,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,374,-152,-362,-363,374,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-65,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-131,-132,-117,-118,-119,-120,-100,-241,-147,-148,-245,-235,-236,-246,-91,-95,-244,-96,-99,-124,-97,]),'THEN':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,307,309,310,319,320,375,377,379,412,413,442,475,476,477,478,479,480,481,482,559,560,567,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,789,790,795,797,798,799,800,801,802,803,845,846,847,848,849,852,857,858,859,860,861,862,863,872,895,926,928,930,932,933,934,936,937,960,961,962,963,980,981,982,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,472,473,474,-362,-363,548,-319,-323,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-331,-332,-322,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-241,-342,-344,-334,-337,-338,-339,-147,-148,-245,-235,-236,-246,-341,-354,-336,-91,-95,-244,-96,-99,-124,-97,]),'AND':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,274,319,320,375,377,379,412,413,442,475,476,477,478,479,480,481,482,507,559,560,567,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,716,721,722,723,724,725,726,727,728,729,732,734,735,736,737,752,761,789,790,795,797,798,799,800,801,802,803,811,828,843,845,846,847,848,849,852,857,858,859,860,861,862,863,872,895,926,928,930,932,933,934,936,937,958,960,961,962,963,978,980,981,982,984,985,994,1002,1004,1007,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-152,-362,-363,550,-319,-323,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,550,-331,-332,-322,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,550,-318,-324,-325,-326,-327,-328,-329,842,-330,-333,-345,-346,-347,-348,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,550,550,927,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-241,-342,-344,-334,-337,-338,-339,-147,-148,550,-245,-235,-236,-246,550,-341,-354,-336,-91,-95,-244,-96,-99,550,-124,-97,]),'GROUP':([135,136,164,165,166,167,168,171,173,174,175,176,177,178,212,213,274,319,320,358,359,360,363,364,377,379,412,413,442,475,476,477,478,479,480,481,482,538,559,560,567,570,571,572,573,574,575,576,577,578,579,580,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,620,622,623,624,649,651,652,653,654,655,656,658,662,663,664,665,666,667,715,716,718,721,722,723,724,725,726,727,729,732,734,735,736,737,752,761,789,790,795,797,798,799,800,801,802,803,837,845,846,847,848,849,852,857,858,859,860,861,862,863,872,895,926,928,930,932,933,934,936,937,960,961,962,963,980,981,982,984,985,994,1002,1004,1013,1021,],[-150,-151,-167,-168,-169,-170,-171,-361,-365,-366,-367,-368,-374,-375,-163,-165,-152,-362,-363,537,-166,-44,-162,-164,-319,-323,-101,-102,-149,-355,-356,-357,-358,-359,-360,-364,-369,-43,-331,-332,-322,-85,-86,-87,-88,-89,-125,-126,-127,-128,-129,-130,-133,-134,-135,-136,-137,-138,-139,-140,-141,-142,-143,-144,-145,-146,-103,-104,-105,-106,-107,-108,-109,-110,-111,-112,-113,-114,-115,-116,-90,-92,-93,-94,-243,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-166,537,-45,-318,-324,-325,-326,-327,-328,-329,-330,-333,-345,-346,-347,-348,-121,-98,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-42,-349,-350,-351,-352,-353,-335,-340,-131,-132,-117,-118,-119,-120,-100,-241,-342,-344,-334,-337,-338,-339,-147,-148,-245,-235,-236,-246,-341,-354,-336,-91,-95,-244,-96,-99,-124,-97,]),'FOUND':([158,],[307,]),'NO_DATA_FOUND':([161,],[309,]),'TOO_MANY_ROWS':([161,],[310,]),'ON':([162,],[311,]),'NULL':([177,178,561,649,650,651,652,653,654,655,656,658,662,663,664,665,666,667,684,685,686,687,738,782,789,790,795,797,798,799,800,801,802,803,831,881,882,883,895,906,916,960,961,962,963,968,969,994,1006,1023,1024,],[-374,-375,734,-243,783,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-303,-304,-305,-306,849,884,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,917,783,783,783,-241,-308,975,-245,-235,-236,-246,-307,-309,-244,783,-310,-311,]),'CONSTRAINT':([177,178,327,351,353,649,650,651,652,653,654,655,656,658,662,663,664,665,666,667,669,684,685,686,687,783,786,789,790,795,797,798,799,800,801,802,803,881,882,883,884,895,906,955,960,961,962,963,968,969,994,1006,1023,1024,],[-374,-375,493,519,528,-243,785,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,493,-303,-304,-305,-306,785,888,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,785,785,785,785,-241,-308,888,-245,-235,-236,-246,-307,-309,-244,785,-310,-311,]),'UNIQUE':([177,178,327,649,650,651,652,653,654,655,656,658,662,663,664,665,666,667,669,684,685,686,687,703,783,789,790,795,797,798,799,800,801,802,803,881,882,883,884,886,895,906,960,961,962,963,968,969,994,1006,1023,1024,],[-374,-375,495,-243,786,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,495,-303,-304,-305,-306,825,786,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,786,786,786,786,955,-241,-308,-245,-235,-236,-246,-307,-309,-244,786,-310,-311,]),'CHECK':([177,178,327,351,649,650,651,652,653,654,655,656,658,662,663,664,665,666,667,669,672,684,685,686,687,703,783,786,789,790,795,797,798,799,800,801,802,803,881,882,883,884,886,895,906,955,957,960,961,962,963,968,969,994,1006,1023,1024,],[-374,-375,494,522,-243,788,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,494,810,-303,-304,-305,-306,522,788,788,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,788,788,788,788,956,-241,-308,788,956,-245,-235,-236,-246,-307,-309,-244,788,-310,-311,]),'OWNER':([187,200,513,677,],[331,348,348,331,]),'MODE':([187,499,500,501,677,678,],[333,333,-184,-185,333,333,]),'EXISTS':([194,221,329,341,378,536,549,550,551,674,705,889,923,992,],[338,380,497,380,380,380,380,-320,-321,380,380,380,380,380,]),'VALUES':([198,],[342,]),'RENAME':([200,201,513,517,],[347,354,347,354,]),'ADD':([201,517,],[351,351,]),'STRICT':([216,223,323,],[367,384,483,]),'YEAR':([273,666,],[435,803,]),'MONTH':([273,666,],[436,799,]),'DAY':([273,],[437,]),'HOUR':([273,666,],[438,800,]),'MINUTE':([273,666,],[439,801,]),'SECOND':([273,666,],[440,802,]),'ENUM':([326,],[487,]),'PRIMARY':([327,351,353,649,650,651,652,653,654,655,656,658,662,663,664,665,666,667,669,703,789,790,795,797,798,799,800,801,802,803,895,960,961,962,963,994,],[491,524,529,-243,777,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,491,524,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-241,-245,-235,-236,-246,-244,]),'FOREIGN':([327,351,353,669,703,],[492,523,530,492,523,]),'TO':([347,348,532,713,],[514,515,714,835,]),'COLUMN':([351,352,353,354,],[520,525,527,531,]),'RAISE':([472,473,474,],[639,639,639,]),'SMALLINT':([488,628,704,832,],[651,651,651,651,]),'INTEGER':([488,628,704,832,],[652,652,652,652,]),'BIGINT':([488,628,704,832,],[653,653,653,653,]),'NUMERIC':([488,628,704,832,],[655,655,655,655,]),'REAL':([488,628,704,832,],[656,656,656,656,]),'DOUBLE':([488,628,704,832,],[657,657,657,657,]),'MONEY':([488,628,704,832,],[658,658,658,658,]),'CHARACTER':([488,628,704,832,],[659,659,659,659,]),'VARCHAR':([488,628,704,832,],[660,660,660,660,]),'CHAR':([488,628,704,832,],[661,661,661,661,]),'TEXT':([488,628,704,832,],[662,662,662,662,]),'TIME':([488,628,704,832,],[664,664,664,664,]),'DATE':([488,628,704,832,],[665,665,665,665,]),'INTERVAL':([488,619,628,704,832,],[666,756,666,666,666,]),'BOLEANO':([488,628,704,832,],[667,667,667,667,]),'KEY':([491,492,523,524,529,530,777,],[670,671,706,707,711,712,881,]),'CURRENT_USER':([515,],[700,]),'SESSION_USER':([515,],[701,]),'BY':([537,],[717,]),'SYMMETRIC':([558,740,],[731,731,]),'UNKNOWN':([561,738,],[737,847,]),'REFERENCES':([649,650,651,652,653,654,655,656,658,662,663,664,665,666,667,789,790,795,797,798,799,800,801,802,803,895,960,961,962,963,966,973,994,],[-243,779,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,-241,-245,-235,-236,-246,996,1000,-244,]),'DEFAULT':([649,650,651,652,653,654,655,656,658,662,663,664,665,666,667,789,790,795,797,798,799,800,801,802,803,881,882,895,960,961,962,963,994,1006,],[-243,780,-226,-227,-228,-229,-230,-231,-233,-237,-247,-247,-240,-253,-242,-232,-234,-238,-239,-247,-248,-249,-250,-251,-252,780,780,-241,-245,-235,-236,-246,-244,780,]),'PRECISION':([657,],[789,]),'VARYING':([659,],[791,]),'INHERITS':([668,],[805,]),'BYTEA':([759,760,762,],[869,870,871,]),'HAVING':([813,839,840,841,967,979,],[-221,923,923,-40,-220,-39,]),} _lr_action = {} for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = {} _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'init':([0,],[1,]),'instrucciones':([0,],[2,]),'instruccion':([0,2,],[3,31,]),'select':([0,2,70,202,204,205,361,568,739,742,743,744,853,],[12,12,214,355,356,357,539,745,851,854,855,856,931,]),'querys':([0,2,],[13,13,]),'problem':([0,2,4,5,6,7,8,9,10,11,70,202,204,205,361,568,739,742,743,744,853,],[14,14,37,41,44,48,51,54,57,61,215,215,215,215,215,215,215,215,215,215,215,]),'pl_asignacion':([0,2,],[15,15,]),'pl_perform':([0,2,],[16,16,]),'pl_if_not_found':([0,2,],[17,17,]),'pl_w_excepcion':([0,2,],[18,18,]),'p_print_strict':([0,2,],[19,19,]),'pl_return':([0,2,],[20,20,]),'pl_execute':([0,2,],[21,21,]),'create':([4,],[32,]),'use':([5,],[38,]),'show':([6,],[42,]),'drop':([7,],[45,]),'delete':([8,],[49,]),'insert':([9,],[52,]),'update':([10,],[55,]),'alter':([11,],[58,]),'parametrosselect':([22,],[66,]),'listadeseleccion':([22,67,],[68,208,]),'listadeseleccionados':([22,67,209,],[69,69,362,]),'funcionesmatematicassimples':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[76,164,164,76,164,164,164,164,164,76,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,164,]),'funcionestrigonometricas':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[77,165,165,77,165,165,165,165,165,77,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,]),'funcionesmatematicas':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[78,166,166,78,166,166,166,166,166,78,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,]),'funcionesdefechas':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[79,167,167,79,167,167,167,167,167,79,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,167,]),'funcionesbinarias':([22,29,30,67,132,155,169,170,172,209,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[80,168,168,80,168,168,168,168,168,80,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,168,]),'operadoresselect':([22,67,209,],[81,81,81,]),'argumentodeoperadores':([22,67,149,151,209,288,291,292,293,296,297,298,299,300,301,458,459,],[150,150,289,302,150,454,455,456,457,460,461,462,463,464,465,631,632,]),'instrucciones1':([27,],[159,]),'instruccion2':([27,159,],[160,308,]),'argument':([29,30,132,155,169,170,172,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,509,536,543,548,549,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,740,755,756,768,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[163,179,274,304,319,320,321,369,369,376,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,441,443,444,445,446,447,448,449,450,451,452,453,466,369,475,476,477,478,479,480,376,547,376,635,693,376,719,720,376,722,723,724,725,726,727,728,746,747,748,749,750,751,753,754,764,376,376,843,728,865,866,875,905,907,908,909,910,926,928,935,376,376,980,981,986,987,989,1001,376,1014,]),'boleano':([29,30,132,155,169,170,172,217,218,221,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,275,277,278,279,280,281,282,283,284,285,286,287,303,306,313,314,315,316,317,318,341,374,378,469,508,509,536,543,548,549,552,553,554,555,556,557,558,581,582,611,612,613,614,616,617,634,674,705,730,740,755,756,768,780,818,819,821,822,823,824,842,844,864,889,923,927,929,940,941,944,983,992,1003,],[171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,687,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,687,687,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,]),'createenum':([33,],[180,]),'createtable':([34,],[182,]),'createdatabase':([36,328,],[185,496,]),'likeopcional':([43,],[190,]),'dropdb':([46,],[193,]),'allopcional':([63,64,65,],[202,204,205,]),'fromopcional':([66,],[206,]),'asopcional':([69,359,362,715,],[210,538,540,837,]),'cases':([74,],[219,]),'case':([74,219,],[220,372,]),'databaseowner':([187,677,],[330,814,]),'databasemode':([187,499,677,678,],[332,679,332,815,]),'condicionesops':([197,344,],[340,510,]),'asignaciones':([199,],[344,]),'alterdbs':([200,],[345,]),'alterdb':([200,513,],[346,696,]),'altertables':([201,],[349,]),'altertable':([201,517,],[350,702,]),'parametrosfrom':([207,],[358,]),'parametrosfromr':([207,535,],[359,715,]),'listadeargumentos':([217,218,306,],[368,370,470,]),'elsecase':([220,372,],[373,546,]),'condiciones':([221,341,536,674,705,889,923,992,],[375,507,716,811,828,958,978,1007,]),'condicion':([221,341,378,536,549,674,705,889,923,992,],[377,377,567,377,721,377,377,377,377,377,]),'condicions':([221,341,378,536,549,674,705,889,923,992,],[379,379,379,379,379,379,379,379,379,379,]),'partedelafecha':([273,],[434,]),'listaidcts':([324,643,769,911,],[485,771,876,972,]),'tabledescriptions':([327,],[489,]),'tabledescription':([327,669,],[490,807,]),'tipoowner':([331,498,],[499,678,]),'alteraddc':([351,],[518,]),'alteradd':([351,703,],[521,826,]),'tipodedrop':([353,],[526,]),'whereopcional':([358,],[533,]),'groupbyopcional':([358,716,],[534,838,]),'comparacionlogica':([375,507,716,811,828,958,978,1007,],[549,549,549,549,549,549,549,549,]),'tipoderound':([432,],[615,]),'raiseexception':([472,473,474,],[638,640,641,]),'tipo':([488,628,704,832,],[650,761,827,918,]),'finalconstraintcheck':([494,810,],[673,899,]),'finalunique':([495,],[675,]),'values':([508,],[682,]),'value':([508,780,818,],[683,883,904,]),'tipodeowner':([515,],[698,]),'betweenopcion':([558,740,],[729,852,]),'symm':([558,740,],[730,730,]),'isopcion':([561,],[732,]),'listacadenas':([648,],[774,]),'tablekey':([650,],[776,]),'tabledefault':([650,881,882,1006,],[778,950,952,1015,]),'tablenull':([650,881,882,883,1006,],[781,781,781,953,781,]),'tableconstraintunique':([650,783,881,882,883,884,1006,],[784,885,784,784,784,954,784,]),'tableconstraintcheck':([650,783,786,881,882,883,884,955,1006,],[787,787,887,787,787,787,787,991,787,]),'tipochar':([659,],[790,]),'precision':([663,664,798,],[795,797,895,]),'fields':([666,],[798,]),'tableherencia':([668,],[804,]),'listaids':([676,717,808,809,829,830,833,834,1017,1020,],[812,839,897,898,913,914,919,920,1022,1025,]),'listanumeros':([717,],[840,]),'isnotoptions':([738,],[845,]),'opcionesalterset':([831,],[915,]),'havings':([839,840,],[922,924,]),} _lr_goto = {} for _k, _v in _lr_goto_items.items(): for _x, _y in zip(_v[0], _v[1]): if not _x in _lr_goto: _lr_goto[_x] = {} _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> init","S'",1,None,None,None), ('init -> instrucciones','init',1,'p_init','gramatica.py',342), ('instrucciones -> instrucciones instruccion','instrucciones',2,'p_instrucciones_lista','gramatica.py',348), ('instrucciones -> instruccion','instrucciones',1,'p_instruciones','gramatica.py',357), ('instruccion -> CREATE create','instruccion',2,'p_instruccion','gramatica.py',366), ('instruccion -> USE use','instruccion',2,'p_instruccion','gramatica.py',367), ('instruccion -> SHOW show','instruccion',2,'p_instruccion','gramatica.py',368), ('instruccion -> DROP drop','instruccion',2,'p_instruccion','gramatica.py',369), ('instruccion -> DELETE delete','instruccion',2,'p_instruccion','gramatica.py',370), ('instruccion -> INSERT insert','instruccion',2,'p_instruccion','gramatica.py',371), ('instruccion -> UPDATE update','instruccion',2,'p_instruccion','gramatica.py',372), ('instruccion -> ALTER alter','instruccion',2,'p_instruccionAlter','gramatica.py',395), ('instruccion -> select PTCOMA','instruccion',2,'p_instruccionSelect','gramatica.py',402), ('instruccion -> querys','instruccion',1,'p_instruccionQuerys','gramatica.py',407), ('instruccion -> problem','instruccion',1,'p_instruccionError','gramatica.py',412), ('instruccion -> pl_asignacion','instruccion',1,'p_instruccion_asignacion','gramatica.py',418), ('instruccion -> pl_perform','instruccion',1,'p_instruccion_perform','gramatica.py',424), ('instruccion -> pl_if_not_found','instruccion',1,'p_instruccion_if_not_found','gramatica.py',430), ('instruccion -> pl_w_excepcion','instruccion',1,'p_instruccion_exception','gramatica.py',440), ('instruccion -> p_print_strict','instruccion',1,'p_instruccion_printstrict','gramatica.py',446), ('instruccion -> pl_return','instruccion',1,'p_instruccion_return','gramatica.py',452), ('instruccion -> pl_execute','instruccion',1,'p_instruccion_pl_execute','gramatica.py',458), ('problem -> error PTCOMA','problem',2,'p_problem','gramatica.py',466), ('querys -> select UNION allopcional select','querys',4,'p_querys','gramatica.py',472), ('querys -> select INTERSECT allopcional select','querys',4,'p_querys','gramatica.py',473), ('querys -> select EXCEPT allopcional select','querys',4,'p_querys','gramatica.py',474), ('allopcional -> ALL','allopcional',1,'p_all_opcional','gramatica.py',491), ('allopcional -> <empty>','allopcional',0,'p_all_opcional_null','gramatica.py',498), ('select -> SELECT parametrosselect fromopcional','select',3,'p_select','gramatica.py',505), ('select -> problem','select',1,'p_select_err','gramatica.py',515), ('fromopcional -> FROM parametrosfrom whereopcional','fromopcional',3,'p_from_opcional','gramatica.py',520), ('fromopcional -> FROM parametrosfrom groupbyopcional','fromopcional',3,'p_from_opcional_2','gramatica.py',528), ('fromopcional -> <empty>','fromopcional',0,'p_from_opcional_null','gramatica.py',536), ('whereopcional -> WHERE condiciones groupbyopcional','whereopcional',3,'p_where_opcional','gramatica.py',542), ('whereopcional -> <empty>','whereopcional',0,'p_where_opcional_null','gramatica.py',550), ('groupbyopcional -> GROUP BY listaids havings','groupbyopcional',4,'p_group_by_opcional','gramatica.py',557), ('groupbyopcional -> GROUP BY listanumeros havings','groupbyopcional',4,'p_group_by_opcional_numeros','gramatica.py',565), ('havings -> HAVING condiciones','havings',2,'p_having','gramatica.py',573), ('havings -> <empty>','havings',0,'p_having_null','gramatica.py',580), ('listanumeros -> listanumeros COMA ENTERO','listanumeros',3,'p_listanumeros_r','gramatica.py',587), ('listanumeros -> ENTERO','listanumeros',1,'p_listanumeros','gramatica.py',596), ('groupbyopcional -> <empty>','groupbyopcional',0,'p_group_by_opcional_null','gramatica.py',604), ('parametrosfrom -> parametrosfrom COMA parametrosfromr asopcional','parametrosfrom',4,'p_parametros_from','gramatica.py',611), ('parametrosfrom -> parametrosfromr asopcional','parametrosfrom',2,'p_parametros_from_r','gramatica.py',621), ('parametrosfromr -> ID','parametrosfromr',1,'p_parametros_fromr','gramatica.py',630), ('parametrosfromr -> PARENIZQ select PARENDER','parametrosfromr',3,'p_parametros_fromr','gramatica.py',631), ('parametrosselect -> DISTINCT listadeseleccion','parametrosselect',2,'p_parametros_select','gramatica.py',644), ('parametrosselect -> listadeseleccion','parametrosselect',1,'p_parametros_select_r','gramatica.py',652), ('listadeseleccion -> listadeseleccion COMA listadeseleccionados asopcional','listadeseleccion',4,'p_lista_de_seleccion','gramatica.py',659), ('listadeseleccion -> listadeseleccionados asopcional','listadeseleccion',2,'p_lista_de_seleccion_r','gramatica.py',669), ('listadeseleccionados -> PARENIZQ select PARENDER','listadeseleccionados',3,'p_lista_de_seleccionados','gramatica.py',677), ('listadeseleccionados -> ASTERISCO','listadeseleccionados',1,'p_lista_de_seleccionados','gramatica.py',678), ('listadeseleccionados -> GREATEST PARENIZQ listadeargumentos PARENDER','listadeseleccionados',4,'p_lista_de_seleccionados','gramatica.py',679), ('listadeseleccionados -> LEAST PARENIZQ listadeargumentos PARENDER','listadeseleccionados',4,'p_lista_de_seleccionados','gramatica.py',680), ('listadeseleccionados -> CASE cases END ID','listadeseleccionados',4,'p_lista_de_seleccionados','gramatica.py',681), ('listadeseleccionados -> funcionesmatematicassimples','listadeseleccionados',1,'p_lista_de_seleccionados_noterminal','gramatica.py',710), ('listadeseleccionados -> funcionestrigonometricas','listadeseleccionados',1,'p_lista_de_seleccionados_noterminal','gramatica.py',711), ('listadeseleccionados -> funcionesmatematicas','listadeseleccionados',1,'p_lista_de_seleccionados_noterminal','gramatica.py',712), ('listadeseleccionados -> funcionesdefechas','listadeseleccionados',1,'p_lista_de_seleccionados_noterminal','gramatica.py',713), ('listadeseleccionados -> funcionesbinarias','listadeseleccionados',1,'p_lista_de_seleccionados_noterminal','gramatica.py',714), ('listadeseleccionados -> operadoresselect','listadeseleccionados',1,'p_lista_de_seleccionados_noterminal','gramatica.py',715), ('listadeargumentos -> listadeargumentos COMA argument','listadeargumentos',3,'p_lista_de_argumentos','gramatica.py',728), ('listadeargumentos -> argument','listadeargumentos',1,'p_lista_de_argumentos_r','gramatica.py',737), ('cases -> cases case elsecase','cases',3,'p_casos','gramatica.py',745), ('cases -> case elsecase','cases',2,'p_casos_r','gramatica.py',755), ('case -> WHEN condiciones THEN argument','case',4,'p_case','gramatica.py',763), ('elsecase -> ELSE argument','elsecase',2,'p_else_case','gramatica.py',771), ('elsecase -> <empty>','elsecase',0,'p_else_case_null','gramatica.py',778), ('operadoresselect -> PLECA argumentodeoperadores','operadoresselect',2,'p_operadores_select_t','gramatica.py',785), ('operadoresselect -> VIRGULILLA argumentodeoperadores','operadoresselect',2,'p_operadores_select_t','gramatica.py',786), ('operadoresselect -> PLECA PLECA argumentodeoperadores','operadoresselect',3,'p_operadores_s_pleca','gramatica.py',799), ('operadoresselect -> argumentodeoperadores AMPERSON argumentodeoperadores','operadoresselect',3,'p_operadores_select_nt','gramatica.py',807), ('operadoresselect -> argumentodeoperadores PLECA argumentodeoperadores','operadoresselect',3,'p_operadores_select_nt','gramatica.py',808), ('operadoresselect -> argumentodeoperadores NUMERAL argumentodeoperadores','operadoresselect',3,'p_operadores_select_nt','gramatica.py',809), ('operadoresselect -> argumentodeoperadores MENORQUE MENORQUE argumentodeoperadores','operadoresselect',4,'p_operadores_select_nt','gramatica.py',810), ('operadoresselect -> argumentodeoperadores MAYORQUE MAYORQUE argumentodeoperadores','operadoresselect',4,'p_operadores_select_nt','gramatica.py',811), ('argumentodeoperadores -> argumentodeoperadores MAS argumentodeoperadores','argumentodeoperadores',3,'p_argumento_de_operadores','gramatica.py',835), ('argumentodeoperadores -> argumentodeoperadores GUION argumentodeoperadores','argumentodeoperadores',3,'p_argumento_de_operadores','gramatica.py',836), ('argumentodeoperadores -> argumentodeoperadores BARRA argumentodeoperadores','argumentodeoperadores',3,'p_argumento_de_operadores','gramatica.py',837), ('argumentodeoperadores -> argumentodeoperadores ASTERISCO argumentodeoperadores','argumentodeoperadores',3,'p_argumento_de_operadores','gramatica.py',838), ('argumentodeoperadores -> argumentodeoperadores PORCENTAJE argumentodeoperadores','argumentodeoperadores',3,'p_argumento_de_operadores','gramatica.py',839), ('argumentodeoperadores -> argumentodeoperadores POTENCIA argumentodeoperadores','argumentodeoperadores',3,'p_argumento_de_operadores','gramatica.py',840), ('argumentodeoperadores -> DECIMAL','argumentodeoperadores',1,'p_argumento_de_operadores_decimal','gramatica.py',867), ('argumentodeoperadores -> ENTERO','argumentodeoperadores',1,'p_argumento_de_operadores_entero','gramatica.py',874), ('argumentodeoperadores -> ID','argumentodeoperadores',1,'p_argumento_de_operadores_ID','gramatica.py',881), ('funcionesmatematicassimples -> COUNT PARENIZQ argument PARENDER','funcionesmatematicassimples',4,'p_funciones_matematicas_simples','gramatica.py',888), ('funcionesmatematicassimples -> MAX PARENIZQ argument PARENDER','funcionesmatematicassimples',4,'p_funciones_matematicas_simples','gramatica.py',889), ('funcionesmatematicassimples -> SUM PARENIZQ argument PARENDER','funcionesmatematicassimples',4,'p_funciones_matematicas_simples','gramatica.py',890), ('funcionesmatematicassimples -> AVG PARENIZQ argument PARENDER','funcionesmatematicassimples',4,'p_funciones_matematicas_simples','gramatica.py',891), ('funcionesmatematicassimples -> MIN PARENIZQ argument PARENDER','funcionesmatematicassimples',4,'p_funciones_matematicas_simples','gramatica.py',892), ('funcionesbinarias -> LENGTH PARENIZQ argument PARENDER','funcionesbinarias',4,'p_funciones_binarias','gramatica.py',910), ('funcionesbinarias -> SUBSTRING PARENIZQ argument COMA ENTERO COMA ENTERO PARENDER','funcionesbinarias',8,'p_funciones_binarias','gramatica.py',911), ('funcionesbinarias -> TRIM PARENIZQ argument PARENDER','funcionesbinarias',4,'p_funciones_binarias','gramatica.py',912), ('funcionesbinarias -> MD5 PARENIZQ argument PARENDER','funcionesbinarias',4,'p_funciones_binarias','gramatica.py',913), ('funcionesbinarias -> SHA PARENIZQ argument PARENDER','funcionesbinarias',4,'p_funciones_binarias','gramatica.py',914), ('funcionesbinarias -> SUBSTR PARENIZQ argument COMA ENTERO COMA ENTERO PARENDER','funcionesbinarias',8,'p_funciones_binarias','gramatica.py',915), ('funcionesbinarias -> GETBYTE PARENIZQ argument DOSPUNTOS DOSPUNTOS BYTEA COMA argument PARENDER','funcionesbinarias',9,'p_funciones_binarias','gramatica.py',916), ('funcionesbinarias -> SETBYTE PARENIZQ argument DOSPUNTOS DOSPUNTOS BYTEA COMA argument COMA argument PARENDER','funcionesbinarias',11,'p_funciones_binarias','gramatica.py',917), ('funcionesbinarias -> CONVERT PARENIZQ argument AS tipo','funcionesbinarias',5,'p_funciones_binarias','gramatica.py',918), ('funcionesbinarias -> ENCODE PARENIZQ argument DOSPUNTOS DOSPUNTOS BYTEA COMA CADENA PARENDER','funcionesbinarias',9,'p_funciones_binarias','gramatica.py',919), ('funcionesbinarias -> DECODE PARENIZQ argument COMA CADENA PARENDER','funcionesbinarias',6,'p_funciones_binarias','gramatica.py',920), ('funcionesmatematicas -> PI PARENIZQ PARENDER','funcionesmatematicas',3,'p_funciones_matematicas_S','gramatica.py',970), ('funcionesmatematicas -> RANDOM PARENIZQ PARENDER','funcionesmatematicas',3,'p_funciones_matematicas_S','gramatica.py',971), ('funcionesmatematicas -> ABS PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',982), ('funcionesmatematicas -> CBRT PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',983), ('funcionesmatematicas -> CEIL PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',984), ('funcionesmatematicas -> CEILING PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',985), ('funcionesmatematicas -> DEGREES PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',986), ('funcionesmatematicas -> EXP PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',987), ('funcionesmatematicas -> FLOOR PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',988), ('funcionesmatematicas -> LN PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',989), ('funcionesmatematicas -> LOG PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',990), ('funcionesmatematicas -> RADIANS PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',991), ('funcionesmatematicas -> SCALE PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',992), ('funcionesmatematicas -> SIGN PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',993), ('funcionesmatematicas -> SQRT PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',994), ('funcionesmatematicas -> TRUNC PARENIZQ argument PARENDER','funcionesmatematicas',4,'p_funciones_matematicas_1','gramatica.py',995), ('funcionesmatematicas -> DIV PARENIZQ argument COMA argument PARENDER','funcionesmatematicas',6,'p_funciones_matematicas_2','gramatica.py',1031), ('funcionesmatematicas -> GCD PARENIZQ argument COMA argument PARENDER','funcionesmatematicas',6,'p_funciones_matematicas_2','gramatica.py',1032), ('funcionesmatematicas -> MOD PARENIZQ argument COMA argument PARENDER','funcionesmatematicas',6,'p_funciones_matematicas_2','gramatica.py',1033), ('funcionesmatematicas -> POWER PARENIZQ argument COMA argument PARENDER','funcionesmatematicas',6,'p_funciones_matematicas_2','gramatica.py',1034), ('funcionesmatematicas -> ROUND PARENIZQ argument tipoderound PARENDER','funcionesmatematicas',5,'p_funciones_matematicas_2R','gramatica.py',1051), ('tipoderound -> COMA argument','tipoderound',2,'p_tipo_de_round','gramatica.py',1060), ('tipoderound -> <empty>','tipoderound',0,'p_tipo_de_round_null','gramatica.py',1067), ('funcionesmatematicas -> BUCKET PARENIZQ argument COMA argument COMA argument COMA argument PARENDER','funcionesmatematicas',10,'p_funciones_matematicas_4','gramatica.py',1074), ('funcionestrigonometricas -> ACOS PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1085), ('funcionestrigonometricas -> ASIN PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1086), ('funcionestrigonometricas -> ACOSD PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1087), ('funcionestrigonometricas -> ASIND PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1088), ('funcionestrigonometricas -> ATAN PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1089), ('funcionestrigonometricas -> ATAND PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1090), ('funcionestrigonometricas -> ATANDOS PARENIZQ argument COMA argument PARENDER','funcionestrigonometricas',6,'p_funciones_trigonometricas','gramatica.py',1091), ('funcionestrigonometricas -> ATANDOSD PARENIZQ argument COMA argument PARENDER','funcionestrigonometricas',6,'p_funciones_trigonometricas','gramatica.py',1092), ('funcionestrigonometricas -> COS PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1093), ('funcionestrigonometricas -> COSD PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1094), ('funcionestrigonometricas -> COT PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1095), ('funcionestrigonometricas -> COTD PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1096), ('funcionestrigonometricas -> SIN PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1097), ('funcionestrigonometricas -> SIND PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1098), ('funcionestrigonometricas -> TAN PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1099), ('funcionestrigonometricas -> TAND PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1100), ('funcionestrigonometricas -> SINH PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1101), ('funcionestrigonometricas -> COSH PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1102), ('funcionestrigonometricas -> TANH PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1103), ('funcionestrigonometricas -> ASINH PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1104), ('funcionestrigonometricas -> ACOSH PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1105), ('funcionestrigonometricas -> ATANH PARENIZQ argument PARENDER','funcionestrigonometricas',4,'p_funciones_trigonometricas','gramatica.py',1106), ('funcionesdefechas -> EXTRACT PARENIZQ partedelafecha FROM TIMESTAMP argument PARENDER','funcionesdefechas',7,'p_funciones_de_fechas','gramatica.py',1162), ('funcionesdefechas -> DATEPART PARENIZQ argument COMA INTERVAL argument PARENDER','funcionesdefechas',7,'p_funciones_de_fechas','gramatica.py',1163), ('funcionesdefechas -> NOW PARENIZQ PARENDER','funcionesdefechas',3,'p_funciones_de_fechas','gramatica.py',1164), ('funcionesdefechas -> CURRENTDATE','funcionesdefechas',1,'p_funciones_de_fechas','gramatica.py',1165), ('funcionesdefechas -> CURRENTTIME','funcionesdefechas',1,'p_funciones_de_fechas','gramatica.py',1166), ('funcionesdefechas -> TIMESTAMP argument','funcionesdefechas',2,'p_funciones_de_fechas','gramatica.py',1167), ('partedelafecha -> YEAR','partedelafecha',1,'p_parte_de_la_decha','gramatica.py',1195), ('partedelafecha -> MONTH','partedelafecha',1,'p_parte_de_la_decha','gramatica.py',1196), ('partedelafecha -> DAY','partedelafecha',1,'p_parte_de_la_decha','gramatica.py',1197), ('partedelafecha -> HOUR','partedelafecha',1,'p_parte_de_la_decha','gramatica.py',1198), ('partedelafecha -> MINUTE','partedelafecha',1,'p_parte_de_la_decha','gramatica.py',1199), ('partedelafecha -> SECOND','partedelafecha',1,'p_parte_de_la_decha','gramatica.py',1200), ('listadeseleccionados -> ID','listadeseleccionados',1,'p_lista_de_seleccionados_id','gramatica.py',1220), ('listadeseleccionados -> ID PUNTO ID','listadeseleccionados',3,'p_lista_de_seleccionados_id_punto_id','gramatica.py',1227), ('listadeseleccionados -> ID PUNTO ASTERISCO','listadeseleccionados',3,'p_lista_de_seleccionados_id_punto_asterisco','gramatica.py',1235), ('asopcional -> AS ID','asopcional',2,'p_asopcional','gramatica.py',1243), ('asopcional -> ID','asopcional',1,'p_asopcional_argument','gramatica.py',1250), ('asopcional -> AS CADENA','asopcional',2,'p_asopcionalS','gramatica.py',1257), ('asopcional -> CADENA','asopcional',1,'p_asopcional_argumentS','gramatica.py',1264), ('asopcional -> <empty>','asopcional',0,'p_asopcional_null','gramatica.py',1271), ('argument -> funcionesmatematicassimples','argument',1,'p_argument_noterminal','gramatica.py',1278), ('argument -> funcionestrigonometricas','argument',1,'p_argument_noterminal','gramatica.py',1279), ('argument -> funcionesmatematicas','argument',1,'p_argument_noterminal','gramatica.py',1280), ('argument -> funcionesdefechas','argument',1,'p_argument_noterminal','gramatica.py',1281), ('argument -> funcionesbinarias','argument',1,'p_argument_noterminal','gramatica.py',1282), ('create -> TYPE createenum','create',2,'p_create_instruccion','gramatica.py',1296), ('create -> TABLE createtable','create',2,'p_create_instruccion','gramatica.py',1297), ('create -> OR REPLACE DATABASE createdatabase','create',4,'p_create_instruccion','gramatica.py',1298), ('create -> DATABASE createdatabase','create',2,'p_create_instruccion','gramatica.py',1299), ('create -> problem','create',1,'p_create_instruccion_err','gramatica.py',1324), ('createenum -> ID AS ENUM PARENIZQ listacadenas PARENDER PTCOMA','createenum',7,'p_createenum','gramatica.py',1329), ('listacadenas -> listacadenas COMA CADENA','listacadenas',3,'p_listacadenas_recursiva','gramatica.py',1337), ('listacadenas -> CADENA','listacadenas',1,'p_listacadenas','gramatica.py',1346), ('createdatabase -> IF NOT EXISTS ID databaseowner','createdatabase',5,'p_createdatabase','gramatica.py',1353), ('createdatabase -> ID databaseowner','createdatabase',2,'p_createdatabase','gramatica.py',1354), ('databaseowner -> OWNER IGUAL tipoowner databasemode','databaseowner',4,'p_databaseowner','gramatica.py',1369), ('databaseowner -> OWNER tipoowner databasemode','databaseowner',3,'p_databaseowner','gramatica.py',1370), ('tipoowner -> ID','tipoowner',1,'p_tipoowner_id','gramatica.py',1384), ('tipoowner -> CADENA','tipoowner',1,'p_tipoowner_cadena','gramatica.py',1391), ('databaseowner -> databasemode','databaseowner',1,'p_databaseownerP','gramatica.py',1398), ('databasemode -> MODE IGUAL ENTERO PTCOMA','databasemode',4,'p_databasemode','gramatica.py',1405), ('databasemode -> MODE ENTERO PTCOMA','databasemode',3,'p_databasemode','gramatica.py',1406), ('databasemode -> PTCOMA','databasemode',1,'p_databasemode','gramatica.py',1407), ('createtable -> ID PARENIZQ tabledescriptions PARENDER tableherencia','createtable',5,'p_createtable','gramatica.py',1424), ('tableherencia -> INHERITS PARENIZQ ID PARENDER PTCOMA','tableherencia',5,'p_tableherencia','gramatica.py',1433), ('tableherencia -> PTCOMA','tableherencia',1,'p_tableherencia','gramatica.py',1434), ('tabledescriptions -> tabledescriptions COMA tabledescription','tabledescriptions',3,'p_tabledescriptions_recursivo','gramatica.py',1445), ('tabledescriptions -> tabledescription','tabledescriptions',1,'p_tabledescriptions','gramatica.py',1454), ('tabledescription -> ID tipo tablekey','tabledescription',3,'p_tabledescription','gramatica.py',1461), ('tabledescription -> PRIMARY KEY PARENIZQ listaids PARENDER','tabledescription',5,'p_tabledescription','gramatica.py',1462), ('tabledescription -> FOREIGN KEY PARENIZQ listaids PARENDER REFERENCES ID PARENIZQ listaids PARENDER','tabledescription',10,'p_tabledescription','gramatica.py',1463), ('tabledescription -> CONSTRAINT ID CHECK finalconstraintcheck','tabledescription',4,'p_tabledescription','gramatica.py',1464), ('tabledescription -> CHECK finalconstraintcheck','tabledescription',2,'p_tabledescription','gramatica.py',1465), ('tabledescription -> UNIQUE finalunique','tabledescription',2,'p_tabledescription','gramatica.py',1466), ('tablekey -> PRIMARY KEY tabledefault','tablekey',3,'p_tablekey','gramatica.py',1504), ('tablekey -> REFERENCES ID PARENIZQ ID PARENDER tabledefault','tablekey',6,'p_tablekey','gramatica.py',1505), ('tablekey -> REFERENCES ID tabledefault','tablekey',3,'p_tablekeyP','gramatica.py',1520), ('tablekey -> tabledefault','tablekey',1,'p_tablekeyP2','gramatica.py',1528), ('columnreferences -> columnreferences COMA ID','columnreferences',3,'p_columnreferences_r','gramatica.py',1535), ('columnreferences -> ID','columnreferences',1,'p_columnreferences_r2','gramatica.py',1544), ('tabledefault -> DEFAULT value tablenull','tabledefault',3,'p_tabledefault','gramatica.py',1551), ('tabledefault -> tablenull','tabledefault',1,'p_tabledefaultP','gramatica.py',1560), ('tablenull -> NOT NULL tableconstraintunique','tablenull',3,'p_tablenull','gramatica.py',1567), ('tablenull -> NULL tableconstraintunique','tablenull',2,'p_tablenull','gramatica.py',1568), ('tablenull -> tableconstraintunique','tablenull',1,'p_tablenullP','gramatica.py',1582), ('tableconstraintunique -> CONSTRAINT ID UNIQUE tableconstraintcheck','tableconstraintunique',4,'p_tableconstraintunique','gramatica.py',1589), ('tableconstraintunique -> UNIQUE tableconstraintcheck','tableconstraintunique',2,'p_tableconstraintunique','gramatica.py',1590), ('tableconstraintunique -> tableconstraintcheck','tableconstraintunique',1,'p_tableconstraintuniqueP','gramatica.py',1606), ('tableconstraintcheck -> CONSTRAINT ID CHECK PARENIZQ condiciones PARENDER','tableconstraintcheck',6,'p_tableconstraintcheck','gramatica.py',1613), ('tableconstraintcheck -> CHECK PARENIZQ condiciones PARENDER','tableconstraintcheck',4,'p_tableconstraintcheck','gramatica.py',1614), ('tableconstraintcheck -> <empty>','tableconstraintcheck',0,'p_tableconstraintcheckE','gramatica.py',1629), ('finalconstraintcheck -> PARENIZQ condiciones PARENDER','finalconstraintcheck',3,'p_finalconstraintcheck','gramatica.py',1635), ('finalunique -> PARENIZQ listaids PARENDER','finalunique',3,'p_finalunique','gramatica.py',1642), ('listaids -> listaids COMA ID','listaids',3,'p_listaids_r','gramatica.py',1649), ('listaids -> ID','listaids',1,'p_listaids','gramatica.py',1658), ('listaidcts -> listaidcts COMA ID PUNTO ID','listaidcts',5,'p_listaidcts_r','gramatica.py',1665), ('listaidcts -> listaidcts COMA ID','listaidcts',3,'p_listaidcts_re','gramatica.py',1675), ('listaidcts -> ID PUNTO ID','listaidcts',3,'p_listaidcts','gramatica.py',1684), ('listaidcts -> ID','listaidcts',1,'p_listaidctse','gramatica.py',1692), ('tipo -> SMALLINT','tipo',1,'p_tipo','gramatica.py',1699), ('tipo -> INTEGER','tipo',1,'p_tipo','gramatica.py',1700), ('tipo -> BIGINT','tipo',1,'p_tipo','gramatica.py',1701), ('tipo -> DECIMAL','tipo',1,'p_tipo','gramatica.py',1702), ('tipo -> NUMERIC','tipo',1,'p_tipo','gramatica.py',1703), ('tipo -> REAL','tipo',1,'p_tipo','gramatica.py',1704), ('tipo -> DOUBLE PRECISION','tipo',2,'p_tipo','gramatica.py',1705), ('tipo -> MONEY','tipo',1,'p_tipo','gramatica.py',1706), ('tipo -> CHARACTER tipochar','tipo',2,'p_tipo','gramatica.py',1707), ('tipo -> VARCHAR PARENIZQ ENTERO PARENDER','tipo',4,'p_tipo','gramatica.py',1708), ('tipo -> CHAR PARENIZQ ENTERO PARENDER','tipo',4,'p_tipo','gramatica.py',1709), ('tipo -> TEXT','tipo',1,'p_tipo','gramatica.py',1710), ('tipo -> TIMESTAMP precision','tipo',2,'p_tipo','gramatica.py',1711), ('tipo -> TIME precision','tipo',2,'p_tipo','gramatica.py',1712), ('tipo -> DATE','tipo',1,'p_tipo','gramatica.py',1713), ('tipo -> INTERVAL fields precision','tipo',3,'p_tipo','gramatica.py',1714), ('tipo -> BOLEANO','tipo',1,'p_tipo','gramatica.py',1715), ('tipo -> ID','tipo',1,'p_tipo','gramatica.py',1716), ('tipochar -> VARYING PARENIZQ ENTERO PARENDER','tipochar',4,'p_tipochar','gramatica.py',1804), ('tipochar -> PARENIZQ ENTERO PARENDER','tipochar',3,'p_tipochar','gramatica.py',1805), ('precision -> PARENIZQ ENTERO PARENDER','precision',3,'p_precision','gramatica.py',1818), ('precision -> <empty>','precision',0,'p_precisionE','gramatica.py',1825), ('fields -> MONTH','fields',1,'p_fields','gramatica.py',1830), ('fields -> HOUR','fields',1,'p_fields','gramatica.py',1831), ('fields -> MINUTE','fields',1,'p_fields','gramatica.py',1832), ('fields -> SECOND','fields',1,'p_fields','gramatica.py',1833), ('fields -> YEAR','fields',1,'p_fields','gramatica.py',1834), ('fields -> <empty>','fields',0,'p_fieldsE','gramatica.py',1854), ('use -> DATABASE ID PTCOMA','use',3,'p_use','gramatica.py',1860), ('use -> ID PTCOMA','use',2,'p_use','gramatica.py',1861), ('use -> problem','use',1,'p_useE','gramatica.py',1875), ('show -> DATABASES likeopcional','show',2,'p_show','gramatica.py',1882), ('show -> problem','show',1,'p_showw','gramatica.py',1891), ('likeopcional -> LIKE CADENA PTCOMA','likeopcional',3,'p_likeopcional','gramatica.py',1896), ('likeopcional -> PTCOMA','likeopcional',1,'p_likeopcional','gramatica.py',1897), ('drop -> DATABASE dropdb PTCOMA','drop',3,'p_drop','gramatica.py',1909), ('drop -> TABLE ID PTCOMA','drop',3,'p_drop','gramatica.py',1910), ('drop -> problem','drop',1,'p_drop_e','gramatica.py',1923), ('dropdb -> IF EXISTS ID','dropdb',3,'p_dropdb','gramatica.py',1928), ('dropdb -> ID','dropdb',1,'p_dropdb','gramatica.py',1929), ('alter -> DATABASE ID alterdbs PTCOMA','alter',4,'p_alterp','gramatica.py',1943), ('alter -> TABLE ID altertables PTCOMA','alter',4,'p_alterp','gramatica.py',1944), ('alter -> problem','alter',1,'p_alterp_err','gramatica.py',1960), ('alterdbs -> alterdbs COMA alterdb','alterdbs',3,'p_alterdbsr','gramatica.py',1965), ('alterdbs -> alterdb','alterdbs',1,'p_alterdbs','gramatica.py',1974), ('alterdb -> RENAME TO ID','alterdb',3,'p_alterdb','gramatica.py',1982), ('alterdb -> OWNER TO tipodeowner','alterdb',3,'p_alterdb','gramatica.py',1983), ('tipodeowner -> ID','tipodeowner',1,'p_tipodeowner','gramatica.py',1996), ('tipodeowner -> CURRENT_USER','tipodeowner',1,'p_tipodeowner','gramatica.py',1997), ('tipodeowner -> SESSION_USER','tipodeowner',1,'p_tipodeowner','gramatica.py',1998), ('altertables -> altertables COMA altertable','altertables',3,'p_altertablesr','gramatica.py',2008), ('altertables -> altertable','altertables',1,'p_altertables','gramatica.py',2017), ('altertable -> ADD alteraddc','altertable',2,'p_altertable','gramatica.py',2024), ('altertable -> ALTER COLUMN ID SET opcionesalterset','altertable',5,'p_altertable','gramatica.py',2025), ('altertable -> DROP tipodedrop','altertable',2,'p_altertable','gramatica.py',2026), ('altertable -> RENAME COLUMN ID TO ID','altertable',5,'p_altertable','gramatica.py',2027), ('altertable -> RENAME ID TO ID','altertable',4,'p_altertableRT','gramatica.py',2050), ('altertable -> ALTER COLUMN ID TYPE tipo','altertable',5,'p_altertableP','gramatica.py',2059), ('alteraddc -> CONSTRAINT ID UNIQUE PARENIZQ listaidcts PARENDER','alteraddc',6,'p_addConstraintU','gramatica.py',2069), ('alteraddc -> COLUMN ID tipo','alteraddc',3,'p_addConstraintU','gramatica.py',2070), ('alteraddc -> CONSTRAINT ID alteradd','alteraddc',3,'p_addConstraint','gramatica.py',2086), ('alteraddc -> alteradd','alteraddc',1,'p_addConstraintS','gramatica.py',2095), ('alteradd -> CHECK PARENIZQ condiciones PARENDER','alteradd',4,'p_alteradd','gramatica.py',2100), ('alteradd -> FOREIGN KEY PARENIZQ listaids PARENDER REFERENCES ID PARENIZQ listaids PARENDER','alteradd',10,'p_alteradd','gramatica.py',2101), ('alteradd -> PRIMARY KEY PARENIZQ listaids PARENDER','alteradd',5,'p_alteradd','gramatica.py',2102), ('opcionesalterset -> NOT NULL','opcionesalterset',2,'p_opcionesalterset','gramatica.py',2121), ('opcionesalterset -> NULL','opcionesalterset',1,'p_opcionesalterset','gramatica.py',2122), ('tipodedrop -> COLUMN ID','tipodedrop',2,'p_tipodedrop','gramatica.py',2133), ('tipodedrop -> CONSTRAINT ID','tipodedrop',2,'p_tipodedrop','gramatica.py',2134), ('tipodedrop -> PRIMARY KEY PARENIZQ listaids PARENDER','tipodedrop',5,'p_tipodedrop','gramatica.py',2135), ('tipodedrop -> FOREIGN KEY PARENIZQ listaids PARENDER','tipodedrop',5,'p_tipodedrop','gramatica.py',2136), ('delete -> FROM ID condicionesops PTCOMA','delete',4,'p_instrucciones_delete','gramatica.py',2158), ('delete -> problem','delete',1,'p_instruccionesdelete_e','gramatica.py',2168), ('insert -> INTO ID VALUES PARENIZQ values PARENDER PTCOMA','insert',7,'p_instrucciones_insert','gramatica.py',2173), ('insert -> problem','insert',1,'p_instrucciones_insert_err','gramatica.py',2183), ('values -> values COMA value','values',3,'p_values_rec','gramatica.py',2188), ('values -> value','values',1,'p_values','gramatica.py',2197), ('value -> ENTERO','value',1,'p_value','gramatica.py',2204), ('value -> DECIMAL','value',1,'p_valuef','gramatica.py',2211), ('value -> CADENA','value',1,'p_valuec','gramatica.py',2218), ('value -> boleano','value',1,'p_valueb','gramatica.py',2225), ('value -> MD5 PARENIZQ argument PARENDER','value',4,'p_value_md','gramatica.py',2232), ('value -> NOW PARENIZQ PARENDER','value',3,'p_value_now','gramatica.py',2240), ('value -> TRIM PARENIZQ argument PARENDER','value',4,'p_value_trim','gramatica.py',2247), ('value -> SUBSTRING PARENIZQ argument COMA ENTERO COMA ENTERO PARENDER','value',8,'p_value_substring','gramatica.py',2255), ('value -> SUBSTR PARENIZQ argument COMA ENTERO COMA ENTERO PARENDER','value',8,'p_value_substr','gramatica.py',2265), ('update -> ID SET asignaciones condicionesops PTCOMA','update',5,'p_instrucciones_update','gramatica.py',2276), ('update -> problem','update',1,'p_instruccions_update_e','gramatica.py',2286), ('asignaciones -> asignaciones COMA ID IGUAL argument','asignaciones',5,'p_asignaciones_rec','gramatica.py',2291), ('asignaciones -> ID IGUAL argument','asignaciones',3,'p_asignaciones','gramatica.py',2301), ('condicionesops -> WHERE condiciones','condicionesops',2,'p_instrucciones_update_condsops','gramatica.py',2309), ('condicionesops -> <empty>','condicionesops',0,'p_instrucciones_update_condsopsE','gramatica.py',2316), ('condiciones -> condiciones comparacionlogica condicion','condiciones',3,'p_condiciones_recursivo','gramatica.py',2323), ('condiciones -> condicion','condiciones',1,'p_codiciones','gramatica.py',2332), ('comparacionlogica -> AND','comparacionlogica',1,'p_comparacionlogica','gramatica.py',2339), ('comparacionlogica -> OR','comparacionlogica',1,'p_comparacionlogica','gramatica.py',2340), ('condicion -> NOT condicion','condicion',2,'p_condicion','gramatica.py',2346), ('condicion -> condicions','condicion',1,'p_condicion','gramatica.py',2347), ('condicions -> argument MENORQUE argument','condicions',3,'p_condicions','gramatica.py',2360), ('condicions -> argument MAYORQUE argument','condicions',3,'p_condicions','gramatica.py',2361), ('condicions -> argument IGUAL argument','condicions',3,'p_condicions','gramatica.py',2362), ('condicions -> argument MENORIGUALQUE argument','condicions',3,'p_condicions','gramatica.py',2363), ('condicions -> argument MAYORIGUALQUE argument','condicions',3,'p_condicions','gramatica.py',2364), ('condicions -> argument DIFERENTELL argument','condicions',3,'p_condicions','gramatica.py',2365), ('condicions -> argument BETWEEN betweenopcion','condicions',3,'p_condicions','gramatica.py',2366), ('condicions -> argument ISNULL','condicions',2,'p_condicions','gramatica.py',2367), ('condicions -> argument NOTNULL','condicions',2,'p_condicions','gramatica.py',2368), ('condicions -> argument IS isopcion','condicions',3,'p_condicions','gramatica.py',2369), ('condicions -> argument IN PARENIZQ select PARENDER','condicions',5,'p_condicions','gramatica.py',2370), ('condicions -> argument NOT BETWEEN betweenopcion','condicions',4,'p_condicions','gramatica.py',2371), ('condicions -> argument NOT IN PARENIZQ select PARENDER','condicions',6,'p_condicions','gramatica.py',2372), ('condicions -> argument ANY PARENIZQ select PARENDER','condicions',5,'p_condicions','gramatica.py',2373), ('condicions -> argument ALL PARENIZQ select PARENDER','condicions',5,'p_condicions','gramatica.py',2374), ('condicions -> argument SOME PARENIZQ select PARENDER','condicions',5,'p_condicions','gramatica.py',2375), ('condicions -> EXISTS PARENIZQ select PARENDER','condicions',4,'p_condicionsP','gramatica.py',2452), ('betweenopcion -> symm argument AND argument','betweenopcion',4,'p_betweenopcion','gramatica.py',2457), ('betweenopcion -> argument AND argument','betweenopcion',3,'p_betweenopcion','gramatica.py',2458), ('symm -> SYMMETRIC','symm',1,'p_symmetric','gramatica.py',2473), ('isopcion -> DISTINCT FROM argument','isopcion',3,'p_isopcion','gramatica.py',2478), ('isopcion -> NULL','isopcion',1,'p_isopcion','gramatica.py',2479), ('isopcion -> TRUE','isopcion',1,'p_isopcion','gramatica.py',2480), ('isopcion -> FALSE','isopcion',1,'p_isopcion','gramatica.py',2481), ('isopcion -> UNKNOWN','isopcion',1,'p_isopcion','gramatica.py',2482), ('isopcion -> NOT isnotoptions','isopcion',2,'p_isopcion','gramatica.py',2483), ('isnotoptions -> FALSE','isnotoptions',1,'p_isnotoptions','gramatica.py',2508), ('isnotoptions -> UNKNOWN','isnotoptions',1,'p_isnotoptions','gramatica.py',2509), ('isnotoptions -> TRUE','isnotoptions',1,'p_isnotoptions','gramatica.py',2510), ('isnotoptions -> NULL','isnotoptions',1,'p_isnotoptions','gramatica.py',2511), ('isnotoptions -> DISTINCT FROM argument','isnotoptions',3,'p_isnotoptions','gramatica.py',2512), ('argument -> argument MAS argument','argument',3,'p_argument_binary','gramatica.py',2533), ('argument -> argument GUION argument','argument',3,'p_argument_binary','gramatica.py',2534), ('argument -> argument BARRA argument','argument',3,'p_argument_binary','gramatica.py',2535), ('argument -> argument ASTERISCO argument','argument',3,'p_argument_binary','gramatica.py',2536), ('argument -> argument PORCENTAJE argument','argument',3,'p_argument_binary','gramatica.py',2537), ('argument -> argument POTENCIA argument','argument',3,'p_argument_binary','gramatica.py',2538), ('argument -> boleano','argument',1,'p_argument_bolano','gramatica.py',2573), ('argument -> MAS argument','argument',2,'p_argument_unary','gramatica.py',2578), ('argument -> GUION argument','argument',2,'p_argument_unary','gramatica.py',2579), ('argument -> PARENIZQ argument PARENDER','argument',3,'p_argument_agrupacion','gramatica.py',2591), ('argument -> ENTERO','argument',1,'p_argument_entero','gramatica.py',2596), ('argument -> DECIMAL','argument',1,'p_argument_decimal','gramatica.py',2603), ('argument -> CADENA','argument',1,'p_argument_cadena','gramatica.py',2610), ('argument -> ID','argument',1,'p_argument_id','gramatica.py',2617), ('argument -> ID PUNTO ID','argument',3,'p_argument_idpid','gramatica.py',2624), ('listadeseleccionados -> ID INTO ID','listadeseleccionados',3,'p_lista_de_seleccionados_id_into_id','gramatica.py',2633), ('listadeseleccionados -> ID INTO STRICT ID','listadeseleccionados',4,'p_lista_de_seleccionados_id_into_strict_id','gramatica.py',2642), ('listadeseleccionados -> ASTERISCO INTO ID','listadeseleccionados',3,'p_lista_de_seleccionados_asterisco_into_id','gramatica.py',2650), ('listadeseleccionados -> ASTERISCO INTO STRICT ID','listadeseleccionados',4,'p_lista_de_seleccionados_asterisco_into_strict_id','gramatica.py',2659), ('boleano -> TRUE','boleano',1,'p_boleano','gramatica.py',2691), ('boleano -> FALSE','boleano',1,'p_boleano','gramatica.py',2692), ('pl_asignacion -> ID DOSPUNTOS IGUAL argument PTCOMA','pl_asignacion',5,'p_pl_asignacion1','gramatica.py',2707), ('pl_asignacion -> ID PUNTO ID DOSPUNTOS IGUAL argument PTCOMA','pl_asignacion',7,'p_pl_asignacion_id_punto_id1','gramatica.py',2715), ('pl_asignacion -> ID IGUAL argument PTCOMA','pl_asignacion',4,'p_pl_asignacion2','gramatica.py',2724), ('pl_asignacion -> ID PUNTO ID IGUAL argument PTCOMA','pl_asignacion',6,'p_pl_asignacion_id_punto_id2','gramatica.py',2732), ('pl_perform -> PERFORM ID PARENIZQ listadeargumentos PARENDER PTCOMA','pl_perform',6,'p_pl_perform','gramatica.py',2745), ('pl_perform -> PERFORM ID PARENIZQ PARENDER PTCOMA','pl_perform',5,'p_pl_perform2','gramatica.py',2754), ('perform -> problem','perform',1,'p_pl_perform_err','gramatica.py',2764), ('pl_if_not_found -> IF NOT FOUND THEN raiseexception END IF PTCOMA','pl_if_not_found',8,'p_pl_if_not_found','gramatica.py',2773), ('raiseexception -> RAISE EXCEPTION argument COMA argument PTCOMA','raiseexception',6,'p_pl_raiseexception','gramatica.py',2782), ('raiseexception -> RAISE EXCEPTION argument PTCOMA','raiseexception',4,'p_pl_raiseexception_simple','gramatica.py',2791), ('pl_w_excepcion -> EXCEPTION instrucciones1','pl_w_excepcion',2,'p_exepciones4','gramatica.py',2802), ('instrucciones1 -> instrucciones1 instruccion2','instrucciones1',2,'p_instrucciones_lista1','gramatica.py',2808), ('instrucciones1 -> instruccion2','instrucciones1',1,'p_instruciones2','gramatica.py',2817), ('instruccion2 -> WHEN NO_DATA_FOUND THEN raiseexception','instruccion2',4,'p_instruccionAlter3','gramatica.py',2825), ('instruccion2 -> WHEN TOO_MANY_ROWS THEN raiseexception','instruccion2',4,'p_instruccionAlter5','gramatica.py',2834), ('p_print_strict -> NUMERAL PRINT_STRICT_PARAMS ON','p_print_strict',3,'p_printstrict','gramatica.py',2846), ('pl_return -> RETURN argument PTCOMA','pl_return',3,'p_pl_return','gramatica.py',2856), ('pl_execute -> EXECUTE argument INTO STRICT ID USING listaidcts PTCOMA','pl_execute',8,'p_pl_execute_into_strict_using','gramatica.py',2870), ('pl_execute -> EXECUTE argument INTO ID USING listaidcts PTCOMA','pl_execute',7,'p_pl_execute_into_using','gramatica.py',2885), ('pl_execute -> EXECUTE argument USING listaidcts PTCOMA','pl_execute',5,'p_pl_execute_using','gramatica.py',2898), ('pl_execute -> EXECUTE argument PTCOMA','pl_execute',3,'p_pl_execute_cad','gramatica.py',2910), ('pl_execute -> EXECUTE argument INTO STRICT ID PTCOMA','pl_execute',6,'p_pl_execute_into_strict','gramatica.py',2919), ('pl_execute -> EXECUTE argument INTO ID PTCOMA','pl_execute',5,'p_pl_execute_into','gramatica.py',2932), ]
'use strict'; import { driver, BASE_URL, } from './helper'; describe('test/datahub-render.test.js', () => { describe('home page render testing', () => { before(() => { return driver .initWindow({ width: 1000, height: 800, deviceScaleFactor: 2, userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36 Language/zh-CN', }); }); afterEach(function () { return driver .coverage() .saveScreenshots(this); }); after(() => { return driver .openReporter(false) .quit(); }); it('home page render should be ok', () => { return driver .getUrl(BASE_URL) .sleep(1000) .elementByCss('[data-accessbilityid="go-btn-dashboard"]') .hasText('立即开始'); }); it('home page render should be ok', () => { return driver .getUrl(BASE_URL) .sleep(1000) .elementByCss('[data-accessbilityid="go-btn-dashboard"]') .click() .elementByCss('h1.title') .hasText('DataHub'); }); }); });
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from .. import models class ServicesOperations(object): """ServicesOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. :ivar api_version: The API version to use for this operation. Constant value: "2018-09-01-preview". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2018-09-01-preview" self.config = config def create_or_update( self, resource_group_name, service_topology_name, service_name, service_info, custom_headers=None, raw=False, **operation_config): """Creates or updates a service in the service topology. Synchronously creates a new service or updates an existing service. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param service_topology_name: The name of the service topology . :type service_topology_name: str :param service_name: The name of the service resource. :type service_name: str :param service_info: The service object :type service_info: ~azure.mgmt.deploymentmanager.models.ServiceResource :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: ServiceResource or ClientRawResponse if raw=true :rtype: ~azure.mgmt.deploymentmanager.models.ServiceResource or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = self.create_or_update.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'serviceTopologyName': self._serialize.url("service_topology_name", service_topology_name, 'str'), 'serviceName': self._serialize.url("service_name", service_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(service_info, 'ServiceResource') # Construct and send request request = self._client.put(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 201: deserialized = self._deserialize('ServiceResource', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeploymentManager/serviceTopologies/{serviceTopologyName}/services/{serviceName}'} def get( self, resource_group_name, service_topology_name, service_name, custom_headers=None, raw=False, **operation_config): """Gets the service. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param service_topology_name: The name of the service topology . :type service_topology_name: str :param service_name: The name of the service resource. :type service_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: ServiceResource or ClientRawResponse if raw=true :rtype: ~azure.mgmt.deploymentmanager.models.ServiceResource or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = self.get.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'serviceTopologyName': self._serialize.url("service_topology_name", service_topology_name, 'str'), 'serviceName': self._serialize.url("service_name", service_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('ServiceResource', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeploymentManager/serviceTopologies/{serviceTopologyName}/services/{serviceName}'} def delete( self, resource_group_name, service_topology_name, service_name, custom_headers=None, raw=False, **operation_config): """Deletes the service. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param service_topology_name: The name of the service topology . :type service_topology_name: str :param service_name: The name of the service resource. :type service_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: None or ClientRawResponse if raw=true :rtype: None or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = self.delete.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'serviceTopologyName': self._serialize.url("service_topology_name", service_topology_name, 'str'), 'serviceName': self._serialize.url("service_name", service_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.delete(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeploymentManager/serviceTopologies/{serviceTopologyName}/services/{serviceName}'}
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See http://js.arcgis.com/3.17/esri/copyright.txt for details. //>>built define("esri/nls/jsapi_it-it",{"esri/nls/jsapi":{io:{proxyNotSet:"esri.config.defaults.io.proxyUrl non impostato. Se si effettua una richiesta a un server abilitato per CORS, impostare il dominio su esri.config.defaults.io.corsEnabledServers."},map:{deprecateReorderLayerString:"Map.reorderLayer(/*String*/ id, /*Number*/ index) deprecato. Utilizzare Map.reorderLayer(/*Layer*/ layer, /*Number*/ index).",deprecateShiftDblClickZoom:"Map.(enable/disable)ShiftDoubleClickZoom deprecato. Shift-Double-Click zoom behavior non sar\u00e0 supportato."}, basemaps:{streets:"Strade",satellite:"Immagini",hybrid:"Immagini con etichette",terrain:"Suolo con etichette",topo:"Topografico",gray:"Tela grigio chiaro","dark-gray":"Tela grigio scuro",oceans:"Oceani","national-geographic":"National Geographic",osm:"OpenStreetMap","streets-night-vector":"Mappa stradale mondiale (notte)","streets-relief-vector":"Mappa stradale mondiale (con rilievo)","streets-navigation-vector":"Mappa mondiale navigazione"},geometry:{deprecateToScreenPoint:"esri.geometry.toScreenPoint deprecato. Utilizzare esri.geometry.toScreenGeometry.", deprecateToMapPoint:"esri.geometry.toMapPoint deprecato. Utilizzare esri.geometry.toMapGeometry."},layers:{tiled:{tileError:"Impossibile caricare la tile"},dynamic:{imageError:"Impossibile caricare l'immagine"},graphics:{drawingError:"Impossibile disegnare l'elemento grafico "},agstiled:{deprecateRoundrobin:'Opzione costruttore "roundrobin" deprecata. Usare l\'opzione "tileServers".'},imageParameters:{deprecateBBox:'Propriet\u00e0 "bbox" deprecata. Usare la propriet\u00e0 "extent".'},FeatureLayer:{noOIDField:"objectIdField non impostato [url: ${url}]", fieldNotFound:'Impossibile trovare il campo "${field}" nelle informazioni "fields" del livello [url: ${url}]',noGeometryField:'Impossibile trovare un campo di tipo "esriFieldTypeGeometry" nelle informazioni "fields" del layer. Se si utilizza un layer di servizio mappe, le feature non avranno geometria [url: ${url}]',invalidParams:"La query contiene uno o pi\u00f9 parametri non supportati",updateError:"Si \u00e8 verificato un errore durante l'aggiornamento del layer",createUserSeconds:"Creato da ${userId} qualche secondo fa", createUserMinute:"Creato da ${userId} un minuto fa",editUserSeconds:"Modificato da ${userId} qualche secondo fa",editUserMinute:"Modificato da ${userId} un minuto fa",createSeconds:"Creato qualche secondo fa",createMinute:"Creato un minuto fa",editSeconds:"Modificato qualche secondo fa",editMinute:"Modificato un minuto fa",createUserMinutes:"Creato da ${userId} ${minutes} minuti fa",createUserHour:"Creato da ${userId} un'ora fa",createUserHours:"Creato da ${userId} ${hours} ore fa",createUserWeekDay:"Creato da ${userId} il giorno ${weekDay} alle ore ${formattedTime}", createUserFull:"Creato da ${userId} il giorno ${formattedDate} alle ore ${formattedTime}",editUserMinutes:"Modificato da ${userId} ${minutes} minuti fa",editUserHour:"Modificato da ${userId} un'ora fa",editUserHours:"Modificato da ${userId} ${hours} ore fa",editUserWeekDay:"Modificato da ${userId} il giorno ${weekDay} alle ore ${formattedTime}",editUserFull:"Modificato da ${userId} il giorno ${formattedDate} alle ore ${formattedTime}",createUser:"Creato da ${userId}",editUser:"Modificato da ${userId}", createMinutes:"Creato ${minutes} minuti fa",createHour:"Creato un'ora fa",createHours:"Creato ${hours} ore fa",createWeekDay:"Creato il giorno ${weekDay} alle ore ${formattedTime}",createFull:"Creato il giorno ${formattedDate} alle ore ${formattedTime}",editMinutes:"Modificato ${minutes} minuti fa",editHour:"Modificato un'ora fa",editHours:"Modificato ${hours} ore fa",editWeekDay:"Modificato il giorno ${weekDay} alle ore ${formattedTime}",editFull:"Modificato il giorno ${formattedDate} alle ore ${formattedTime}"}}, tasks:{gp:{gpDataTypeNotHandled:"Tipo di dati GP non gestito."},na:{route:{routeNameNotSpecified:'"RouteName" non specificato per almeno 1 fermata nel FeatureSet delle fermate.'}},query:{invalid:"Impossibile eseguire la query. Verificare i parametri."}},toolbars:{draw:{convertAntiClockwisePolygon:"I poligoni tracciati in senso antiorario verranno ridisegnati in senso orario.",addPoint:"Fare clic per aggiungere un punto",addShape:"Fare clic per aggiungere una forma o premere per iniziare e rilasciare per terminare", addMultipoint:"Fare clic per iniziare ad aggiungere punti",freehand:"Premere per iniziare e rilasciare per terminare",start:"Fare clic per iniziare a disegnare",resume:"Fare clic per continuare a disegnare",complete:"Fare doppio clic per completare",finish:"Fare doppio clic per terminare",invalidType:"Tipo di geometria non supportato"},edit:{invalidType:"Impossibile attivare lo strumento. Verificare che lo strumento sia valido per il tipo di geometria dato.",deleteLabel:"Elimina"}},virtualearth:{vetiledlayer:{bingMapsKeyNotSpecified:"BingMapsKey deve essere specificato."}, vegeocode:{bingMapsKeyNotSpecified:"BingMapsKey deve essere specificato.",requestQueued:"Token server non recuperato. La richiesta di accodamento verr\u00e0 eseguita dopo il recupero del token del server."}},widgets:{appProxySettings:{premiumContent:"Contenuti per abbonati",untitled:"Senza titolo (${url})"},attributeInspector:{NLS_first:"Primo",NLS_previous:"Precedente",NLS_next:"Seguente",NLS_last:"Ultimo",NLS_deleteFeature:"Elimina",NLS_title:"Modifica attributi",NLS_errorInvalid:"Non valido",NLS_validationInt:"Il valore deve essere un numero intero.", NLS_validationFlt:"Il valore deve essere mobile.",NLS_of:"di",NLS_noFeaturesSelected:"Nessuna feature selezionata"},basemapToggle:{toggle:"Attiva/disattiva mappa di base"},homeButton:{home:{button:"Home",title:"Estensione predefinita"}},layerSwipe:{title:"Trascinare per visualizzare il layer sottostante"},locateButton:{locate:{button:"Posizione",title:"Trova posizione personale",tracking:"Rileva posizione",stopTracking:"Non rilevare pi\u00f9 posizione"}},overviewMap:{NLS_drag:"Trascinare per modificare i limiti della mappa", NLS_show:"Mostra anteprima mappa",NLS_hide:"Nascondi anteprima mappa",NLS_maximize:"Ingrandisci",NLS_restore:"Ripristina",NLS_noMap:'"map" non trovato nei parametri di input',NLS_noLayer:"La mappa principale non dispone di un layer di base",NLS_invalidSR:"Riferimento spaziale del layer fornito non compatibile con la mappa principale",NLS_invalidType:'Tipo di layer non supportato. I tipi validi sono "TiledMapServiceLayer"e "DynamicMapServiceLayer"'},timeSlider:{NLS_first:"Primo",NLS_previous:"Precedente", NLS_next:"Seguente",NLS_play:"Riproduci/Pausa",NLS_invalidTimeExtent:"TimeExtent non specificato o in un formato non corretto."},mdSlider:{NLS_play:"Riproduci/Pausa",NLS_previous:"Precedente",NLS_next:"Avanti"},attachmentEditor:{NLS_attachments:"Allegati:",NLS_add:"Aggiungi",NLS_none:"Nessuno",NLS_error:"Errore.",NLS_fileNotSupported:"Questo tipo di file non \u00e8 supportato."},directions:{error:{notEnoughStops:"Immettere un'origine e una destinazione.",notReady:"Il caricamento del widget Indicazioni stradali non \u00e8 completato o si \u00e8 verificato un errore durante l'inizializzazione.", unknownStop:"Posizione '\x3cname\x3e' non trovata.",routeTask:"Impossibile creare l'itinerario per questi indirizzi.",locator:"Posizione non trovata.",invalidStopType:"Tipo di fermata non valido",locatorUndefined:"Impossibile eseguire la geocodifica inversa. URL del localizzatore non definito.",noAddresses:"Non sono stati restituiti indirizzi.",noStops:"Non sono state specificate fermate da aggiungere.",maximumStops:"\u00c8 stato raggiunto il numero massimo di fermate.",cantFindRouteServiceDescription:"Descrizione del servizio itinerari irraggiungibile o non riconosciuta. Verificare l'URL del servizio e/o le credenziali utente, se specificate.", maxWalkingDistance:"La distanza tra qualsiasi input deve essere inferiore a 50 miglia (80 chilometri) durante gli spostamenti a piedi.",nonNAmTruckingMode:"Il calcolo degli itinerari in camion al di fuori del Nord America e dell'America Centrale al momento non \u00e8 supportato.",cantRemoveStop:"Impossibile rimuovere la fermata.",waypointShouldBeInBetweenStops:"Un punto di riferimento pu\u00f2 essere inserito solo tra interruzioni esistenti o altri punti di riferimento.",couldNotUpdateStop:"Impossibile aggiornare fermata.", cantSaveRoute:"Si \u00e8 verificato un errore durante il salvataggio del percorso.",accessDenied:"Non si dispone dell'accesso al layer del percorso. Al momento si \u00e8 connessi come: ",loadError:"Errore durante il caricamento del layer del percorso."},time:{minute:"minuto",minutes:"minuti",hour:"ora",hours:"ore"},units:{KILOMETERS:{name:"chilometri",abbr:"km"},METERS:{name:"metri",abbr:"m"},MILES:{name:"miglia",abbr:"mi"},NAUTICAL_MILES:{name:"miglia nautiche",abbr:"nm"}},travelMode:{car:"In auto", truck:"In camion",walking:"Camminata"},impedance:{fastest:"Pi\u00f9 veloce",shortest:"Pi\u00f9 breve"},unlocatedStop:"\x3cposizione sconosciuta\x3e",showOptions:"Mostra altre opzioni",hideOptions:"Nascondi opzioni",findOptimalOrder:"Ottimizza ordine",useTraffic:"Usa traffico",returnToStart:"Torna all'inizio",addDestination:"Aggiungi destinazione",viewFullRoute:"Zoom a itinerario completo",getDirections:"Ottieni indicazioni",clearDirections:"Cancella",reverseDirections:"Inverti indicazioni",activate:"Aggiungere fermate facendo clic sulla mappa o modificare il percorso con punti di riferimento", print:"Stampa",printNotes:"Immettere qui le note",printDisclaimer:"Le indicazioni vengono fornite solo per la pianificazione e sono soggette alle \x3ca href\x3d'http://www.esri.com/legal/software-license' target\x3d'_blank'\x3eCondizioni d'uso di Esri\x3c/a\x3e. \u00c8 necessario tenere conto delle condizioni effettive della strada, che potrebbero essere diverse da quelle delle indicazioni, nonch\u00e9 dei segnali stradali e delle limitazioni previste per legge. L'utente si assume tutti i rischi connessi all'utilizzo delle indicazioni.", retrievingMyLocation:"Recupero della posizione in corso...",myLocationError:"Impossibile recuperare la posizione",setToMyLocation:"Utilizza posizione corrente",setToMyLocationTitle:"Parti dalla posizione corrente",stopNoTitle:"N. fermata",maneuver:"Manovra percorso",stop:"Posizione",waypoint:"Punto di riferimento",dragRoute:"Trascina per cambiare percorso",dragStop:"Trascinare per cambiare la posizione o fare clic per visualizzare i dettagli",dragWaypoint:"Trascinare per cambiare la posizione o fare clic per rimuovere", toNearbyStops:"nelle fermate vicine",saveTitle:"Salvare e condividere il percorso da utilizzare, ad esempio, in Navigator",layerName:"Nome layer risultati",save:"Salva",saveAs:"Salva come nuovo",routeIsSaved:"Il percorso \u00e8 stato salvato.",share:"Condividi il percorso"},editor:{tools:{NLS_attributesLbl:"Attributi",NLS_cutLbl:"Taglia",NLS_deleteLbl:"Elimina",NLS_extentLbl:"Estensione",NLS_freehandPolygonLbl:"Poligono a mano libera",NLS_freehandPolylineLbl:"Polilinea a mano libera",NLS_pointLbl:"Punto", NLS_polygonLbl:"Poligono",NLS_polylineLbl:"Polilinea",NLS_reshapeLbl:"Rimodella",NLS_selectionNewLbl:"Nuova selezione",NLS_selectionAddLbl:"Aggiungi a selezione",NLS_selectionClearLbl:"Cancella selezione",NLS_selectionRemoveLbl:"Elimina da selezione",NLS_selectionUnionLbl:"Unione",NLS_autoCompleteLbl:"Completamento automatico",NLS_unionLbl:"Unione",NLS_rectangleLbl:"Rettangolo",NLS_circleLbl:"Cerchio",NLS_ellipseLbl:"Ellisse",NLS_triangleLbl:"Triangolo",NLS_arrowLbl:"Freccia",NLS_arrowLeftLbl:"Freccia sinistra", NLS_arrowUpLbl:"Freccia su",NLS_arrowDownLbl:"Freccia gi\u00f9",NLS_arrowRightLbl:"Freccia destra",NLS_undoLbl:"Annulla",NLS_redoLbl:"Ripeti"}},Search:{main:{searchButtonTitle:"Cerca",clearButtonTitle:"Cancella ricerca",placeholder:"Trova luogo o indirizzo",searchIn:"Cerca in",lonlat:"Latitudine, longitudine",reverseLonLatHeader:"Cosa si intendeva?",all:"Tutto",allPlaceholder:"Trova indirizzo o luogo",emptyValue:"Immettere un termine di ricerca.",untitledResult:"Senza titolo",untitledSource:"Origine senza titolo", noResults:"Nessun risultato",noResultsFound:"Nessun risultato trovato per ${value}.",showMoreResults:"Mostra altri risultati",hideMoreResults:"Nascondi",searchResult:"Risultato ricerca",moreResultsHeader:"Altri risultati",esriLocatorName:"Esri World Geocoder"}},Geocoder:{main:{clearButtonTitle:"Cancella ricerca",searchButtonTitle:"Cerca",geocoderMenuButtonTitle:"Cambia geocodificatore",geocoderMenuHeader:"Cerca in",geocoderMenuCloseTitle:"Chiudi menu",untitledGeocoder:"Geocodificatore senza titolo"}, esriGeocoderName:"Esri World Geocoder"},geocodeMatch:{match:{mapAllCandidatesLabel:"Mappa tutti i suggerimenti",defaultSortOrderLabel:"Criterio di ordinamento predefinito",tableOptionsLabel:"Opzioni",columnLabelAddress:"Indirizzo",columnLabelType:"Tipo",columnLabelScore:"Punteggio",noDataMsg:"Nessun risultato.",userCreatedLabel:"Creato dall'utente",defaultMatchType:"Corrispondenza predefinita"},popup:{noAddress:"Nessun indirizzo trovato.",matchButtonLabel:"Confronta",discardButtonLabel:"Annulla", checkBoxLocation:"Posizione (X, Y)",checkBoxAddress:"Indirizzo suggerito",addressTitle:"Indirizzo suggerito",optionsTitle:"Opzioni di confronto:",loadingPH:"Ricerca in corso...",locationTitle:"Posizione",xTitle:"X: ",yTitle:"Y: "},customLabel:"Personalizza",idProperty:"ID",gridTitle:"Suggerimenti",matchedLC:"corrispondenti",matchedUC:"Corrispondenti",unmatchedLC:"non corrispondenti",unmatchedUC:"Non corrispondenti"},geocodeReview:{review:{noDataMsg1:"Nessuna feature non corrispondente",noDataMsg2:"Nessuna feature corrispondente", noDataMsg3:"Nessuna feature rivista",columnOriginalLocation:"Posizione originale",columnSelectedLocation:"Posizione selezionata",columnOriginalAddress:"Indirizzo originale",columnSelectedAddress:"Indirizzo selezionato"},customLabel:"Personalizza",unmatchedLC:"non corrispondenti",matchedLC:"corrispondenti",unmatchedUC:"Non corrispondenti",matchedUC:"Corrispondenti",totalUC:"Totale",remainingUC:"Residui",idProperty:"ID",reviewedUC:"Rivisti",columnLabelAddress:"Indirizzo",of:"di",unmatchedTotal:"Non corrispondenti (${count} in totale)", unmatchedRemaining:"Non corrispondenti (${count1} di ${count2} residui)",matchedTotal:"Corrispondenti (${count} in totale)",reviewedTotal:"Rivisti (${count} in totale)"},FeatureTable:{sortAsc:"Ordinamento crescente",sortDesc:"Ordinamento decrescente",defaultSort:"Criterio di ordinamento predefinito",showSelected:"Mostra record selezionati",clearSelection:"Cancella selezione",toggleColumns:"Mostra/nascondi colonne",statistics:"Statistiche",close:"Chiudi",untitled:"Senza titolo",loadingData:"Caricamento dati feature in corso...", noData:"Nessun dato trovato",dataError:"Errore dati",gridHeader:"${gridTitle} (${featureCount} feature, ${featureSelectedCount} selezionate)",add:"Aggiungi",show:"Mostra",hide:"Nascondi",relatedRecords:"Record correlati",photosAndFiles:"Foto e file",attachments:"Allegati",owners:"Proprietari",parenValue:"(${value})",date:"Data",number:"Numero",string:"Stringa",centerOnSelection:"Centra su selezione",numberOfValues:"Numero di valori",sumOfValues:"Somma di valori",minimum:"Minima",maximum:"Massima", average:"Mediocre",standardDeviation:"Deviazione standard",fieldLabel:"Campo: ${fieldName}",view:"Visualizza",upload:"Carica",uploading:"Caricamento in corso...",uploadFail:"Caricamento non riuscito.",uploadSuccess:"Caricamento riuscito.",deleting:"Eliminazione in corso...",deleteSuccess:"Eliminazione riuscita.",deleteFail:"Eliminazione non riuscita.",empty:"- vuoto -",showDetailedView:"Mostra vista dettagliata",B:"${fileSize} B",kB:"${fileSize} kB",MB:"${fileSize} MB",GB:"${fileSize} GB",TB:"${fileSize} TB", errorApplyFilter:"Impossibile applicare il filtro.",errorGetStats:"Impossibile ottenere le statistiche.",errorSelectFeatures:"Impossibile selezionare le feature.",errorLoadRow:"Impossibile caricare la riga. Selezione non riuscita.",errorValidExtent:"Impossibile generare un'estensione valida.",errorRollback:"Impossibile eseguire il rollback del valore.",errorUpdateFailed:"Aggiornamento non riuscito.",errorDomainType:"Tipo di dominio non supportato.",errorFeatureInfo:"Impossibile ottenere informazioni sulle feature.", errorGenerateStore:"Impossibile generare l'archivio."},HistogramTimeSlider:{count:"Conteggio: ${count}",dateRange:"Intervallo date: ${start} - ${end}"},layerList:{legend:"Legenda",sublayers:"Sublayer",opacity:"Opacit\u00e0",expand:"Espandi",collapse:"Comprimi",noSublayers:"Nessun sublayer da visualizzare",noLayers:"Nessun layer da visualizzare."},legend:{NLS_points:"Punti",NLS_lines:"Linee",NLS_areas:"Aree",NLS_creatingLegend:"Creazione legenda",NLS_noLegend:"Nessuna legenda",NLS_dotValue:"1 punto \x3d ${value} ${unit}", NLS_currentObservations:"Osservazioni correnti",NLS_previousObservations:"Osservazioni precedenti",high:"Alta",low:"Bassa",NLS_esriMetersPerSecond:"m/s",NLS_esriKilometersPerHour:"km/h",NLS_esriKnots:"nodi",NLS_esriFeetPerSecond:"piedi/sec",NLS_esriMilesPerHour:"miglio orario",showField:"${field}",showNormField:"${field} diviso per ${normField}",showNormPct:"${field} come una percentuale del totale",showRatio:"Rapporto di ${field} a ${normField}",showRatioPercent:"${field} come una percentuale di ${normField}", showRatioPercentTotal:"${field} come una percentuale di ${field} e ${normField}"},popup:{NLS_moreInfo:"Altre informazioni",NLS_searching:"Ricerca in corso...",NLS_prevFeature:"Oggetto feature precedente",NLS_nextFeature:"Oggetto feature seguente",NLS_close:"Chiudi",NLS_prevMedia:"Media precedente",NLS_nextMedia:"Media seguente",NLS_noInfo:"Nessuna informazione disponibile",NLS_noAttach:"Nessun allegato trovato",NLS_maximize:"Ingrandisci",NLS_restore:"Ripristina",NLS_zoomTo:"Zoom a",NLS_pagingInfo:"(${index} di ${total})", NLS_attach:"Allegati"},measurement:{NLS_distance:"Distanza",NLS_area:"Area",NLS_location:"Posizione",NLS_resultLabel:"Risultato misurazione",NLS_length_miles:"Miglia",NLS_length_kilometers:"Chilometri",NLS_length_feet:"Piedi",NLS_length_meters:"Metri",NLS_length_yards:"Iarde",NLS_length_nautical_miles:"Miglia marine",NLS_area_acres:"Acri",NLS_area_sq_miles:"Miglia quadre",NLS_area_sq_kilometers:"Chilometri quadri",NLS_area_hectares:"Ettari",NLS_area_sq_yards:"Iarde quadre",NLS_area_sq_feet:"Piedi quadri", NLS_area_sq_meters:"Metri quadri",NLS_area_sq_nautical_miles:"Miglia marine quadrate",NLS_deg_min_sec:"DMS",NLS_decimal_degrees:"Gradi",NLS_map_coordinate:"Coordinate mappa",NLS_longitude:"Longitudine",NLS_latitude:"Latitudine",NLS_MGRS:"MGRS",NLS_USNG:"USNG",NLS_UTM:"UTM",NLS_GeoRef:"GeoRef",NLS_GARS:"GARS",NLS_geometry_service_error:"Errore servizio geometria",NLS_calculating:"Calcolo in corso...",NLS_length_miles_us:"Miglia (USA)",NLS_area_sq_miles_us:"Miglia quadrate (USA)",NLS_length_feet_us:"Piede (USA)", NLS_area_sq_feet_us:"Piede quadrato (USA)",NLS_length_yards_us:"Iarde (USA)",NLS_area_sq_yards_us:"Iarde quadrate (USA)",NLS_area_acres_us:"Acri (USA)"},bookmarks:{NLS_add_bookmark:"Aggiungi segnalibro",NLS_new_bookmark:"Senza titolo",NLS_bookmark_edit:"Modifica",NLS_bookmark_remove:"Rimuovi"},print:{NLS_print:"Stampa",NLS_printing:"Stampa",NLS_printout:"Stampa"},textSymbolEditor:{symbolConfiguration:"Configurazione simboli",alignment:"Allineamento",color:"Colore",halo:"Alone"},scalebar:{km:"km", mi:"mi",ft:"piedi",m:"m"},templatePicker:{creationDisabled:"La creazione delle feature \u00e8 disabilitata per tutti i layer.",loading:"Caricamento in corso..."},renderingRule:{rendererLabelTitle:"Renderer",bandCombinationLabelTitle:"RGB composto",userDefinedRendererTitle:"Renderer definito dall'utente",userDefinedRendererDesc:"Un renderer definito dall'utente. Utilizzare bande diverse per gli input per i canali Rosso, Verde e Blu (solo servizi multibanda). Applicare diversi algoritmi di miglioramento radiometrici per dare un aspetto migliore all'immagine.", imageEnhancementLabelTitle:"Miglioramento dell'immagine",stretchDescLabel:"Applicare dei miglioramenti al contrasto per migliorare la visualizzazione dell'immagine",stretchMethodLabel:"Tipo di estensione:",stretchMethodNoneDesc:"Nessun ulteriore miglioramento applicato.",stretchMethodMinMaxDesc:"Estendi sull'intera gamma di valori di pixel.",numStdDevLabelTitle:"Taglia valori di pixel estremi oltre le",numStdDevEndLabelTitle:"deviazioni standard.",draLabelTitle:"Regolazione gamma dinamica",minMaxDescLabelTitle:"Taglia valori di pixel estremi", minPercentLabelTitle:"Escludi parte inferiore:",maxPercentLabelTitle:"Escludi parte superiore:",percentLabelTitle:"%",gammaLabelTitle:"Gamma:",bandNamesRequestMsg:"Richiesta di informazioni sulle bande in corso...",noneStretchAlias:"Nessuno",minMaxStretchAlias:"Minimo e massimo",stdDevStretchAlias:"Deviazione standard",percentClipStretchAlias:"Ritaglio percentuale",minGammaLabel:"0,1",maxGammaLabel:"10"},vectorFieldRenderer:{symbolTypeLabelTitle:"Simbolo:",simpleScalarLabelTitle:"Scalare semplice", simpleScalarDesc:"Rappresenta la grandezza dei dati utilizzando simboli con dimensioni progressive.",singleArrowLabelTitle:"Freccia singola",singleArrowDesc:"Rappresenta la grandezza e la direzione del flusso mediante una freccia. La dimensione della freccia rappresenta la grandezza del flusso, mentre la direzione della freccia indica la direzione del flusso.",windBarbsLabelTitle:"Frecce direzionali vento",windBarbsDesc:"Rappresenta la grandezza e la direzione del vento mediante frecce direzionali. Una freccia lunga rappresenta 10 nodi, una freccia corta rappresenta 5 nodi, mentre una freccia con bandierina nera rappresenta 50 nodi. La bandierina \u00e8 rivolta a seconda della direzione di origine del vento.", beaufortLabelTitle:"Scala Beaufort (forza del vento)",beaufortDesc:"Rappresenta la grandezza e la direzione del vento in base alla scala Beaufort della forza del vento. La grandezza \u00e8 suddivisa in categorie dal livello 0 al livello 12, dove 0 rappresenta la bonaccia (visualizzata in blu), mentre 12 rappresenta un uragano (rosso). La freccia \u00e8 rivolta a seconda della direzione di origine del vento.",oceanCurrentKnotsLabelTitle:"Corrente oceanica (nove classi)",oceanCurrentKnotsDesc:"Rappresenta la grandezza e la direzione della corrente oceanica in base a nove categorie predefinite con un intervallo da 0 a 4 nodi. La freccia \u00e8 rivolta a seconda della direzione corrente del flusso.", oceanCurrentMpsLabelTitle:"Corrente oceanica (quattro classi)",oceanCurrentMpsDesc:"Rappresenta la grandezza e la direzione della corrente oceanica in base a quattro categorie predefinite con un intervallo da 0 a 2 m/s. La freccia \u00e8 rivolta a seconda della direzione corrente del flusso.",classifiedArrowLabelTitle:"Freccia classificata",classifiedArrowDesc:"Rappresenta la grandezza e la direzione del flusso in base a categorie calcolate con riferimento ai limiti di grandezza. La grandezza \u00e8 rappresentata mediante la progressione delle dimensioni e dei colori dei simboli, a partire dal verde (limite inferiore) fino al rosso (limite superiore).", dataTypeLabelTile:"Rappresentazione flusso tramite direzione:",angleFromAlias:"Da (meteorologico)",angleToAlias:"A (oceanografico)",unitLabelTitle:"Converti grandezza ",outputUnitLabelTitle:"A: ",inputUnitLabelTitle:"Da: ",symbolDensityLabelTitle:"Densit\u00e0 simbolo: ",sparseTileSizeAlias:"Sparso",denseTileSizeAlias:"Compatto",symbolSizeLabelTitle:"Scala simbolo:",minSymbolSizeAlias:"Minima",maxSymbolSizeAlias:"Massima",advancedOptionsTitle:"Impostazioni avanzate",magnitudeLabelTitle:"Grandezza", minAlias:"Minima:",maxAlias:"Massima:",invalidNumberMessage:"Immettere un valore numerico.",dataValueRangeLabelTitle:"Le dimensioni del simbolo rappresentano l'intervallo di grandezza. Definire l'intervallo di grandezza.",applyLabelTitle:"Applica",esriMetersPerSecond:"m/s",esriKilometersPerHour:"km/h",esriKnots:"nodi",esriFeetPerSecond:"piedi/sec",esriMilesPerHour:"miglio orario"},mosaicRule:{mosaicMethodLabel:"Classifica immagini in base a:",orderFieldLabel:"Attributo",orderValueLabel:"Valore massimo priorit\u00e0:", lockRasterIdLabel:"ID immagine:",mosaicOperatorLabel:"Risolvi sovrapposizione pixel mediante:",descendingLabel:"Inverti ordine",queryLabel:"Filtra immagini:",queryFieldLabel:"Campo:",queryOperatorLabel:"Operatore:",queryValueLabel:"Valore:",selectAllLabel:"Seleziona tutto",mosaicruleNotApplicable:"Il layer immagine contiene una sola immagine e non supporta la modifica dell\u00b4ordine di visualizzazione delle immagini.",lockRasterRequestMsg:"Ricerca in corso...",lockRasterRequestDoneMsg:"Operazione completata...", lockRasterRequestErrorMsg:"Errore durante la ricerca...",lockRasterRequestNoRasterMsg:"Nessun raster trovato...",refreshLockRasterIdsLabel:"Aggiorna",orderFieldNotFound:"Non disponibile",byAttributeAlias:"Un attributo",centerAlias:"Centro immagine pi\u00f9 vicino a centro vista",lockRasterAlias:"Un elenco di immagini",nadirAlias:"Posizione sensore pi\u00f9 vicina a centro vista",northWestAlias:"Ordine fisso con estremo Nord ovest per primo",seamlineAlias:"Linee di confine definite",viewPointAlias:"Punto di osservazione", noneAlias:"Solo scala",firstAlias:"Solo priorit\u00e0 massima",lastAlias:"Solo priorit\u00e0 minima",minAlias:"Minimo dei valori pixel",maxAlias:"Massimo dei valori pixel",averageAlias:"Media dei valori pixel",blendAlias:"Fondi valori pixel",sumAlias:"Somma dei valori pixel"},multidimensionalFilter:{variableFilter:"Variabile",filterByDimensionalValues:"Dimensioni",fromTimeText:"Ora di inizio:",toTimeText:"Ora di fine:",fromNumericText:"Da:",toNumericText:"A:",sliceTimeText:"Ora:",sliceNumberText:"Valore:", rangeText:"Definire un intervallo",hasRangesInfoText1:"I punti di dati sono sotto forma di intervalli.",hasRangesInfoText2:"Selezionare i valori dell'intervallo predefinito.",defaultVariableText:"Predefinito",dateSnapText:"Con snap alla data pi\u00f9 vicina",numSnapText:"Con snap al valore pi\u00f9 vicino",disabledNumericDimensionText:"*Disabilitato perch\u00e9 il cursore delle dimensioni \u00e8 attivo.",disabledTimeDimensionText:"*Disabilitato perch\u00e9 il cursore delle ore \u00e8 attivo.",applyLabelTitle:"Applica", startNumberButtonTooltip:"Prima",nextButtonTooltip:"Seguente",previousButtonTooltip:"Precedente",endNumberButtonTooltip:"Ultima",startDateButtonTooltip:"Prima",endDateButtonTooltip:"Ultima",tooltipNumberFromValueText:"Minima:",tooltipNumberToValueText:"Massima:",tooltipCountText:"Conteggio:",tooltipDateFromValueText:"Prima:",tooltipDateToValueText:"Ultima:"},imageServiceMeasure:{measureBtnText:"Misura",angularUnits:"Unit\u00e0 angolari",linearUnits:"Unit\u00e0 lineari",areaUnits:"Unit\u00e0 Area", infoWindowTitle:"Misura risultato",measure3DLabel:"Misura in 3D",settings:"Impostazioni",mensurationCapabilitiesAbsentText:"Funzionalit\u00e0 di misurazione non supportate dal layer.",measurementErrorGeneric:"Impossibile eseguire misurazione. Parametri di input non validi o mancanti.",operationLabel:{OPERATION_POINT:"Posizione",OPERATION_DISTANCE_ANGLE:"Distanza e angolo",OPERATION_AREA_PERIMETER:"Area e perimetro",OPERATION_BASE_TOP:"Altezza: da base a cima",OPERATION_BASE_TOP_SHADOW:"Altezza: ombra da base a cima", OPERATION_TOP_TOP_SHADOW:"Altezza: ombra da cima a cima",OPERATION_CENTROID:"Centroide",OPERATION_POINT_3D:"Posizione (3D)",OPERATION_DISTANCE_ANGLE_3D:"Distanza e angolo (3D)",OPERATION_AREA_PERIMETER_3D:"Area e perimetro (3D)",OPERATION_CENTROID_3D:"Centroide (3D)"},unitLabel:{INCHES:"Pollici",FEET:"Piede",YARDS:"Iarde",MILES:"Miglia",NAUTICAL_MILES:"Miglia nautiche",MILLIMETERS:"Millimetri",CENTIMETERS:"Centimetri",DECIMETERS:"Decimetri",METERS:"Metri",KILOMETERS:"Chilometri",RADIANS:"Radianti", DECIMAL_DEGREES:"Gradi",SQUARE_INCHES:"Pollici quadrati",SQUARE_FEET:"Piedi quadrati",SQUARE_YARDS:"Iarde quadrate",ACRES:"Acri",SQUARE_MILES:"Miglia quadrate",SQUARE_MILLIMETERS:"Millimetri quadrati",SQUARE_CENTIMETERS:"Centimetri quadrati",SQUARE_DECIMETERS:"Decimetri quadrati",SQUARE_METERS:"Metri quadrati",ARES:"Are",HECTARES:"Ettari",SQUARE_KILOMETERS:"Chilometri quadrati"},measureDialog:{Point:"Posizione",Centroid:"Centroide",X:"X",Y:"Y",Distance:"Distanza",AzimuthAngle:"Angolo di azimuth", ElevationAngle:"Angolo di elevazione",Area:"Area",Perimeter:"Perimetro",Height:"Altezza"}},obliqueViewer:{northTooltip:"Angolo di visualizzazione verso nord",southTooltip:"Angolo di visualizzazione verso sud",eastTooltip:"Angolo di visualizzazione verso est",westTooltip:"Angolo di visualizzazione verso ovest",nadirTooltip:"Centra come se visto dall'alto"},tags:{addTags:"Aggiungi tag",noTagsFound:"Non esiste corrispondenza di tag.",required:"Sono obbligatori uno o pi\u00f9 tag."},rendererSlider:{statsAvg:"Media: ${avg}", count:"Conteggio: ${count}",percent:"${num}%",high:"Massimo",low:"Minimo",color:{changeMinMaxToolTIp:"Digitare un valore.",handleToolTip:"Abbinare i valori dei dati ai colori.",maxValueToolTip:"Digitare il valore di dati pi\u00f9 alto previsto.",minValueToolTip:"Digitare il valore di dati pi\u00f9 basso previsto.",changeSymbol:"Cambia simbolo"},size:{handleToolTip:"Abbinare i valori dei dati alla dimensione del simbolo.",sizeInputBoxLines:"Impostare lo spessore della linea su un valore da 0 a 18 pixel.", sizeInputBoxPoints:"Impostare la dimensione del simbolo su un valore da 1 a 120 pixel"}},histogram:{statsAvg:"Media: ${avg}",statsSD:"Deviazione standard: ${sd}",count:"Conteggio: ${count}",percent:"${num}%"},zoomSlider:{zoomIn:"Ingrandisci",zoomOut:"Riduci"},colorPicker:{transparency:"Trasparenza",suggested:"Suggerito",recent:"Recente",more:"Maggiori informazioni",moreColorsTooltip:"Visualizza altri colori.",paletteTooltip:"Selezionare un colore.",noColorTooltip:"Nessun colore",hexInputTooltip:"Colore personalizzato nella notazione esadecimale (#FFFF00)."}, visibleScaleRangeSlider:{noLimit:"Nessun limite",preview:"Anteprima",currentScaleTooltip:"Scala mappa corrente (${scaleLabel})",customScaleInputTooltip:"Digitare una scala.",current:"Corrente",setTo:"Imposta su",selectOne:"(selezionare un'opzione)",setToSelectOne:"${setTo} ${selectOne}",useSameAs:"Utilizza come",layerNameAndType:"${name} (${type})",layer:"Layer",basemap:"Mappa di base",scaleRangeLabels:{world:"Mondo",continent:"Continente",countries:"Paesi",country:"Paese",states:"Stati",state:"Stato", counties:"Regioni",county:"Regione",metropolitanArea:"Area metropolitana",cities:"Citt\u00e0",city:"Citt\u00e0",town:"Citt\u00e0",neighborhood:"Vicinato",streets:"Vie",street:"Strada",buildings:"Edifici",building:"Edificio",smallBuilding:"Edificio piccolo",rooms:"Sale",room:"Sala"},featuredScaleLabels:{current:"Vista mappa corrente (${scaleLabel})",world:"Mondo (${scaleLabel})",continent:"Contenuto (${scaleLabel})",countriesBig:"Paesi- Grandi (${scaleLabel})",countriesSmall:"Paesi - Piccoli (${scaleLabel})", statesProvinces:"Stati/Province (${scaleLabel})",stateProvince:"Stato/Provincia (${scaleLabel})",counties:"Paesi (${scaleLabel})",county:"Paese (${scaleLabel})",metropolitanArea:"Area metropolitana (${scaleLabel})",cities:"Citt\u00e0 (${scaleLabel})",city:"Citt\u00e0 (${scaleLabel})",town:"Cittadina (${scaleLabel})",neighborhood:"Vicinanza (${scaleLabel})",streets:"Strade (${scaleLabel})",street:"Strada (${scaleLabel})",buildings:"Edifici (${scaleLabel})",building:"Edificio (${scaleLabel})",smallBuilding:"Edificio piccolo (${scaleLabel})", rooms:"Stanze (${scaleLabel})",room:"Stanza (${scaleLabel})"}},symbolEditor:{preview:"Anteprima",shape:"Forma",fill:"Riempi",outline:"Contorno",px:"px",symbolSize:"Dimensione simbolo",symbolSizeTooltip:"Imposta la dimensione del simbolo da ${min} a ${max} pixel.",useImage:"Usa immagine",useImageTooltip:"Usa un'immagine personalizzata.",imageUrlInputTooltip:"Per ottenere risultati ottimali, utilizzare un'immagine quadrata (PNG, GIF o JPEG) di dimensioni non superiori a 120 x 120 pixel. Altre dimensioni verranno regolate per l'adattamento.", imageUrlInputPlaceholder:"https://\x3cURL immagine\x3e",selectCategoryTooltip:"Selezionare una categoria.",imageLoadError:"Impossibile caricare l'immagine.",symbolLoadError:"Impossibile caricare i simboli.",noFillTooltip:"Nessun riempimento",symbolTransparencyTooltip:"Trasparenza simbolo",lineWidth:"Larghezza linea",lineWidthTooltip:"Imposta la larghezza di una linea da ${min} a ${max} pixel.",pattern:"Modello",patternTooltip:"Tipo di linea",flipColors:"Inverti colori",flipColorsTooltip:"Inverte la scala cromatica.", noOutlineTooltip:"Nessun contorno",autoAdjustOutline:"Regola automaticamente il bordo",saturation:"Saturazione",saturationTooltip:"Regola l'intensit\u00e0 del colore.",selectRampTooltip:"Seleziona una scala cromatica."}},arcgis:{utils:{baseLayerError:"Impossibile caricare il layer mappa di base",geometryServiceError:"Specificare un servizio di geometria per aprire la mappa Web.",showing:"Visualizzazione di ${fieldAlias}"}},identity:{lblItem:"Elemento",title:"Accedi",info:"Effettuare l'accesso per accedere all'elemento su ${server} ${resource}", oAuthInfo:"Eseguire l'accesso per continuare.",lblUser:"Nome utente:",lblPwd:"Password:",lblOk:"OK",lblSigning:"Accesso in corso...",lblCancel:"Annulla",errorMsg:"Nome utente/password non validi. Riprovare.",invalidUser:"Il nome utente o la password inseriti non sono validi.",forbidden:"Il nome utente e la password sono validi, ma non si dispone di accesso alla risorsa.",noAuthService:"Impossibile accedere al servizio di autenticazione."},common:{cancel:"Annulla",ok:"OK",create:"Crea",close:"Chiudi", done:"Fine",apply:"Applica",remove:"Rimuovi",open:"Apri",edit:"Modifica",share:"Condividi",save:"Salva",help:"Guida",warning:"Avviso",deleteLabel:"Elimina",titleLabel:"Titolo:",newLabel:"Nuovo",arcgis:"ArcGIS",previous:"Precedente",submit:"Invia",next:"Seguente",yesLabel:"S\u00ec",noLabel:"No",errorTitle:"Errore",upload:"Carica",sum:"Somma",minimum:"Minimo",maximum:"Massimo",average:"Media",standardDev:"Deviazione standard",statistic:"Statistica",attribute:"Campo",selectAttribute:"Selezionare l'attributo", runAnalysis:"Analizza",oneLabel:"1",twoLabel:"2",threeLabel:"3",fourLabel:"4",fiveLabel:"5",sixLabel:"6",sevenLabel:"7",eightLabel:"8",nineLabel:"9",tenLabel:"10",outputnameMissingMsg:"Il nome output \u00e8 obbligatorio",miles:"Miglia",kilometers:"Chilometri",meters:"Metri",feet:"Piedi",degree:"Gradi decimali",inches:"Pollici",nautMiles:"Miglia marine",pointsUnit:"Punti",yards:"Iarde",comingSoonLabel:"Disponibile a breve.",sqMiles:"Miglia quadrate",sqFeet:"Piedi quadri",sqKm:"Chilometri quadrati", sqMeters:"Metri quadrati",hectares:"Ettari",acres:"Acri",seconds:"Secondi",minutes:"Minuti",hours:"Ore",count:"Conteggio",variance:"Varianza",range:"Intervallo",days:"Giorni",weeks:"Settimane",years:"Anni",months:"Mesi",today:"Oggi",monday:"luned\u00ec",tuesday:"marted\u00ec",wednesday:"mercoled\u00ec",thursday:"gioved\u00ec",friday:"venerd\u00ec",saturday:"sabato",sunday:"domenica",chooseSummarizeLabel:"Scegliere il layer per il riepilogo",creditTitle:"Report utilizzo crediti",analysisLayers:"Layer analisi:", showCredits:"Mostra crediti",learnMore:"Ulteriori informazioni",hoursSmall:"ora",minutesSmall:"min",secondsSmall:"sec",statsRequiredMsg:"\u00c8 necessario specificare almeno uno dei parametri delle statistiche.",nowLabel:"Adesso",hrsLabel:"h",groupLabel:"Gruppo",ungroupLabel:"Separa",and:"e",or:"oppure",add:"Aggiungi",polygons:"Poligoni",points:"Punti",lines:"Linee",input:"Input",areas:"Aree",validateRouteIdMsg:"I layer devono contenere lo stesso numero di record oppure un layer deve contenere un solo record.", straightLineDistance:"Distanza tra linee",outputLabel:"Output:",addPoint:"Fare clic per aggiungere un punto",movePoint:"Fare clic per spostare il punto",selectAll:"Seleziona tutto",unselectAll:"Deseleziona tutto",selectLabel:"Seleziona",queryLabel:"Interrogazione",drawnBoundary:"Confine segnato",basic:"Base",intermediate:"Intermedio",advanced:"Avanzato",majority:"Maggioranza",minority:"Minoranza",addMinMajorityLable:"Aggiungi minoranza, maggioranza",addPercentageLabel:"Aggiungi percentuali",drivingMode:"In auto", truckingMode:"In camion",walkingMode:"Camminata",distanceMsg:"Sono consentiti solo valori numerici",analysisLayerLabel:"Selezionare il layer di analisi",selectPointLayer:"\u00c8 necessario selezionare un feature layer punto per l'esecuzione di ${toolName}.",selectPolyLayer:"\u00c8 necessario selezionare un feature layer area (poligono) per l'esecuzione di ${toolName}.",hotspotsLineFeatureMsg:"Non \u00e8 possibile specificare feature lineari come input per ${toolName}.",areaFeatureInvalidMsg:"Non \u00e8 possibile specificare feature area come input per ${toolName}.", overlayValidationMsg:"Per eseguire ${toolName}, \u00e8 necessario disporre di due feature layer nella mappa.",aggregatePolyMsg:"Per eseguire ${toolName}, \u00e8 necessario disporre di almeno un feature layer area (poligono).",odPointMsg:"Per eseguire ${toolName}, \u00e8 necessario disporre di almeno due feature layer punto.",mapNotesAllMsg:"La nota della mappa contiene punti, linee e aree. Per ${toolName} verranno utilizzate solo le aree.",mapNotesPtsPoly:"La nota della mappa contiene punti e aree. Per ${toolName} verranno utilizzate solo le aree.", mapNotesLinesPoly:"La nota della mappa contiene linee e aree. Per ${toolName} verranno utilizzate solo le aree.",mapNotesLinesPts:"La nota della mappa contiene punti e linee. Per ${toolName} verranno utilizzate solo le linee.",mergeValidationMsg:"L'opzione Unisci layer richiede almeno due layer dello stesso tipo di feature (punto, linea, area).",runAnalysisMsg:"I dati sono in fase di estrazione e saranno disponibili in I miei contenuti.",extractValidationMsg:"Nella mappa non sono presenti dati estraibili. Il proprietario dei dati deve prima consentire l'esportazione da parte di altri utenti.", analysisSignInErrorMsg:"Impossibile accedere al servizio di analisi.",drawLabel:"Disegna",noneLabel:"Nessuno",chooseLabel:"Scegli...",browseAnalysisTitle:"Scegli layer di analisi atlante dinamico",addLayer:"Aggiungi layer a mappa",withinMapArea:"Nell'area della mappa",back:"Indietro",insufficientCreditsMsg:"Non si dispone di crediti sufficienti per eseguire questa operazione. Contattare l'amministratore di sistema ArcGIS per richiedere assistenza.",decimeters:"Decimetri",millimeters:"Millimetri", centimeters:"Centimetri",noImageServiceMsg:"Per eseguire ${toolName}, \u00e8 necessario disporre di almeno un layer di image service.",noSingleBandISMsg:"Per eseguire ${toolName}, \u00e8 necessario disporre di almeno un layer di image service a banda singola.",noMultiBandISMsg:"Per eseguire ${toolName}, \u00e8 necessario disporre di almeno un layer di image service a pi\u00f9 bande.",browseLayers:"Sfoglia layer",addLayerBtnLabel:"Aggiungi layer",timeEnabled:"Ora abilitata",milliseconds:"Millisecondi", browseAnalysisLayers:"Scegliere un layer di analisi",listLabel:"Campi",allLabel:"Tutto",geodesicLabel:"Geodetico",planarLabel:"Planare",spatialReference:"Riferimento spaziale (wkid)",addStatsLabel:"Aggiungi statistiche (facoltativo)",fieldExpLabel:"Espressione",datastoreLabel:"Scegliere un archivio dati",relationalDS:"Archivio dati relazionale",spatialDS:"Archivio dati spazio-temporale"},analysisTools:{performAnalysis:"Esegui analisi",summarizeData:"Riepiloga dati",findLocations:"Trova posizioni", aggregateTool:"Aggrega punti",bufferTool:"Dati buffer",dataEnrichment:"Miglioramento dati",analyzePatterns:"Analizza modelli",useProximity:"Usa prossimit\u00e0",manageData:"Gestisci dati",aggregateToolName:"Aggrega punti",bufferToolName:"Crea buffer",aggregatePoints:"Aggrega punti",summarizeWithin:"Riepiloga entro",summarizeNearby:"Riepiloga nelle vicinanze",reconstructTracks:"Ricostruisci tracce",enrichLayer:"Aggiungi dati al layer",findNearest:"Trova pi\u00f9 vicine",findHotSpots:"Trova hot spot", createBuffers:"Crea buffer",dissolveBoundaries:"Dissolvi confini",mergeLayers:"Unisci layer",extractData:"Estrai dati",overlayLayers:"Sovrapponi layer",fieldCalculator:"Calcolatore campo",createDriveTimeAreas:"Crea aree tempo di guida",deriveNewLocations:"Deriva nuove localit\u00e0",findExistingLocations:"Trova localit\u00e0 esistenti",findSimilarLocations:"Trova localit\u00e0 simili",exploreCorrelations:"Esplora correlazioni",findRoute:"Trova itinerario",generateFleetPlan:"Genera piano itinerari per flotta", createDensitySurface:"Crea superficie di densit\u00e0",interpolatePoints:"Interpolazione punti",orgUsrMsg:"Per eseguire il servizio, \u00e8 necessario essere membro di un'organizzazione.",pubRoleMsg:"All'account online non \u00e8 stato assegnato il ruolo di editore.",servNameExists:"Esiste gi\u00e0 un layer risultati con questo nome. I nomi di layer risultati devono essere univoci nell'organizzazione. Specificare un nome diverso.",outputLayerLabel:"Nome layer risultati",outputFileName:"Nome file di output", emptyResultInfoMsg:"I risultati dell'analisi non hanno restituito alcuna feature. Non verranno creati dei layer.",invalidServiceName:'Il nome del layer dei risultati contiene uno o pi\u00f9 caratteri non validi (\x3c, \x3e, #, %, :, ", ?, \x26, +, / o \\).',invalidServiceNameLength:"La lunghezza del nome del layer risultati deve essere inferiore a 98 caratteri.",invalidEncodedServiceNameLength:"La lunghezza del nome del layer risultati codificato deve essere inferiore a 170 caratteri.",requiredValue:"Valore obbligatorio.", saveResultIn:"Salva risultato in",useMapExtent:"Usa estensione mappa corrente",connectOriginsToDestinations:"Connetti origini a destinazioni",planRoutes:"Pianifica itinerari",calculateDensity:"Calcolo densit\u00e0",traceDownstream:"Traccia a valle",createWatershed:"Crea spartiacque",createViewshed:"Crea campo di vista",createWatersheds:"Crea spartiacque",filterNoResults:"Il filtro non ha restituito risultati.",chooseBestFacilities:"Scegli strutture migliori",createPanel:"Crea pannello",createSpaceTimeCube:"Crea cubo spazio-temporale", joinFeatures:"Join delle feature",analyzeImage:"Analizza immagine",analyzeTerrain:"Analizza terreno",summarizeRasterWithin:"Riepiloga raster entro",histogramRasterWithin:"calcola istogramma raster entro",findSuitableLocations:"Trova localit\u00e0 adatte",filterLocations:"Filtra posizioni",calculateDistance:"Calcola distanza",findShortestPath:"Trova percorso minimo",segmentImage:"Segmenta immagine",classifyImage:"Classifica immagine",detectDifferences:"Rileva differenze",monitorVegetation:"Monitora vegetazione", calculateSlope:"Calcola pendenza",deriveAspect:"Deriva aspetto",extractRaster:"Estrai raster",remapValues:"Rimappa valori",convertFeatureToRaster:"Converte feature in raster",convertRasterToFeature:"Converte raster in feature",saveLayerType:"Tipo layer di output",dynamicLayer:"Layer dinamico",permanentLayer:"Layer immagine Web"},aggregatePointsTool:{aggregateDefine:"Conta \x3cb\x3e${layername}\x3c/b\x3e entro",outputLayerName:"Aggregazione di ${pointlayername} in ${polygonlayername}",groupByLabel:"Scegli campo in base a cui raggruppare (facoltativo)", itemDescription:"Feature service generato dall'esecuzione di soluzioni Aggrega punti. I punti di ${pointlayername} sono stati aggregati in ${polygonlayername}",itemTags:"Risultato analisi, Aggrega punti, ${pointlayername}, ${polygonlayername}",itemSnippet:"Feature service Analisi generato da Aggrega punti",removeAttrStats:"Rimuovi statistiche attributi",keepPolygonLabel:"Mantieni le aree senza punti",chooseAreaLabel:"Scegli il layer contenente le aree di aggregazione",analysisLayerLabel:"Scegli il layer contenente i punti da aggregare nelle aree", aggTimeStepsLabel:"Aggrega usando periodi di tempo (facoltativo)",intervalLabel:"Intervallo di tempo in cui eseguire l'aggregazione",repeatLabel:"Passaggio temporale in cui eseguire l'aggregazione",timeRefLabel:"Tempo di riferimento utilizzato per allineare il periodo di tempo",binsLabel:"Scegliere una distanza per generare contenitori e in cui eseguire l'aggregazione",polygonLabel:"Scegliere un layer poligono in cui eseguire l'aggregazione",aggOption:"Scegliere le aree di aggregazione",bins:"Contenitori"}, findHotSpotsTool:{hotspotsPolyDefine:"Analizza \x3cb\x3e${layername}\x3c/b\x3e per trovare gli hot spot e cold spot statisticamente rilevanti di ",hotspotsPointDefine:"Analizza \x3cb\x3e${layername}\x3c/b\x3e per trovare hot spot e cold spot statisticamente rilevanti ",fieldLabel:"con o senza un campo di analisi",noAnalysisField:"Senza campo di analisi",hotspots:"Hot spot",outputLayerName:"Hot spot ${layername}",Options:"Opzioni",defineBoundingLabel:"Definisci dove sono possibili i punti",provideAggLabel:"Calcolare i punti all'interno", defaultBoundingOption:"Nessuno",defaultAggregationOption:"Griglia Fishnet",itemDescription:"Feature service generato dall'esecuzione della soluzione Trova hot spot.",itemTags:"Risultato analisi, Hot spot, ${layername}, ${fieldname}",itemSnippet:"Feature service Analisi generato da Trova hot spot",chooseAttributeLabel:"Trova cluster di valori alti e bassi",divideByLabel:"Suddividi per (facoltativo)",blayerName:"Confini segnati",analysisLayerLabel:"Scegli il layer per il quale verranno calcolati gli hot spot", pointCounts:"Conteggi punti",enrichLabel:"Popolazione Esri (con utilizzo di crediti)"},overlayLayersTool:{overlayDefine:"Sovrapponi \x3cb\x3e${layername}\x3c/b\x3e a",chooseOverlayLayer:"Scegliere il layer per la sovrapposizione",chooseOverlayMethod:"Scegliere il metodo di sovrapposizione",chooseOutputType:"Seleziona tipo di output",itemDescription:"Feature service generato dall'esecuzione della soluzione Sovrapponi layer.",itemTags:"Risultato analisi, Sovrapponi layer, ${layername}",itemSnippet:"Feature service Analisi generato da Sovrapponi layer", unionOutputLyrName:"Unione di ${layername} e ${overlayname}",intersectOutputLyrName:"Intersezione di ${layername} e ${overlayname}",eraseOutputLyrName:"Cancella ${layername} con ${overlayname}",overlayLayerPolyMsg:"Il layer di sovrapposizione deve essere di tipo poligono per la sovrapposizione di tipo unione",notSupportedEraseOverlayMsg:"Layer di sovrapposizione non supportato per la sovrapposizione di tipo cancellazione. Verr\u00e0 utilizzata la sovrapposizione di tipo intersezione.",intersect:"Incrocia", union:"Unione",erase:"Cancella",analysisLayerLabel:"Scegli il layer di input"},bufferTool:{bufferDefine:"Crea buffer da \x3cb\x3e${layername}\x3c/b\x3e",outputLayerName:"Buffer di ${layername}",sizeLabel:"Immetti dimensione buffer",sizeHelp:"Per creare pi\u00f9 buffer, immettere le distanze separate da spazi (2 3 5).",typeLabel:"Tipo di buffer",resultLabel:"Nome layer risultati",optionsLabel:"Opzioni",itemDescription:"Feature service generato dall'esecuzione della soluzione Feature buffer. I dati di input di ${layername} sono stati memorizzati nel buffer a una distanza di ${distance_field} ${units}", itemTags:"Risultato analisi, Buffer, ${layername}",itemSnippet:"Feature service Analisi generato da Buffer",overlap:"Sovrapponi",dissolve:"Dissolvi",include:"Includi",exclude:"Escludi",around:"Intorno a",sideType:"Tipo di lato",endType:"Tipo finale",left:"Sinistra",right:"Destra",round:"Arrotondato",flat:"Piatto",multipleDistance:"I buffer per pi\u00f9 distanze devono essere",rings:"Anelli",disks:"Dischi",areaofInputPoly:"Poligoni dell'area di input in poligoni buffer",distance:"Distanza",field:"Campo", analysisLayerLabel:"Scegli il layer contenente le feature da includere nel buffer",dissolveType:"Selezionare il tipo di metodo di dissolvenza",method:"Selezionare il metodo di buffer",allowMulitipart:"Consenti poligoni multiparte",bufferDefineBd:"Scegliere il layer a cui applicare il buffer",bufferTypeBd:"Selezionare il tipo di layer da applicare",selectFieldToDissLabel:"Selezionare i campi in cui eseguire la dissolvenza"},driveTimes:{toolDefine:"Crea aree intorno a \x3cb\x3e${layername}\x3c/b\x3e", outputLayerName:"Guida da ${layername} (${breakValues} ${breakUnits})",outputModeLayerName:"${mode} da ${layername} (${breakValues} ${breakUnits})",driving:"Guida",trucking:"Camion",walking:"Cammina",other:"Viaggio",measureLabel:"Misura",measureHelp:"Per ottenere pi\u00f9 aree per ciascun punto, digitare le dimensioni separate da spazi (2 3.5 5).",areaLabel:"Aree da punti diversi",trafficLabel:"Usa traffico",typicalTraffCdtnLabel:"Traffico basato su condizioni standard per",resultLabel:"Nome layer risultati", liveTrafficLabel:"Traffico in tempo reale",itemDescription:"Feature service generato dall'esecuzione della soluzione Crea poligoni tempo di guida.",itemTags:"Risultato analisi, Tempi di guida, ${layername}",itemSnippet:"Feature service Analisi generato da Crea poligoni tempi di guida",split:"Dividi",seeAvailability:"Visualizza la disponibilit\u00e0.",timeOfDeparture:"Ora di partenza",drivingDistance:"Distanza di guida",drivingTime:"Tempo di guida",truckingTime:"Tempo di guida in camion",truckingDistance:"Distanza di guida in camion", walkingDistance:"Distanza a piedi",walkingTime:"Tempo a piedi",liveSingularTimeLabel:"Traffico in tempo reale + 1 ora ${minute} min",liveSingularHourTimeLabel:"Traffico in tempo reale + 1 ora",liveTimeLabel:"Traffico in tempo reale + ${hour} ora ${minute} min",liveTimeHoursLabel:"Traffico in tempo reale + ${hour} ora",liveTimeMinutesLabel:"Traffico in tempo reale + ${minute} min",analysisLayerLabel:"Scegli il layer di punti per calcolare le aree del tempo di guida nei dintorni"},routeOriginDestinationPairsTool:{toolDefine:"Itinerario tra coppie di punti la cui origine \u00e8 \x3cb\x3e${layername}\x3c/b\x3e", labelOne:"Itinerario per destinazioni in",pairPoints:"Punti con ID corrispondenti collegati:",originTripId:"Campo ID in origini",destnTripId:"Campo ID corrispondente in destinazioni",includeSegments:"Includi singoli segmenti di strada.",inValidNumberRecordsMsg:"I layer devono contenere lo stesso numero di record oppure un layer deve contenere un solo record.",outputLayerName:"${layername} - ${destnlayername}",itemDescription:"Feature service generato dall'esecuzione della soluzione Connetti origini a destinazioni.", itemTags:"Risultato analisi, Connetti origini a destinazioni, ${layername}, ${destnlayername}",itemSnippet:"Feature service Analisi generato da Connetti origini a destinazioni",analysisLayerLabel:"Scegli il layer di punti che rappresenta le posizioni di origine:"},planRoutesTool:{toolDefine:"Itinerario per fermate veicoli in \x3cb\x3e${layername}\x3c/b\x3e",timeSpentLabel:"Durata singola fermata",defineRoutesLabel:"Definisci itinerari",startRoutesLabel:"Inizio itinerari",endRoutesLabel:"Fine itinerari", routes:"Itinerari",stops:"Fermate",numRoutes:"Numero massimo di veicoli per itinerario",maxPtsRoute:"Numero massimo di fermate per veicolo",limitMaxTime:"Limita la durata totale dell'itinerario per veicolo",returnToStart:"Torna all'inizio",specifyStartTime:"Ora di inizio per tutti gli itinerari",createStartLoc:"Aggiungi punto alla mappa",createEndLoc:"Aggiungi punto alla mappa",selectStartLoc:"Seleziona posizione di partenza",selectEndLoc:"Seleziona posizione di arrivo",vehicles:"Veicoli",routeId:"Campo ID itinerario", selectRouteId:"Seleziona ID itinerario",stopsLabel:"Il layer contiene ${numStops} fermate.",stopsLabelByExtent:"Nell'estensione mappa corrente sono visualizzate ${numStops} fermate.",outputLayerName:"Itinerari per ${layername}",itemDescription:"Feature service generato dall'esecuzione della soluzione Pianifica itinerari.",itemTags:"Risultato analisi, Pianifica itinerari, ${layername}",itemSnippet:"Feature service Analisi generato da Pianifica itinerari",startEndPtsValidMsg:"Punti iniziali o finali non impostati", travelModeLabel:"Modalit\u00e0 viaggio per itinerari",analysisLayerLabel:"Scegli il layer punto che rappresenta le fermate da visitare"},extractDataTool:{layersToExtract:"Layer da estrarre",studyArea:"Area di studio",outputDataFormat:"Formato dati di output",filegdb:"Geodatabase file (.zip)",shpFile:"Shapefile (.zip)",lyrpkg:"Pacchetto layer (.lpk)",selectFtrs:"Seleziona feature",clipFtrs:"Feature di taglio",sameAsDisplay:"Come visualizzato",sameAsLayer:"Come ${layername}",outputfileName:"Estrai dati ${datetime}", itemDescription:"File generato dall'esecuzione della soluzione Estrai dati.",itemTags:"Risultato analisi, Estrai i dati",itemSnippet:"Elemento del file di analisi generato da Estrai dati",kml:"KML (.kmz o .zip)",csvPoints:"CSV (.csv o .zip) ",linesCSVValidationMsg:"Non \u00e8 possibile estrarre in CSV i layer di linea e di area. Scegliere un formato diverso o deselezionare tutti i layer di linea e di area.",runAnalysisMsg:"I dati sono in fase di estrazione e saranno disponibili in I miei contenuti."}, summarizeWithinTool:{summarizeDefine:"Per feature incluse in \x3cb\x3e${sumWithinLayerName}\x3c/b\x3e",outputLayerName:"Riepiloga ${summaryLayerName} in ${sumWithinLayerName}",groupByLabel:"Scegli campo in base a cui raggruppare (facoltativo)",itemDescription:"Feature service generato dall'esecuzione della soluzione Riepiloga in. Sono stati riepilogati ${summaryLayerName} in ${sumWithinLayerName}",itemTags:"Risultato analisi, Riepiloga in, ${sumWithinLayerName}, ${summaryLayerName}",itemSnippet:"Feature service di analisi generato da Riepiloga in", removeAttrStats:"Rimuovi statistiche attributi",summarizeMetricPoint:"Numero di punti",summarizeMetricLine:"Lunghezza delle linee in",summarizeMetricPoly:"Somma area in",addStatsLabel:"Statistiche attributi",addStats:"Aggiungi statistiche dal layer da riepilogare",sumLabel:"Riepilogo",analysisLayerLabel:"Scegli layer di area per riepilogare altre feature entro i suoi confini"},summarizeNearbyTool:{summarizeDefine:"Riepiloga elementi nelle vicinanze di \x3cb\x3e${sumNearbyLayerName}\x3c/b\x3e",findNearLabel:"Riepiloga le feature pi\u00f9 vicine utilizzando", outputLayerName:"Riepiloga ${summaryLayerName} in ${sumNearbyLayerName}",groupByLabel:"Scegli campo in base a cui raggruppare (facoltativo)",itemDescription:"Feature service generato dall'esecuzione della soluzione Riepiloga nelle vicinanze. Sono stati riepilogati ${sumNearbyLayerName} nelle vicinanze di ${summaryLayerName}",itemTags:"Risultato analisi, Riepiloga nelle vicinanze, ${sumNearbyLayerName}, ${summaryLayerName}",itemSnippet:"Feature service di analisi generato da Riepiloga nelle vicinanze", removeAttrStats:"Rimuovi statistiche attributi",summarizeMetricPoint:"Numero di punti",summarizeMetricLine:"Lunghezza totale",summarizeMetricPoly:"Area totale",addStatsLabel:"Statistiche attributi",addStats:"Aggiungi statistiche dal layer da riepilogare",sumLabel:"Riepilogo",chooseLayer:"Scegliere il layer per il riepilogo",returnBdrycCheckLabel:"Restituisci aree di confine",analysisLayerLabel:"Scegli il layer a partire dal quale verranno misurate le distanze rispetto alle feature nel layer da riepilogare"}, creditEstimator:{analysisLayersLabel:"Layer analisi:",totalRecordsLabel:"Totale record:",creditsAvailLabel:"Crediti disponibili:",creditsReqLabel:"Crediti richiesti:",ntwCreditsReqLabel:"Crediti rete richiesti:",EnrichCreditsLabel:"Crediti aggiunta dati richiesti",maxCreditsLabel:"Numero massimo di crediti richiesti:"},enrichLayerTool:{selectCountryLabel:"Selezionare il Paese",enrichDefine:"Aggiungi dati a \x3cb\x3e${inputLayerName}\x3c/b\x3e",chooseDataCollectionLabel:"Mostra dati disponibili per:", defAreasLabel:"Definisci aree per cui aggiungere dati",outputLayerName:"Dati aggiunti a ${layername}",itemDescription:"Feature service generato in seguito all\u00b4esecuzione della soluzione Aggiungi dati al layer. Sono stati aggiunti dati a ${inputLayerName}",itemTags:"Risultato analisi, Migliora layer, ${inputLayerName}",itemSnippet:"Feature service Analisi generato da Aggiungi dati al layer",straightLineDistance:"Distanza tra linee",selectDataVar:"Seleziona variabili",clickDataVar:"Fare clic su Seleziona variabili per aprire il browser dati e cercare le variabili", selectedVars:"Variabili selezionate",usCountryCode:"Stati Uniti",canadaCountryCode:"Canada",albaniaCountryCode:"Albania",australiaCountryCode:"Australia",austriaCountryCode:"Austria",bahrainCountryCode:"Bahrein",belarusCountryCode:"Bielorussia",bosniaCountryCode:"Bosnia ed Erzegovina",botswanaCountryCode:"Botswana",belgiumCountryCode:"Belgio",brazilCountryCode:"Brasile",bulgariaCountryCode:"Bulgaria",chinaCountryCode:"Cina",colombiaCountryCode:"Colombia",croatiaCountryCode:"Croazia",cyprusCountryCode:"Cipro", czechCountryCode:"Repubblica Ceca",coteCountryCode:"C\u00f4te d'Ivoire (Costa d'Avorio)",denmarkCountryCode:"Danimarca",finlandCountryCode:"Finlandia",franceCountryCode:"Francia",germanyCountryCode:"Germania",ghanaCountryCode:"Ghana",greeceCountryCode:"Grecia",hungaryCountryCode:"Ungheria",icelandCountryCode:"Islanda",indiaCountryCode:"India",indonesiaCountryCode:"Indonesia",irelandCountryCode:"Irlanda",israelCountryCode:"Israele",italyCountryCode:"Italia",japanCountryCode:"Giappone",kazakhstanCountryCode:"Kazakhstan", kenyaCountryCode:"Kenya",latviaCountryCode:"Lettonia",liechtensteinCountryCode:"Liechtenstein",lithuaniaCountryCode:"Lituania",luxembourgCountryCode:"Lussemburgo",malawiCountryCode:"Malawi",malaysiaCountryCode:"Malaysia",maltaCountryCode:"Malta",mauritiusCountryCode:"Mauritius",mexicoCountryCode:"Messico",moldovaCountryCode:"Moldova",montenegroCountryCode:"Montenegro",mozambiqueCountryCode:"Mozambico",namibiaCountryCode:"Namibia",netherlandsCountryCode:"Paesi Bassi",nzCountryCode:"Nuova Zelanda", nigeriaCountryCode:"Nigeria",norwayCountryCode:"Norvegia",peruCountryCode:"Per\u00f9",polandCountryCode:"Polonia",portugalCountryCode:"Portogallo",puertoCountryCode:"Portorico",romaniaCountryCode:"Romania",reunionCountryCode:"Riunione",spainCountryCode:"Spagna",switzerlandCountryCode:"Svizzera",swedenCountryCode:"Svezia",turkeyCountryCode:"Turchia",ukCountryCode:"Regno Unito",zmCountryCode:"Zambia",ugandaCountryCode:"Uganda",mkCountryCode:"Ex Repubblica Jugoslava di Macedonia",uaeCountryCode:"Emirati Arabi Uniti", thCountryCode:"Thailandia",twCountryCode:"Taiwan",szCountryCode:"Swaziland",krCountryCode:"Corea del Sud",siCountryCode:"Slovenia",sgCountryCode:"Singapore",rsCountryCode:"Serbia",saCountryCode:"Arabia Saudita",tzCountryCode:"Tanzania",ukrCountryCode:"Ucraina",globalCode:"Globale",russiaCountryCode:"Russia",algCountryCode:"Algeria",andCountryCode:"Andorra",argCountryCode:"Argentina",azCountryCode:"Azerbaigian",baCountryCode:"Bangladesh",chCountryCode:"Cile",coCountryCode:"Costa Rica",egCountryCode:"Egitto", elCountryCode:"El Salvador",eeCountryCode:"Estonia",grCountryCode:"Georgia",gtCountryCode:"Guatemala",hoCountryCode:"Honduras",joCountryCode:"Giordania",kwCountryCode:"Kuwait",kzCountryCode:"Kirghizistan",lbCountryCode:"Libano",leCountryCode:"Lesotho",mgCountryCode:"Mongolia",moCountryCode:"Marocco",niCountryCode:"Nicaragua",omCountryCode:"Oman",pkCountryCode:"Pakistan",phCountryCode:"Filippine",qaCountryCode:"Qatar",slCountryCode:"Slovacchia",safCountryCode:"Sud Africa",sriCountryCode:"Sri Lanka", sdCountryCode:"Sudan",tnCountryCode:"Tunisia",ugCountryCode:"Uruguay",syCountryCode:"Siria",vzCountryCode:"Venezuela",vtCountryCode:"Vietnam",keyGlobalFacts:"Dati principali a livello globale",age:"Et\u00e0",husByOccupancy:"Unit\u00e0 abitative per occupazione",householdsByIncome:"Nuclei familiari per reddito",keyUSFacts:"Dati principali USA",policy:"Politica",raceAndEthnicity:"Razza ed etnicit\u00e0",wealth:"Ricchezza",keyCanFacts:"Dati principali Canada",aTSpend:"Austria - Spese",aTFacts:"Austria - Dati", bESpend:"Belgio - Spese",bEFacts:"Belgio - Dati",bRSpend:"Brasile - Spese",bRFacts:"Brasile - Dati",dKSpend:"Danimarca - Spese",dKFacts:"Danimarca - Dati",fISpend:"Finlandia - Spese",fIFacts:"Finlandia - Dati",fRSpend:"Francia - Spese",fRFacts:"Francia - Dati",dESpend:"Germania - Spese",dEFacts:"Germania - Dati",gRSpend:"Grecia - Spese",gRFacts:"Grecia - Dati",iEFacts:"Irlanda - Dati",iESpend:"Irlanda - Spese",iNFacts:"India - Dati",iNSpend:"India - Spese",iTFacts:"Italia - Dati",iTSpend:"Italia - Spese", keyWEFacts:"Europa Occidentale - Dati principali",keyWESpend:"Europa Occidentale - Spese principali",jPFacts:"Giappone - Dati",jPSpend:"Giappone - Spese",lIFacts:"Liechtenstein - Dati",lISpend:"Liechtenstein - Spese",lUFacts:"Lussemburgo - Dati",lUSpend:"Lussemburgo - Spese",nLFacts:"Paesi Bassi - Dati",nLSpend:"Paesi Bassi - Spese",nOFacts:"Norvegia - Dati",nOSpend:"Norvegia - Spese",pTFacts:"Portogallo - Dati",pTSpend:"Portogallo - Spese",eSSpend:"Spagna - Spese",eSFacts:"Spagna - Dati",sEFacts:"Svezia - Dati", sESpend:"Svezia - Spese",cHFacts:"Svizzera - Dati",cHSpend:"Svizzera - Spese",tRFacts:"Turchia - Dati",tRSpend:"Turchia - Spese",gBFacts:"Regno Unito - Dati",gBSpend:"Regno Unito - Spese",tapestry:"Tapestry",infrastructure:"Infrastruttura",landCover:"Copertura del suolo",landscapeFacts:"Paesaggio - Dati",publicLands:"Terreni pubblici",soils:"Suoli",waterWetlands:"Paludi con acqua",rUFacts:"Russia - Dati",rUSpend:"Russia - Spese",analysisLayerLabel:"Scegli il layer a cui aggiungere nuovi dati",returnBoundingAreas:"Restituisci risultato come aree di confine"}, dissolveBoundaries:{dissolveBoundariesDefine:"Dissolvi \x3cb\x3e${layername}\x3c/b\x3e",chooseDissolveLabel:"Scegli metodo di dissolvenza",overlappingAreasLabel:"Aree sovrapposte o adiacenti",sameAttributeAreasLabel:"Aree con lo stesso valore di campo",summarizeLabel:"Aggiungi statistiche (facoltativo)",itemDescription:"Feature service generato dall\u00b4esecuzione della soluzione Dissolvi confini.",itemTags:"Risultato analisi, Dissolvi confini, ${layername}",itemSnippet:"Feature service Analisi generato da Dissolvi confini", resultLabel:"Nome layer risultati",outputLayerName:"Dissolvi ${layername}",analysisLayerLabel:"Scegli il layer di area i cui confini verranno dissolti"},FindNearestTool:{summarizeDefine:"Per ogni posizione in \x3cb\x3e${sumNearbyLayerName}\x3c/b\x3e, trovare le posizioni pi\u00f9 vicine.",findNearLabel:"Trova le posizioni pi\u00f9 vicine misurando",outputLayerName:"${layer} pi\u00f9 vicino a ${sumNearbyLayerName}",groupByLabel:"Scegli campo in base a cui raggruppare (facoltativo)",itemDescription:"Feature service generato dall'esecuzione della soluzione Trova pi\u00f9 vicine. Pi\u00f9 vicino ${sumNearbyLayerName}", itemTags:"Risultato analisi, Trova pi\u00f9 vicine, ${sumNearbyLayerName}, ${summaryLayerName}",itemSnippet:"Feature service Analisi generato da Trova pi\u00f9 vicine",removeAttrStats:"Rimuovi statistiche attributi",forEachLocationLabel:"Per ogni posizione nel layer di input",findNearestLabel:"Limita il numero delle posizioni pi\u00f9 vicine a:",limitSearchRangeCheck:"Limita l'intervallo di ricerca a",addStats:"Per ogni posizione in \x3cb\x3e${summaryLayerName}\x3c/b\x3e",chooseLayer:"Selezionare un layer", findLocationsIn:"Trova le posizioni pi\u00f9 vicine in:",outputLayersLabel:"Nomi layer risultati",straightLineDistance:"Distanza tra linee",resultLabel1:"Layer delle posizioni pi\u00f9 vicine",resultLabel2:"Layer linee di connessione",outputConnectingLayerName:"${layer} pi\u00f9 vicino a ${sumNearbyLayerName} (Linee)",chooseLayerInfoLabel:"Per abilitare le opzioni Distanza di guida e Tempo di guida, entrambi i layer di input devono contenere punti",analysisLayerLabel:"Scegliere il layer da cui trovare le localit\u00e0 pi\u00f9 vicine:"}, mergeLayers:{mergeLayersDefine:"Unisci \x3cb\x3e${layername}\x3c/b\x3e con",outputLayerName:"Unisci ${layername} ${mergelayername}",chooseMergeLayer:"Scegli il layer da unire",mergeFieldsLabel:"Modifica campi di unione (facoltativo)",itemDescription:"Feature service generato dall'esecuzione della soluzione Unisci layer.",itemTags:"Risultato analisi, Unisci layer, ${layername}",itemSnippet:"Feature service Analisi generato da Unisci layer",resultLabel:"Nome layer risultati",rename:"Rinomina",remove:"Rimuovi", match:"Confronta",operation:"Operazione",fieldTypeMatchValidationMsg:"I campi da associare devono essere dello stesso tipo. La trasformazione dei tipi \u00e8 supportata (ad esempio, da doppio a numero intero, da numero intero a stringa) eccetto la trasformazione da stringa a valore numerico.",analysisLayerLabel:"Scegliere il layer"},findExistingLocations:{findExpLabel:"Crea un'interrogazione per trovare feature",outputLayerName:"Trova posizioni in ${analysisLayerName}",itemDescription:"Feature service generato dall'esecuzione delle soluzioni Trova localit\u00e0 esistenti per ${analysisLayerName}.", itemTags:"Risultato analisi, Trova localit\u00e0 esistenti, ${analysisLayerName}",itemSnippet:"Feature service Analisi generato da Trova localit\u00e0 esistenti",analysisLayerLabel:"Scegli il layer contenente le feature da trovare utilizzando interrogazioni sugli attributi e sui dati spaziali"},deriveNewLocations:{findExpLabel:"Deriva nuove localit\u00e0 corrispondenti alle seguenti espressioni",outputLayerName:"Nuove localit\u00e0",itemDescription:"Feature service generato dall'esecuzione di soluzioni Deriva nuove localit\u00e0.", itemTags:"Risultato analisi, Deriva nuove localit\u00e0, ${analysisLayerName}",itemSnippet:"Feature service Analisi generato da Trova localit\u00e0 esistenti"},findSimilarLocations:{toolDefine:"Trova localit\u00e0 simili a: \x3cb\x3e${layername}\x3c/b\x3e",labelOneText:"\u00c8 possibile utilizzare tutte le localit\u00e0 o effettuare una selezione",labelTwoText:"Cerca localit\u00e0 simili in",labelThreeText:"Basa somiglianza su",labelFourText:"Mostra",outputLayerName:"${analysisLayerName} pi\u00f9 simile", selectTargetFtrs:"Selezionare una o pi\u00f9 feature di destinazione",useAllFtrs:"Utilizza tutte le feature",itemDescription:"Feature service generato dall'esecuzione delle soluzioni Trova localit\u00e0 simili per ${analysisLayerName}.",itemTags:"Risultato analisi, Trova localit\u00e0 simili, ${analysisLayerName}",itemSnippet:"Feature service Analisi generato da Trova localit\u00e0 simili",allResults:"tutte le localit\u00e0 da quella pi\u00f9 simile a quella meno simile",justShowTop:"i primi",selectSearchLayer:"Selezionare il layer di ricerca", query:"Interrogazione",noFieldMatchMsg:"Il layer di ricerca e quello di input non hanno campi in comune.",reqSelectionMsg:"Per selezionare le feature da abbinare, \u00e8 possibile effettuare una selezione interattiva oppure creare un'interrogazione.",selectedFeaturesLabel:"${total} feature selezionata/e",analysisLayerLabel:"Scegli il layer contenente le posizioni di riferimento"},expressionGrid:{addExpr:"Aggiungi espressione",expression:"Espressione",editExpr:"Modifica espressione",viewText:"Visualizza testo", viewGrid:"Visualizza griglia",addExprDescription:"Fare clic su Aggiungi espressione per iniziare a creare l'interrogazione.",duplicateExpression:"Espressione gi\u00e0 esistente"},expressionForm:{where:"dove (interrogazione attributi)",whereLabel:"dove",intersects:"interseca",notIntersects:"non interseca",withinDistance:"entro una distanza di",notWithinDistance:"non entro una distanza di",contains:"contiene completamente",notContains:"non contiene completamente",completelyContains:"contiene completamente", notCompletelyContains:"non contiene completamente",within:"completamente all'interno di",notWithin:"non completamente all'interno",completelyWithin:"completamente all'interno di",notCompletelyWithin:"non completamente all'interno",identical:"sono identiche a",notIdentical:"non sono identiche a",touches:"tocca",notTouches:"non tocca",crossesOutline:"sono attraversate dai confini di",notCrossesOutline:"non sono attraversate dai confini di",from:"da",inValidAttributeFilterMessage:"Il layer ${layername} non contiene attributi utilizzabili in un'interrogazione attributi."}, interpolatePointsTool:{toolDefine:"Interpolazione valori da \x3cb\x3e${layername}\x3c/b\x3e",outputLayerName:"Predizione ${layername}",interpolationMethod:"Metodo di interpolazione",optimizeFor:"Ottimizza per",selectAttributesLabel:"Scegliere il campo per l'interpolazione",classifyLabel:"Classifica per",classesCountLabel:"Numero di classi",equalInterval:"Intervallo uguale",manual:"Manuale",quantile:"Area Equivalente",geometricInterval:"Intervallo geometrico",outputPredictionErrors:"Visualizza errori di predizione", interpolateWithin:"Ritaglia output in",predictLocLabel:"Esegui predizione in queste posizioni",choosePointLayer:"Scegli layer puntuale",pointlayerName:"Traccia punti predizione",classBreakValues:"Valori di interruzione classe",defaultBoundingOption:"Scegli area di studio",classBreaksHelp:"Immettere i valori di interruzione separati da spazi: (10 20 30)",itemDescription:"Feature service generato dall'esecuzione della soluzione Interpolazione punti.",itemTags:"Risultato analisi, Interpolazione punti, ${layername}, ${fieldname}", itemSnippet:"Feature service Analisi generato da Interpolazione punti",speed:"Velocit\u00e0",accuracy:"Precisione",analysisLayerLabel:"Scegli il layer punto contenente posizioni con valori noti"},calculateDensityTool:{toolDefine:"Calcola valori di densit\u00e0 da \x3cb\x3e${layername}\x3c/b\x3e",selectAttributesLabel:"Usa un campo conteggio (facoltativo)",outputAerealUnits:"Unit\u00e0 area di output",itemDescription:"Feature service generato dall'esecuzione della soluzione Calcolo densit\u00e0.", itemTags:"Risultato analisi, Calcolo densit\u00e0, ${layername}, ${fieldname}",itemSnippet:"Feature service Analisi generato da Calcolo densit\u00e0",outputLayerName:"Densit\u00e0 ${layername}",searchDistance:"Distanza di ricerca",naturalBreaks:"Natural breaks",standardDeviation:"Deviazione standard",chooseCountField:"Nessun campo conteggio",analysisLayerLabel:"Scegli il layer di punti o di linea in base al quale calcolare la densit\u00e0"},traceDownstreamTool:{toolDefine:"Traccia a valle da \x3cb\x3e${layername}\x3c/b\x3e", outputLayerName:"Traccia ${layername}",choosePointLayer:"Scegli layer puntuale",pointlayerName:"Punti di input tracciati",defaultBoundingOption:"Scegli area di studio",itemDescription:"Feature service generato dalla soluzione Traccia a valle.",itemTags:"Risultato analisi, Traccia a valle, ${layername}",itemSnippet:"Feature service Analisi generato da Traccia a valle",clipOutputToLabel:"Ritaglia output in",traceOptionsLabel:"Impostazioni traccia a valle (facoltativo)",splitTraceLabel:"Suddividi traccia in segmenti lineari", maxTraceLabel:"Distanza massima della traccia",analysisLayerLabel:"Feature puntuali utilizzate come localit\u00e0 di partenza per ogni tracciamento a valle"},createWatershedTool:{toolDefine:"Crea spartiacque da \x3cb\x3e${layername}\x3c/b\x3e",outputLayerName:"Spartiacque ${layername}",choosePointLayer:"Scegli layer puntuale",pointlayerName:"Punti di input tracciati",defaultBoundingOption:"Scegli area di studio",itemDescription:"Feature service generato dall'esecuzione della soluzione Crea spartiacque.", itemTags:"Risultato analisi, Crea spartiacque, ${layername}",itemSnippet:"Feature service Analisi generato da Crea spartiacque",searchDistanceLabel:"Ricerca distanza per il drenaggio pi\u00f9 vicino (facoltativo)",analysisLayerLabel:"Feature puntuali da utilizzare per calcolare gli spartiacque"},chooseBestFacilitiesTool:{goalLabel:"Obiettivo",facTodemLabel:"Struttura a richiesta",demTofacLabel:"Richiesta a struttura",demandLayer:"Layer posizioni di richiesta",demandLabel:"Il layer dispone di ${numberOf} posizioni di richiesta.", demandExtentLabel:"L'estensione mappa corrente mostra ${numberOf} posizioni richiesta.",facilitiesNumLabel:"Il layer dispone di ${numberOf} strutture obbligatorie.",facilitiesExtentLabel:"L'estensione mappa corrente mostra ${numberOf} strutture obbligatorie.",candidateNumLabel:"Il layer dispone di ${numberOf} strutture candidate.",candidateExtentLabel:"L'estensione mappa corrente mostra ${numberOf} strutture candidate.",demandAmountLabel:"Numero di richieste in ogni posizione di richiesta:",constLabel:"Constante", maxTravelLabel:"Intervallo di spostamento massimo:",unlimitedLabel:"Senza limitazioni",reqdFacilities:"Layer strutture obbligatorie",candFacilities:"Layer strutture candidate",capacityLabel:"Capacit\u00e0",minimizeImpedance:"Riduci viaggio",allocate:"Assegna a strutture esistenti",maximizeCoverage:"Ottimizza coverage",maximizeCapacitatedCoverage:"Ottimizza copertura con capacit\u00e0",percentCoverage:"Copri una percentuale di richiesta",numberCandidates:"Numero di candidati da scegliere:",travelDirection:"Direzione di viaggio:", reqFacLayerLabel:"Layer puntale strutture obbligatorie:",outputLayerName:"Strutture assegnate per ${demandLayer}",delieveries:"Consegne",demand:"Richiesta",pickups:"Selezioni",weight:"Peso",demandPercentCover:"Percentuale di richieste da coprire:",selectGoal:"Selezionare l'opzione pi\u00f9 adatta all'obiettivo",allocateDesc:"Assegnare posizioni di richiesta a strutture esistenti in base all'approvvigionamento presso la struttura e alla quantit\u00e0 di richiesta dall'area circostante.",minimizeImpedanceDesc:"Individuare strutture tali che il tempo o la distanza di viaggio complessiva tra le posizioni di richiesta e le strutture sia ridotto.", maximizeCoverageDesc:"Individuare strutture tali che venga allocata la quantit\u00e0 massima di richiesta, con tutta la richiesta da ogni posizione di richiesta allocata alla singola struttura pi\u00f9 vicina.",maximizeCapacitatedCoverageDesc:"Individuare strutture tali che venga allocata la quantit\u00e0 massima di richiesta, con tutta la richiesta da ogni posizione di richiesta allocata alla singola struttura pi\u00f9 vicina senza superare la capacit\u00e0 della struttura.",percentCoverageDesc:"Individuare il numero minimo di strutture che sono richieste per coprire la percentuale di richiesta specificata.", candidateLayerLabel:"Layer puntale strutture candidate:",noneReqOption:"Non esiste alcuna struttura che deve sempre essere utilizzata"},createViewshedTool:{toolDefine:"Crea aree visibili da \x3cb\x3e${layername}\x3c/b\x3e",outputLayerName:"Aree visibili ${layername}",itemDescription:"Feature service generato dall'esecuzione della soluzione Crea campo di vista.",itemTags:"Risultato analisi, Crea campo di vista, ${layername}",itemSnippet:"Feature service Analisi generato da Crea campo di vista",maxDistanceLabel:"Distanza di visualizzazione massima", observerHghtLabel:"Altezza delle posizioni dell'osservatore",targetHghtLabel:"Altezza di altri oggetti al suolo",viewshedOptionlabel:"Impostazioni visibilit\u00e0 (facoltativo)",maxDistanceValidMsg:"La distanza di visualizzazione massima non pu\u00f2 essere maggiore di ${limit} ${units}.",maxdistanceInValidMsg:"Sono consentiti solo valori interi",analysisLayerLabel:"Feature puntuali che rappresentano le posizioni dell'osservatore",pointlayerName:"Punti di input tracciati"},calculateSlopeTool:{toolDefine:"Calcola pendenza da \x3cb\x3e${layername}\x3c/b\x3e", outputLayerName:"Pendenza ${layername}",defaultBoundingOption:"Scegli area di studio",itemDescription:"Image service generato dall'esecuzione della soluzione Calcola pendenza.",itemTags:"Risultato analisi, Calcola pendenza, ${layername}",itemSnippet:"Image service di analisi generato da Calcola pendenza",zFactorInputLabel:"Specificare fattore di scala per elevazione",analysisLayerLabel:"Scegliere dati di input per calcolare la pendenza"},deriveAspectTool:{toolDefine:"Deriva aspetto da \x3cb\x3e${layername}\x3c/b\x3e", outputLayerName:"Aspetto di ${layername}",defaultBoundingOption:"Scegli area di studio",itemDescription:"Image service generato dall'esecuzione della soluzione Deriva aspetto.",itemTags:"Risultato analisi, Identifica aspetto, ${layername}",itemSnippet:"Image service di analisi generato da Deriva aspetto",analysisLayerLabel:"Scegliere dati di input per derivare l'aspetto"},monitorVegetationTool:{monitorVegetation:"Monitora vegetazione",toolDefine:"Monitora vegetazione in \x3cb\x3e${layername}\x3c/b\x3e", outputLayerName:"Monitora vegetazione di ${layername}",indexType:"Scegliere metodo per monitorare vegetazione",bandIndexes:"Specificare indici di banda NIR e RED",nirBandIndex:"Indice di banda NIR",redBandIndex:"Indice di banda RED",greenVegetativeCover:"Quantit\u00e0 di copertura di vegetazione verde",slopeOfSoilLine:"Pendenza della linea del terreno",gradientOfSoilLine:"Gradiente della linea del terreno",adjustmentFactor:"Fattore di regolazione",NDVI:"Indice di vegetazione della differenza normalizzata", SAVI:"Indice di vegetazione in funzione del suolo",TSAVI:"Indice di vegetazione in funzione del suolo trasformato",GEMI:"Indice di monitoraggio ambientale globale",PVI:"Indice di vegetazione perpendicolare",MSAVI:"Indice di vegetazione in funzione del suolo modificato",GVITM:"Indice di vegetazione verde - Landsat TM",Sultan:"Formula di Sultan",Options:"Rimappa valori di pixel su nuovi valori",minimum:"Minima",maximum:"Massima",output:"Output",addItemLabel:"Aggiungi una voce",removeItemLabel:"Rimuovi voce selezionata", analysisLayerLabel:"Seleziona i dati di input",itemDescription:"Image service generato dall'esecuzione della soluzione Monitora vegetazione.",itemTags:"Risultato analisi, Monitora vegetazione, ${layername}",itemSnippet:"Image service di analisi generato da Monitora vegetazione"},remapValuesTool:{toolDefine:"Rimappa valori di pixel in ${layername}",outputLayerName:"Raster mappato di nuovo da ${layername}",remapList:"Rimappa valori di pixel su nuovi valori",analysisLayerLabel:"Scegliere dati di input per rimappare i valori", itemDescription:"Raster generato dall'esecuzione della funzione Rimappa",itemTags:"Risultato dell'analisi raster, Rimappa",itemSnippet:"Image service di analisi generato da Rimappa",clipping:"Specifica l'area da rimappare",add:"Aggiungi",remove:"Rimuovi",viewText:"Visualizza"},extractRasterTool:{toolDefine:"Estrai dati da ${layername}",outputLayerName:"Dati estratti da ${layername}",clipping:"Specifica geometria di ritaglio",clippingInside:"Dati all'interno della geometria",clippingOutside:"Dati all'esterno della geometria", clippingExtent:"Utilizza estensione corrente",clippingGeometry:"Scegli area di studio",analysisLayerLabel:"Scegliere dati di input da estrarre",itemDescription:"Raster generato dall'esecuzione della funzione Estrai dati raster.",itemTags:"Risultato analisi raster, Estrai dati raster",itemSnippet:"Image service di analisi generato da Estrai dati raster"},reconstructTracksTool:{inputFeatures:"Scegliere le feature da cui ricostruire le tracce",trackField:"Scegliere i campi utilizzati per identificare le tracce", bufField:"Creare un'espressione con cui eseguire il buffer di feature di input (facoltativo)",durSplit:"Selezionare un'ora in cui suddividere le tracce (facoltativo)",methodLabel:"Scegliere il metodo utilizzato per ricostruire le tracce",itemDescription:"Feature service generato in seguito all'esecuzione della soluzione Ricostruisci tracce per ${inputLayerName}.",itemTags:"Risultato analisi, Ricostruisci tracce, ${inputLayerName}",itemSnippet:"Feature service di analisi generato da Ricostruisci tracce", outputLayerName:"Ricostruisci tracce per ${inputLayerName}"},analysisMsgCodes:{SS_84493:"\u00c8 presente una posizione di deviazione; non \u00e8 stata utilizzata per calcolare il tipo di aggregazione ${AggregationType}.",SS_84492:"L'area totale dello studio \u00e8 ${Area}.",SS_84491:"Sono presenti ${NumFeatures} aree di aggregazione di input valide.",SS_84490:"Con il processo di aggregazione sono state ottenute ${AggNumFeatures} aree ponderate.",SS_84489:"L'analisi \u00e8 stata eseguita su tutte le aree di aggregazione.", SS_84485:"Sono presenti ${NumFeatures} feature di input valide.",SS_84477:"Le feature di output blu rappresentano i cold spot con cluster di ${FieldName} inferiore.",SS_84476:"Le feature di output rosse rappresentano gli hot spot con cluster di ${FieldName}superiore.",SS_84471:"Output",SS_84470:"Sulla base di una correzione FDR ${NumSignificant} feature di output sono statisticamente significative per test multipli e dipendenza spaziale.",SS_84466:"Analisi hot spot",SS_84465:"La banda di distanza fissa ottimale \u00e8 stata basata su una distanza standard delle feature dalla media geometrica: ${DistanceInfo}.", SS_84464:"La banda di distanza fissa ottimale \u00e8 stata basata sulla distanza media da ${NumNeighs} vicini pi\u00f9 prossimi: ${DistanceInfo}.",SS_84461:"La banda di distanza fissa ottimale selezionata \u00e8 stata basata sul clustering di picco trovato a ${DistanceInfo}.",SS_84459:"Scala di analisi",SS_84458:"L\u00b4analisi \u00e8 stata basata sul numero di punti in ogni cella del poligono.",SS_84457:"I punti sono stati aggregati alle celle del poligono a griglia comprese nelle aree di confine specificate.", SS_84453:"L'analisi \u00e8 stata eseguita su tutte le celle del poligono a griglia comprese nel layer delle aree di confine.",SS_84452:"L'analisi \u00e8 stata eseguita su tutte le celle del poligono a griglia contenenti almeno un punto.",SS_84451:"L'analisi \u00e8 stata basata sul numero di punti in ogni cella del poligono a griglia.",SS_84450:"Le dimensioni della cella poligonale erano ${SnapInfo}.",SS_84449:"\u00c8 stata creata una mesh di poligoni a griglia per l'aggregazione dei punti.",SS_84446:"Propriet\u00e0 di ${VarName}:", SS_84444:"Aggregazione incidenti",SS_84437:"Non esistono deviazioni di posizione.",SS_84434:"Sono presenti ${NumOutliers} deviazioni di posizione; non sono state utilizzate per calcolare il tipo di aggregazione ${AggregationType}.",SS_84428:"Valutazione dati iniziale.",SS_84271_0:"Minimo",SS_84272_0:"Max",SS_84261_0:"Media",SS_84262_0:"Dev.Std.",SS_00002:"Nel report seguente \u00e8 descritto il flusso di lavoro utilizzato per ottimizzare il risultato di Trova hot spot:",AO_100001:"Aggrega punti non riuscito.", AO_100002:"Specificare punti come tipo di geometria del layer punti.",AO_100003:"Specificare poligoni come tipo di geometria del layer poligoni.",AO_100004:"Il campo ${fieldName} specificato per i campi di riepilogo non esiste.",AO_100005:"Il campo ${fieldName} specificato per i campi di riepilogo non \u00e8 numerico.",AO_100006:"Il tipo di riepilogo ${summary} specificato per il campo ${fieldName} non \u00e8 valido.",AO_100007:"Trova hot spot non riuscito.",AO_100008:"Specificare poligoni come tipo di geometria del layer poligoni di contorno.", AO_100009:"Specificare punti o poligoni come tipo di geometria del layer analisi.",AO_100010:"Specificare poligoni come tipo di geometria del layer poligoni di aggregazione.",AO_100011:"\u00c8 necessario specificare un campo di analisi per il layer analisi del poligono.",AO_100012:"Crea buffer non riuscito.",AO_100013:"Sovrapponi layer non riuscito.",AO_100014:"Riepiloga entro non riuscito.",AO_100015:"Specificare punto, linea o poligoni come tipo di geometria del valore di input del layer di riepilogo.", AO_100016:"Specificare punto o linea come tipo di geometria del valore di input del layer di riepilogo.",AO_100017:"Specificare punto come tipo di geometria del valore di input del layer di riepilogo.",AO_100018:"Unit\u00e0 di somma ${sumUnits} non applicabili per il tipo di forma ${shapeType}.",AO_100019:"Specificare almeno uno dei parametri tra Riepiloga forma e Campi di riepilogo.",AO_468:"I tipi di forma dell\u00b4input non sono uguali.",AO_1156:"Valore incompatibile con il tipo di campo.",AO_800:"Il valore non \u00e8 membro di SUM | MEAN | MIN | MAX | RANGE | STD | COUNT | FIRST | LAST.", AO_728:"Il campo di analisi ${fieldName} specificato non esiste nel layer di analisi.",AO_12:"Campo da aggiungere gi\u00e0 esistente.",AO_539:"Espressione non valida.",AO_1115:"La propriet\u00e0 descrizione layer deve essere impostata per ${layerName}.",AO_366:"Tipo di geometria non valido.",AO_641:"Per calcolare i risultati con questo strumento, sono necessarie almeno ${numFeatures} feature.",AO_906:"Varianza zero: tutti i valori per il campo di input sono gli stessi.",AO_1533:"Impossibile calcolare hot e cold spot per i dati forniti. Se appropriato, provare a specificare un campo di analisi.", AO_1534:"Impossibile calcolare gli hot spot e i cold spot se il numero di punti in ciascuna area poligono \u00e8 uguale. Provare con aree poligono diverse o con altre opzioni di analisi.",AO_1535:"Per l'opzione di analisi selezionata, sono necessarie almeno ${minNumFeatures} aree di aggregazione.",AO_1536:"Per l'opzione di analisi selezionata, sono necessari almeno ${minNumIncidents} punti per calcolare gli hot spot e i cold spot.",AO_1570:"Per l'opzione di analisi selezionata, \u00e8 necessario che almeno ${minNumIncidents} punti si trovino all'interno delle aree del poligono di contorno.", AO_1571:"Per l'opzione di analisi selezionata, sono necessari almeno ${minNumFeatures} feature con dati validi nel campo di analisi per consentire il calcolo di hot spot e cold spot.\t",AO_1572:"Nelle posizioni dei punti, la variazione non \u00e8 sufficiente per calcolare hot e cold spot. Punti coincidenti, ad esempio, riducono la variazione spaziale. \u00c8 possibile provare a fornire un'area di confine, aree di aggregazione (almeno 30) o un campo di analisi.",AO_1573:"Variazione insufficiente tra i punti all'interno delle aree dei poligoni di contorno. \u00c8 possibile provare a fornire confini pi\u00f9 ampi.", AO_1574:"Per l'opzione di analisi selezionata, \u00e8 necessario che almeno ${minNumIncidents} punti si trovino all'interno dei poligoni di aggregazione.",AO_1575:"\u00c8 probabile che tutti i valori del campo di analisi siano identici. Quando non vi \u00e8 alcuna variazione nel campo che si sta analizzando, non \u00e8 possibile calcolare hot e cold spot.",AO_84426:"\u00c8 necessario specificare i poligoni per aggregare gli incidenti in valori numerici ai fini di questo metodo di aggregazione dei dati sugli incidenti.", AO_26:"La distanza di buffer \u00e8 zero.",AO_109:"La distanza di buffer non pu\u00f2 essere negativa per linee e punti.",AO_385:"L\u00b4opzione LINEA non \u00e8 valida con feature punto.",AO_438:"Overlay non poligono.",AO_100020:"Aggiungi dati al layer non riuscito.",AO_100021:"Il tipo di geometria del layer di input deve essere punto, linea o poligono.",AO_100022:"Unit\u00e0 ${units} non supportate per Tipo di buffer ${bufferType}.",AO_100023:"Impossibile aggiungere dati al layer per l'input di riferimento spaziale ${spref}.", AO_100024:"Il numero feature in ${inputLayer} \u00e8 zero.",AO_100025:"Riepiloga nelle vicinanze non riuscito.",AO_100026:"Estrai dati non riuscito.",AO_100027:"Dissolvi confini non riuscito.",AO_100028:"Crea aree tempo di guida non riuscito.",AO_100029:"Unisci layer non riuscito.",AO_100030:"Trova pi\u00f9 vicine non riuscito.",AO_100031:"Il numero delle posizioni pi\u00f9 vicine da cercare non deve essere maggiore di 100.",AO_100032:"Il numero delle feature in ${analysisLayer} \u00e8 zero.",AO_100033:"Il numero delle feature in ${nearLayer} \u00e8 zero.", AO_100034:"Il numero delle feature in ${analysisLayer} non pu\u00f2 essere maggiore di 1000.",AO_100035:"Il numero delle feature in ${nearLayer} non pu\u00f2 essere maggiore di 1000.",AO_100036:"Se si utilizza ${measurementType} come tipo di misurazione, il layer ${analysisLayer} deve disporre di un tipo di geometria di punto.",AO_100037:"Se si utilizza ${measurementType} come tipo di misurazione, il layer ${nearLayer} deve disporre di un tipo di geometria di punto.",AO_100038:"Il limite della ricerca non pu\u00f2 essere inferiore a zero.", AO_100039:"Il ${inputLayer} deve disporre di un tipo di geometria di punto.",AO_100040:"Il numero di feature in ${inputLayer} non pu\u00f2 essere maggiore di ${max}.",AO_100041:"Il parametro del tipo di buffer \u00e8 supportato soltanto per layer che contengono punti o linee.",AO_100042:"Il tipo di geometria ${shapeType} del layer vicino non \u00e8 supportato per il tipo vicino ${nearType}",AO_100043:"Le unit\u00e0 ${units} non sono supportate dal tipo vicino ${nearType}.",AO_100044:"Il valore della distanza deve essere maggiore di 0", AO_100045:"Se \u00e8 specificato il Tipo di buffer, \u00e8 necessario fornire i valori relativi alla distanza e alle unit\u00e0",AO_100046:"Impossibile accedere al server GeoEnrichment.",AO_100047:"La funzione di miglioramento potrebbe non essere disponibile per alcune feature.",AO_100048:"Il layer di input ${inputLayer} contiene geometria multipunto ed \u00e8 stato convertito in geometria a punti singoli.",AO_100049:"Nell'estensione di elaborazione non esistono feature per i layer di input.",AO_100050:"Nel layer di input non esistono campi per l'estrazione dati.", AO_100051:"Nell'estensione di elaborazione non esistono feature per i layer di input e nessun layer di input include campi per l'estrazione dati. ",AO_100052:"Il nome di campo ${fieldName} non esiste in ${paramName}.",AO_100053:"Chiavi obbligatorie ${missingKeys} risultano mancanti nell'espressione di attributi ${expression}.",AO_100054:"Chiavi obbligatorie ${missingKeys} risultano mancanti nell'espressione di relazione spaziale ${expression}.",AO_100055:"Espressione non valida; sintassi JSON errata.", AO_100056:"Indice di layer non valido nell'espressione ${expression}.",AO_100057:"L'indice di layer \u00e8 superiore al numero di layer di input nell'espressione ${expression}.",AO_100058:"La relazione spaziale ${spatialRel} non supporta i tipi di geometria ${lyrGeomType}/${selLyrGeomType} per layer/selectingLayer nell'espressione ${expression}.",AO_100059:"Relazione spaziale non valida {spatialRel} nell'espressione ${expression}.",AO_100060:"Espressione di interrogazione non riuscita nell'espressione ${expression}.", AO_100061:"FindExistingLocations non riuscito.",AO_100062:"Distanza e/o unit\u00e0 non valide nell'espressione ${expression}",AO_100063:"PlanRoutes non riuscito.",AO_100064:"Il numero delle feature in ${stopsLayer} \u00e8 zero.",AO_100065:"Il numero delle feature in ${startLayer} \u00e8 zero.",AO_100066:"Il numero massimo di veicoli per itinerario non pu\u00f2 essere minore di zero e maggiore di ${max}.",AO_100067:"Il numero massimo di fermate per veicolo non pu\u00f2 essere minore di zero e maggiore di ${max}.", AO_100068:"Il numero di feature in ${stopsLayer} non pu\u00f2 essere maggiore di ${max}.",AO_100069:"Il numero di feature in ${startLayer} non pu\u00f2 essere maggiore di ${max}.",AO_100070:"Il numero di feature in ${endLayer} non pu\u00f2 essere maggiore di ${max}.",AO_100071:"Il layer ${stopsLayer} deve disporre di un tipo di geometria di punto.",AO_100072:"Il layer ${startLayer} deve disporre di una geometria di tipo punto.",AO_100073:"Il layer ${endLayer} deve disporre di una geometria di tipo punto.", AO_100074:"La durata di ciascuna fermata non pu\u00f2 essere minore di zero.",AO_100075:"Il tempo totale dell'itinerario per veicolo deve essere maggiore di zero e minore di un anno (525600 minuti).",AO_100076:"Non specificare ${endLayer} se \u00e8 previsto il ritorno al punto di partenza.",AO_100077:"Comando Trova localit\u00e0 simili non riuscito.",AO_100078:"Nome di campo non valido nell'espressione ${expression}",AO_100079:"Comando Deriva nuove localit\u00e0 non riuscito.",AO_100080:"Comando Connetti origini a destinazioni non riuscito.", AO_100081:"Comando Calcolatore campo non riuscito.",AO_735:"Specificare almeno un campo di analisi valido su cui basare la somiglianza.",AO_1589:"Con questo strumento \u00e8 necessario specificare almeno due localit\u00e0 da cercare.",AO_100082:"Sono necessario un nome di campo e un'espressione.",AO_100083:"Per creare un nuovo campo \u00e8 necessario un tipo di campo.",AO_100084:"Il campo deve essere di tipo Stringa, Intero, Double o Data.",AO_1599:"Numero insufficiente di record per l'analisi. Per calcolare i risultati con questo strumento \u00e8 necessario almeno 1 posizione di riferimento nel layer di input.", AO_100088:"Il campo o i campi ${attribute} devono essere inclusi nei layer di riferimento e di ricerca candidati.",AO_100089:"La variazione nei seguenti campi \u00e8 insufficiente per l'uso in questa analisi: ${attribute}.",AO_100090:"Con questo strumento sono necessarie almeno due localit\u00e0 di ricerca candidate che non sono anche localit\u00e0 di riferimento.",AO_100094:"Il numero massimo di veicoli per l'itinerario deve essere uguale a quello delle feature in ${startLayer}.",AO_100104:"Interpolazione punti non riuscito.", AO_40039:"Dati insufficienti per calcolare il metodo. Sono necessari almeno 10 punti.",AO_40040:"I dati sono distribuiti lungo una linea retta. Impossibile elaborarli.",AO_40069:"La varianza dei dati \u00e8 troppo piccola per essere calcolata.",AO_100091:"Specificare punti come tipo di geometria di ${paramName}.",AO_100092:"Specificare poligoni come tipo di geometria del layer poligoni di contorno.",AO_100093:"Per il tipo di classificazione Manuale \u00e8 richiesto il valore di ClassBreaks.",AO_100095:"Il numero di feature in ${endLayer} deve essere uguale a quello in ${startLayer}.", AO_100096:"Il campo ${startLayerRouteIDField} in ${startLayer} non contiene valori univoci.",AO_100097:"Il campo ${endLayerRouteIDField} in ${endLayer} non contiene valori univoci.",AO_100098:"I valori del campo ${startLayerRouteIDField} in ${startLayer} non presentano una corrispondenza uno-a-uno con quelli nel campo ${endLayerRouteIDField} in ${endLayer}.",AO_100099:"Tutti i valori di interruzione devono essere maggiori di zero.",AO_100100:"Le feature in ${inputLayer} non sono compresi nell'area di coverage dati. Vedere la disponibilit\u00e0 all'indirizzo ${url}.", AO_100101:"In ${inputLayer} non sono presenti feature entro una distanza di ${max} chilometri dalle strade.",AO_100102:"Tutte le feature di ${inputLayer} devono trovarsi nello stesso fuso orario quando si utilizza la funzionalit\u00e0 di traffico e si creano aree con opzioni di dissolvenza o divisione.",AO_100103:"Il valore di ${measureType} non pu\u00f2 essere maggiore di ${max} ${breakUnits}.",AO_100105:"Calcolo densit\u00e0 non riuscito",AO_100106:"Il campo ${fieldName} non \u00e8 numerico.",AO_100107:"Il campo ${fieldName} non contiene valori positivi.", AO_100108:"Il campo ${fieldName} contiene valori negativi. Per il calcolo della densit\u00e0 verranno considerati solo i valori positivi.",AO_100109:"Specificare punti o linee come tipo di geometria del layer di input.",AO_100110:"Il ruolo utente disponibile non include il privilegio GeoEnrichment",AO_100111:"Il ruolo utente disponibile non include il privilegio Analisi rete",AO_100112:"Il ruolo utente disponibile non include il privilegio Pubblicare feature ospitate",AO_100113:"Nessuna fermata \u00e8 stata assegnata ad alcun itinerario. Controllare i campi Stato e Vincoli violati nel layer Fermate non assegnate di output per ulteriori informazioni.", AO_100114:"La durata di ciascuna fermata, ${stopServiceTime} minuti, deve essere minore della durata totale dell'itinerario per veicolo, ${maxRouteTime} minuti.",AO_100115:"Alcune fermate non sono state assegnate ad alcun itinerario. Controllare il campo Vincoli violati nel layer Fermate non assegnate di output per ulteriori informazioni.",AO_100116:"Sono necessari solo ${routesUsed} itinerari su ${routeCount} per raggiungere tutte le fermate. Se si desidera utilizzare pi\u00f9 itinerari, eseguire nuovamente Pianifica itinerari ma ridurre i limiti per il numero massimo di fermate o la durata totale dell'itinerario per veicolo.", AO_100117:"La guida di camion al momento non \u00e8 supportata al di fuori del Nord America e dell'America Centrale.",AO_100118:"Il ruolo utente non include il privilegio per la creazione, l'aggiornamento e l'eliminazione del contenuto.",GPEXT_001:"Valore del parametro ${name} non valido",GPEXT_002:"Parametro mancante ${name}",GPEXT_003:"Parametro non valido ${name}: propriet\u00e0 ${propname} mancante",GPEXT_004:"Propriet\u00e0 ${propname} del parametro del layer non valido mancante",GPEXT_005:"Impossibile accedere all'URL ${url}.", GPEXT_006:"L'accesso all'URL ${url} ha restituito l'errore ${error}.",GPEXT_007:"Elemento non valido ${id}",GPEXT_008:"Impossibile creare il servizio ${name}",GPEXT_009:"Impossibile aggiungere il layer ${lname} al servizio ${name}",GPEXT_010:"Impossibile analizzare il layer JSON",GPEXT_011:"Il layer ${url} non dispone di funzioni Estrai",GPEXT_012:"Operazione esterna non valida",GPEXT_013:"Questo strumento utilizza il servizio di miglioramento dei dati geografici. Per ulteriori informazioni, fare riferimento all'utilit\u00e0 per il calcolo dei crediti di servizio di ArcGIS Online.", GPEXT_014:"Questo strumento utilizza i servizi di analisi di rete. Per ulteriori informazioni, fare riferimento all'utilit\u00e0 per il calcolo dei crediti di servizio di ArcGIS Online.",GPEXT_015:"Selezionare l'URL dei servizi helper appropriato dal portale per l'operazione richiesta.",GPEXT_016:"Oggetto layer non valido.",GPEXT_017:"Servizio ${name} gi\u00e0 esistente.",GPEXT_018:"Il numero di feature nel servizio ${url} supera il limite di 100.000 feature. Utilizzare un feature service ospitato come input per analizzare dataset di grandi dimensioni.", GPEXT_019:"Filtro per layer ${url} non valido.",SS_00003:"Il seguente report include il riepilogo dei risultati della ricerca delle posizioni simili:",SS_84503:"Riepilogo delle feature input da abbinare",SS_89997:'["Attributo", "Min", "Max", "SD", "Media"]',SS_84504:"Riepilogo degli attributi di interesse",SS_84512:'["Attributo", "Min", "Max", "SD", "Media", "Input"]',SS_84505:"Prime ${numResults} posizioni pi\u00f9 simili (Values)",SS_84506:" Prime 10 di ${numResults} posizioni pi\u00f9 simili (Valori)", SS_84510:'["OID", "SIMRANK", "SIMINDEX"]',SS_89998:' ["", "Totale", ${sumIndex}] ',AO_100119:"Il tipo di geometria di input WithinLayer deve essere poligoni",AO_100120:"Le feature nel layer superano il limite massimo della dimensione richiesta e pertanto non possono essere complesse",AO_100121:"CreateViewshed non riuscito",AO_100122:"TraceDownstream non riuscito",AO_100123:"CreateWatersheds non riuscito",AO_100124:"Il tipo di geometria del layer di input deve essere punto per il tipo di buffer ${bufferType}", AO_100125:"Il campo groupby ${fieldName} deve includere un valore di tipo intero, testo o data.",AO_100126:"Le feature nel layer di input superano la dimensione della richiesta massima e pertanto vengono semplificate",AO_100127:"Tutti i punti di input sono all'esterno dell'area di copertura dei dati.",AO_100128:"Il campo punto immesso deve essere di tipo stringa o intero",AO_100129:"Il punto \u00e8 esterno all'estensione del bacino fluviale",AO_100130:"Il punto \u00e8 esterno all'estensione dell'unit\u00e0 di elaborazione", AO_100131:"Il parametro Distanza di visualizzazione massima non pu\u00f2 superare ${max}${units}",AO_100132:"I dati di origine DEM non sono disponibili nell'area dei punti di input.",AO_100133:"La risoluzione DEM di input non \u00e8 supportata per il valore della distanza massima specificato. Specificare un valore della distanza massima inferiore.",AO_100136:"Il tipo di geometria del layer estensione deve essere poligono.",AO_100137:"Valore per ${parameterName} obbligatorio.",AO_100138:"Alcune origini non sono connesse alle destinazioni associate. Per ulteriori informazioni, controllare il campo Stato nelle origini non assegnate di output e le destinazioni non assegnate.", AO_100139:"Nessuna delle origini pu\u00f2 essere connessa alle destinazioni.",AO_100140:"Le feature del layer di estensione superano le dimensioni max della richiesta e sono state semplificate.",AO_100141:"Le feature del layer di estensione superano le dimensioni max della richiesta e non possono essere estratte.",AO_100142:"L'estensione delle feature puntuali di input supera l'estensione massima consentita.",AO_100143:"Il ruolo utente disponibile non include il privilegio Analisi elevazione.",AO_100144:"Il servizio di utilit\u00e0 ${serviceName} non \u00e8 registrato per il portale.", AO_100145:"La seguente modalit\u00e0 di viaggio non \u00e8 valida: ${travelMode}.",AO_100146:"Le unit\u00e0 di interruzione scelte, ${breakUnits}, e la modalit\u00e0 di viaggio, ${travelMode}, non sono compatibili. Non sono reciprocamente valori di tempo o di distanza.",AO_100147:"La modalit\u00e0 di viaggio non specifica un attributo di impedenza basato sul tempo.",AO_100148:"Non si dispone delle autorizzazioni per accedere all'utilit\u00e0 ${serviceName}",AO_100149:"Impossibile accedere all'URL registrato per l'utilit\u00e0 ${serviceName}: ${msg}", AO_100150:"Scelta strutture migliori non riuscita.",AO_100151:"Le unit\u00e0 intervallo di spostamento scelte, ${travelRangeUnits}, e la modalit\u00e0 di viaggio, ${travelMode}, non sono compatibili. Non sono reciprocamente valori di tempo o di distanza.",AO_100152:"Il conteggio combinato di feature in ${requiredFacilitiesLayer} e ${candidateFacilitiesLayer} non pu\u00f2 essere maggiore di ${max}.",AO_100153:"Il valore del parametro ${paramName} deve essere maggiore di zero.",AO_100154:"Specificare un valore per il parametro ${paramName1} o ${paramName2}.", AO_100155:"Il layer strutture candidate, ${candidateFacilitiesLayer}, non deve essere specificato per l'obiettivo Alloca.",AO_100156:"La percentuale di richiesta da coprire deve essere maggiore di zero e minore o uguale a 100.",AO_100157:"Il numero di candidati da scegliere non pu\u00f2 essere minore del numero di feature nel layer strutture richiesto.",AO_100158:"Il numero di candidati da scegliere non pu\u00f2 essere maggiore di ${max}."},geoenrichment:{task:{GeoenrichmentTask:{noData:"Dati non disponibili per l'area selezionata"}}, dijit:{AgePyramid:{maxLabel:"Gruppo pi\u00f9 grande:",minLabel:"Gruppo pi\u00f9 piccolo:",compLabel:"I punti indicano il confronto con",menLabel:"Uomini",womenLabel:"Donne"},BufferOptions:{studyArea:"Mostra dati per:",ring:"Anello",driveTime:"Tempi di guida",driveDistance:"Distanza di guida",radius:"Raggio:",time:"Tempo:",distance:"Distanza:",buffer:"Buffer:",units:{esriDriveTimeUnitsMinutes:"minuti",esriMiles:"miglia",esriKilometers:"chilometri",esriFeet:"piedi",esriMeters:"metri"}},bufferTitle:{pointRing:{esriFeet:"Anello di ${radius} piedi", esriKilometers:"Anello di ${radius} km",esriMeters:"Anello di ${radius} metri",esriMiles:"Anello di ${radius} miglia"},pointDriveTime:{esriFeet:"Distanza di guida di ${radius} piedi",esriKilometers:"Distanza di guida di ${radius} km",esriMeters:"Distanza di guida di ${radius} metri",esriMiles:"Distanza di guida di ${radius} miglia",esriDriveTimeUnitsMinutes:"Tempo di guida di ${radius} minuti"},lineBuffer:{esriFeet:"Buffer di ${radius} piedi",esriKilometers:"Buffer di ${radius} km",esriMeters:"Buffer di ${radius} metri", esriMiles:"Buffer di ${radius} miglia"},polygon:"Quest'area",stdGeo:"Feature${level} di intersezione"},VariableStore:{global:"Globale",number:"#",percent:"%",average:"Media",index:"Indice",reliability:"Affidabilit\u00e0"},DataCategoriesPage:{loading:"Caricamento in corso...",search:"Cerca un nome di variabile",noResults:"Nessun risultato trovato per '${seachKey}'.",showFavorites:"Mostra variabili preferite",allHierarchies:"Tutti i dati",hierarchy_census:"Dati standard",hierarchy_landscape:"Dati del paesaggio", premiumHierarchy:"Dati di ${name}"},DataCollectionsPage:{categoryName:"Variabili di ${categoryName}",mapPopVar:"Scegli variabile comune",keepBrowse:"Continua esplorazione",showAll:"Mostra tutte le variabili di ${categoryName}",noResults:"Nessun risultato trovato per '${seachKey}'.",search:"Cerca nella categoria corrente"},DataVariablesPage:{allVariablesTitle:"Tutte le variabili",favoriteVariablesTitle:"Variabili preferite",groupVariables:"Variabili di ${groupName}",searchVariables:'Variabili di "${searchKey}"', allVariables:"Tutte le variabili",searchInGroupVariables:'Variabili di "${searchKey}" da ${groupName}',favoriteVariables:"Variabili preferite"},ShoppingCart:{selectedVars:"Variabili selezionate",noVariables:"Variabili non ancora selezionate"},VariableInfo:{name:"Nome",variable:"Variabile",source:"Origine",vintage:"D'epoca"},EnrichOptionsPage:{bufferRing:"Cerchio di un miglio intorno alle posizioni",bufferPolygon:"Poligoni di input (buffer non disponibile)",selectedVariables:"Variabili selezionate:", customize:"Personalizza",bufferOptions:"Mostra dati per:",edit:"modifica",totalVars:"Variabili totali: ${varCount} (${credits})",varsPerRow:"Variabili per riga: ${varCount} (${credits})",credits:"${credits} crediti",creditsCalc:"calcolo in corso...",totalVarsTooltip:"Quest'operazione aggiunger\u00e0 ${varCount} variabili alle righe ${rowCount} e coster\u00e0 ${credits}.",varsPerRowTooltip:"Quest'operazione aggiunger\u00e0 ${varCount} variabili alle righe e coster\u00e0 ${credits} a riga.",overwriteExisting:"I valori di colonna esistenti verranno sovrascritti", varName:"Nome variabile",column:"Colonna",newColumn:"\x3cCrea nuovo\x3e",noColumn:"\x3cNessuno\x3e",back:"Indietro",finish:"Aggiungi dati al sistema"},InfographicsMainPage:{mainTitle:"Configura infografica",loading:"Caricamento in corso...",chooseCountry:"Mostra dati disponibili per: ",chooseDataCollection:"Scegli da raccolte di dati pi\u00f9 comuni: ",chooseTheme:"Selezionare il tema colori:",dark:"Scuro",light:"Chiaro",addVariables:"Aggiungi altre variabili...",ok:"OK",add:"Aggiungi",cancel:"Annulla"}, OneVar:{subtitleSite2:"per quest'area ",subtitleVar2:"${alias} \u00e8 ",lessThan:"che \u00e8 inferiore alla media per ${site}",moreThan:"che \u00e8 superiore alla media per ${site}",same:"che \u00e8 uguale alla media per ${site}",areaCol:"Area",valueCol:"Valore"},RelatedVariables:{highLabel2:"Il gruppo pi\u00f9 grande: ${alias}",lowLabel2:"Il gruppo pi\u00f9 piccolo: ${alias}",indicatorCol:"Indicatore",valueCol:"Valore",difCol:"Differenza",chartLabel:"La barra mostra la deviazione da"},Tapestry:{hhTypeLabel:"Tipo di nucleo familiare:", medianAgeLabel:"Et\u00e0 media:",incomeLabel:"Reddito:",employmentLabel:"Occupazione:",educationLabel:"Istruzione:",residentialLabel:"Residenziale:",raceEthnicityLabel:"Razza/Etnia:",hhLabel:"Nuclei familiari",adultsLabel:"adulti",prtHhLabel:"di nuclei familiari"},WizardButtons:{back:"Indietro",ok:"OK",apply:"Applica",cancel:"Annulla",next:"Seguente"},EnrichConfig:{title:"Aggiungi dati al layer"},DataBrowser:{title:"Esplorazione dati"}}},filterDlg:{expressionTemplate:"${field_dropdown} ${operator_dropdown} ${values_input}", filter:"Filtro",applyFilter:"Applica filtro",applyFilterBtn:"Applica filtro",removeFilterBtn:"Rimuovi filtro",view:"Visualizza",change:"Cambia",edit:"Modifica",create:"Crea",match1Msg:"Visualizza le feature nel layer corrispondenti alla seguente espressione",matchMsg:"Visualizza le feature nel layer corrispondenti a ${any_or_all} seguenti espressioni",matchMsgSet:"In questo set ${any_or_all} seguenti espressioni sono vere",all:"tutte le",any:"una qualsiasi delle",andBetweenValues:"e",and:"e",or:"oppure", friendlyAnd:"Tutte queste espressioni devono essere vere:",friendlyOr:"Una qualsiasi di queste espressioni deve essere vera:",friendlyDatePattern:"dd/MM/yyyy",addAnotherExpression:"Aggiungi un'altra espressione",addSet:"Aggiungi un set",askForValues:"Richiedi valori",value:"Valore",valueTooltip:"Immetti valore",field:"Campo",fieldTooltip:"Seleziona da campo esistente",uniqueValues:"Univoci",uniqueValueTooltip:"Seleziona da valori univoci nel campo selezionato",toThisLayer:"A questo layer",toNewLayer:"A un nuovo layer", newLayerName:"Nuovo nome del layer",showFilterExpression:"Mostra espressioni del filtro",deleteExpression:"Elimina questa espressione",deleteSet:"Elimina questo set",addExpression:"Aggiungi un'espressione al set",addSetTooltip:"Aggiunge un set che conterr\u00e0 espressioni",promptMsg:"Consente di specificare un prompt e testo descrittivo per presentare il filtro in modo interattivo ad altri utenti.",prompt:"Prompt",hint:"Suggerimento",stringOperatorIs:"\u00e8",stringOperatorIsNot:"non \u00e8",stringOperatorStartsWith:"inizia con", stringOperatorEndsWith:"termina con",stringOperatorContains:"contiene",stringOperatorDoesNotContain:"non contiene",stringOperatorIsBlank:"\u00e8 vuoto",stringOperatorIsNotBlank:"non \u00e8 vuoto",dateOperatorIsOn:"ricorre il giorno",dateOperatorIsNotOn:"non ricorre il giorno",dateOperatorIsBefore:"ricorre prima del giorno",dateOperatorIsAfter:"ricorre dopo il giorno",dateOperatorDays:"giorni",dateOperatorWeeks:"settimane",dateOperatorMonths:"mesi",dateOperatorInTheLast:"negli ultimi/nelle ultime", dateOperatorNotInTheLast:"non negli ultimi/nelle ultime",dateOperatorIsBetween:"\u00e8 compreso tra",dateOperatorIsNotBetween:"non \u00e8 compreso tra",dateOperatorIsBlank:"\u00e8 vuoto",dateOperatorIsNotBlank:"non \u00e8 vuoto",numberOperatorIs:"\u00e8",numberOperatorIsNot:"non \u00e8",numberOperatorIsAtLeast:"\u00e8 almeno",numberOperatorIsLessThan:"\u00e8 minore di",numberOperatorIsAtMost:"\u00e8 al massimo",numberOperatorIsGreaterThan:"\u00e8 maggiore di",numberOperatorIsBetween:"\u00e8 compreso tra", numberOperatorIsNotBetween:"non \u00e8 compreso tra",numberOperatorIsBlank:"\u00e8 vuoto",numberOperatorIsNotBlank:"non \u00e8 vuoto",emptyString:"stringa vuota",error:{noUniqueValues:"Nessun valore disponibile per il campo specificato.",generateRendererFailed:"Impossibile determinare valori univoci per il campo selezionato.",missingValue:"valore mancante in una delle espressioni",cantParseExpression:"Impossibile visualizzare il filtro perch\u00e9 non \u00e8 possibile analizzarne una o pi\u00f9 espressioni. Per modificare le espressioni del filtro, cancellare il filtro e crearne uno nuovo in modo interattivo."}}, calculateFields:{addFieldTitle:"Aggiungi campo",nameLabel:"Nome:",aliasLabel:"Alias:",typeLabel:"Tipo:",lengthLabel:"Lunghezza:",defaultValueLabel:"Valore predefinito:",optional:"(Facoltativo)",stringLabel:"Stringa",integerLabel:"Intero",doubleLabel:"Double",dateLabel:"Data",expBuilderTitle:"Generatore espressioni",operators:"Operatori",availableFields:"Campi disponibili",helpers:"Helper",functions:"Funzioni",numeric:"Numerico",clear:"Cancella",validate:"Convalida",addNewField:"Aggiungi nuovo campo", add:"Aggiungi",close:"Chiudi",calculate:"Calcola",deleteLabel:"Elimina",exprLabel:"${fieldName} \x3d",layerReqMsg:"un layer \u00e8 un parametro obbligatorio per il campo di calcolo",fieldReqMsg:"Non \u00e8 stato specificato un campo di calcolo",lyrSupportCalMsg:"Questo layer ${layername} non supporta i campi di calcolo",lyrUpdateCapMsg:"La funzionalit\u00e0 di aggiornamento non \u00e8 abilitata nel layer ${layername} oppure non si dispone dell'accesso per aggiornare feature in questo layer",selectCalField:"Scegliere il campo da calcolare:", firstOperatorMsg:"Impossibile utilizzare l'operatore '${operator}' all'inizio di un'espressione",completeHelperMsg:"Completare il metodo helper aggiunto in precedenza",successMsg:"Aggiornamento di ${count} feature riuscito ",deleteField:"Elimina campo",deleteFieldConfirm:"Eliminare il campo '${field}' da questo layer?",fields:"Campi",exprFailedMsg:"Calcolo per l'espressione '${expr}' non riuscito.",inValidFielNameCharMsg:"Il nome di campo contiene uno o pi\u00f9 caratteri non validi\x3cbr/\x3e(`~@#$%^\x26*()-+\x3d|\\\x3c\x3e?/{.!'[]:\n\r).", inValidFieldStartCharMsg:"Il nome di campo non pu\u00f2 iniziare con uno di questi caratteri non validi\x3cbr/\x3e(`~@#$%^\x26*()-+\x3d|\\\x3c\x3e?/{}.!'[]:;\n\r_012356789).",invalidSqlkeywordsMsg:"Il nome di campo non pu\u00f2 essere uguale a una parola chiave SQL.",invalidExpression:"L'espressione di calcolo non \u00e8 valida",validExpression:"L'espressione \u00e8 stata verificata con successo.",sameFielNameMsg:"Il nome di campo non pu\u00f2 essere uguale a un nome di campo esistente",invalidFieldLengthMsg:"La lunghezza del nome del campo deve essere inferiore a 128 caratteri.", errorCodes:{3001:"Espressione SQL non supportata.",3002:"Errore di sintassi dell'espressione SQL.",3004:"Errore semantico dell'espressione SQL.",3007:"Nome di tabella ${tableName} non valido.",3008:"Nome di campo ${fieldName} non valido.",3009:"Espressione SQL non sicura non consentita."},absFunc:"${functionName}: restituisce il valore assoluto (positivo) di ${num}.",castFunc:"${functionName}: converte ${num} in un tipo diverso. FLOAT converte ${num} nel tipo double e INT converte nel tipo integer.", ceilingFunc:"${functionName}: restituisce l'intero pi\u00f9 piccolo maggiore o uguale a ${num}.",cosFunc:"${functionName}: restituisce il coseno di ${num}. Si presume che ${num} sia un angolo espresso in radianti.",floorFunc:"${functionName}: restituisce l'intero pi\u00f9 grande minore o uguale a ${num}.",logFunc:"${functionName}: logaritmo naturale di ${num}.",log10Func:"${functionName}: logaritmo in base 10 di ${num}.",modFunc:"${functionName}: restituisce il resto dopo l'esecuzione della divisione di n su ${num}. ${n} e ${num} devono essere numeri interi.", powerFunc:"${functionName}: restituisce il valore di ${num} elevato alla potenza ${y} specificata.",roundFunc:"${functionName}: arrotonda ${num} al valore specificato ${length}.",sinFunc:"${functionName}: restituisce il seno di ${num}. Si presume che ${num} sia un angolo espresso in radianti.",tanFunc:"${functionName}: restituisce la tangente di ${num}. Si presume che ${num} sia un angolo espresso in radianti.",truncateFunc:"${functionName}: tronca ${num} alla posizione ${decimal_place} specificata. Un valore ${decimal_place} positivo comporta il troncamento, mentre un valore ${decimal_place} negativo comporta l'arrotondamento.", nullifFunc:"${functionName}: restituisce un valore nullo se ${num} \u00e8 uguale a ${value}. In genere viene utilizzata per evitare errori di divisione per zero impostando ${value} su 0.",char_lengthFunc:"${functionName}: restituisce il numero di caratteri in ${str}. Il risultato \u00e8 un numero intero.",concatFunc:"${functionName}: concatena due stringhe.",positionFunc:"${functionName}: restituisce la posizione della prima occorrenza della sottostringa in ${str}. Se la sottostringa non viene trovata, il risultato \u00e8 0.", lowerFunc:"${functionName}: restituisce una stringa dove tutti i caratteri in ${str} vengono convertiti in minuscolo.",substringFunc:"${functionName}: restituisce una parte di ${str}. ${start} \u00e8 un indice intero che specifica dove iniziano i caratteri restituiti. ${length} \u00e8 il numero di caratteri da restituire.",trimFunc:"${functionName}: restituisce una stringa dove tutti gli spazi iniziali o finali vengono rimossi da ${str}.",upperFunc:"${functionName}: restituisce una stringa dove tutti i caratteri in ${str} vengono convertiti in maiuscolo.", current_dateFunc:"${functionName}: restituisce la data corrente.",current_timeFunc:"${functionName}: restituisce l'ora corrente (ore, minuti, secondi).",current_timestampFunc:"${functionName}: restituisce l'ora corrente (ore, minuti, secondi, millisecondi)."},smartMapping:{other:"Altro",minToMax:"a",sumOfCategories:"Somma di categorie",predominantCategory:"Categoria predominante",strengthOfPredominance:"Intensit\u00e0 di predominanza",ageInfo_years:"Et\u00e0 in anni da ${startTime} a ${endTime}", ageInfo_months:"Et\u00e0 in mesi, da ${startTime} a ${endTime}",ageInfo_days:"Et\u00e0, in giorni, da ${startTime} a ${endTime}",ageInfo_hours:"Et\u00e0, in ore, da ${startTime} a ${endTime}",ageInfo_minutes:"Et\u00e0, in minuti, da ${startTime} a ${endTime}",ageInfo_seconds:"Et\u00e0, in secondi, da ${startTime} a ${endTime}"},networkAnalysis:{enums:{esriNAObjectStatus:{esriNAObjectStatusOK:"OK",esriNAObjectStatusNotLocated:"Non trovato in rete",esriNAObjectStatusElementNotLocated:"Non generato dalla rete", esriNAObjectStatusElementNotTraversable:"Divieto di accesso",esriNAObjectStatusInvalidFieldValues:"Valori di campo non validi",esriNAObjectStatusNotReached:"Irraggiungibile",esriNAObjectStatusTimeWindowViolation:"Violazione finestra temporale"},esriNACurbApproachType:{esriNAEitherSideOfVehicle:"Qualunque lato",esriNARightSideOfVehicle:"Dalla destra",esriNALeftSideOfVehicle:"Dalla sinistra",esriNANoUTurn:"Partire nella stessa direzione"},esriNALocationType:{stop:"Termine",waypoint:"Punto di riferimento"}, esriDirectionsManeuverType:{esriDMTBearLeft:"Svoltare a sinistra",esriDMTBearRight:"Svoltare a destra",esriDMTDepart:"Fermarsi",esriDMTDoorPassage:"Porta",esriDMTElevator:"Ascensore",esriDMTEndOfFerry:"Fine del traghetto",esriDMTEscalator:"Scala mobile",esriDMTFerry:"Imbarcarsi sul traghetto",esriDMTForkCenter:"All'incrocio, rimanere al centro",esriDMTForkLeft:"All'incrocio, mantenere la sinistra",esriDMTForkRight:"All'incrocio, mantenere la destra",esriDMTHighwayChange:"Prendere un'altra autostrada", esriDMTHighwayExit:"Uscire dall'autostrada",esriDMTHighwayMerge:"Convergere in autostrada",esriDMTPedestrianRamp:"Rampa pedoni",esriDMTRampLeft:"Rampa a sinistra",esriDMTRampRight:"Rampa a destra",esriDMTRoundabout:"Prendere la rotatoria",esriDMTSharpLeft:"Fare una curva accentuata a sinistra",esriDMTSharpRight:"Fare una curva accentuata a destra",esriDMTStairs:"Scale",esriDMTStop:"Arrivare allo stop",esriDMTStraight:"Andare diritto",esriDMTTripItem:"Elemento di pianificazione del percorso",esriDMTTurnLeft:"Svoltare a sinistra", esriDMTTurnLeftLeft:"Svoltare a sinistra e poi immediatamente a sinistra",esriDMTTurnLeftRight:"Svoltare a sinistra e poi immediatamente a destra",esriDMTTurnRight:"Svoltare a destra",esriDMTTurnRightLeft:"Svoltare a destra e poi immediatamente a sinistra",esriDMTTurnRightRight:"Svoltare a destra e poi immediatamente a destra",esriDMTUnknown:"Sconosciuto",esriDMTUTurn:"Fare inversione di marcia"}},fields:{RouteId:"ID itinerario",stops:{CurbApproach:"Curb approach",ArrivalCurbApproach:"Curb approach in arrivo", DepartureCurbApproach:"Curb approach in partenza",Name:"Nome",Sequence:"Sequenza",Status:"Stato",LocationType:"Tipo di posizione",TimeWindowStart:"Inizio finestra temporale",TimeWindowEnd:"Fine finestra temporale",ArrivalTime:"Ora di arrivo",DepartureTime:"Ora di partenza",ArrivalUTCOffset:"Ora di arrivo: offset da UTC in minuti",DepartureUTCOffset:"Ora di partenza: offset da UTC in minuti",ServiceMinutes:"Minuti di servizio",ServiceMeters:"Metri di servizio",ServiceOtherCosts:"Altri costi di servizio", CumulativeMinutes:"Minuti cumulativi",CumulativeMeters:"Metri cumulativi",CumulativeOtherCosts:"Altri costi cumulativi",LateMinutes:"Minuti di ritardo",WaitMinutes:"Minuti di anticipo",Properties:"Propriet\u00e0 aggiuntive"},directions:{Sequence:"Sequenza",StopSequence:"Sequenza di fermate associate",ArrivalTime:"La manovra inizia alle",UTCOffset:"Offset da UTC in minuti",ManeuverType:"Manovra",Meters:"Lunghezza in metri",Minutes:"Durata in minuti",DirectionText:"Testo di direzione",ManeuverMessages:"Messaggi manovra"}, directionEvents:{DirectionSequence:"Sequenza direzione",Sequence:"Sequenza",ArrivalTime:"Ora evento",UTCOffset:"Offset da UTC in minuti",EventText:"Testo evento",EventMessages:"Messaggi evento"},routeInfo:{Version:"Versione",RouteName:"Nome itinerario",TotalMinutes:"Minuti totali",TotalMeters:"Metri totali",TotalLateMinutes:"Minuti di ritardo totali",TotalWaitMinutes:"Minuti di attesa totali",OtherCosts:"Altri costi",StartTime:"Tempo Iniziale",StartUTCOffset:"Ora di inizio: offset da UTC in minuti", EndTime:"Ora di fine",EndUTCOffset:"Ora di fine: offset da UTC in minuti",Messages:"Messaggi di analisi",AnalysisSettings:"Impostazioni di analisi",Properties:"Propriet\u00e0 aggiuntive"}},sharing:{stopsLayer:"Fermate",directionsLayer:"Indicazioni",directionEventsLayer:"Eventi direzione",routeInfoLayer:"Dettagli percorso",itemDescription:"Aggiungere una descrizione dettagliata dell'elemento.",itemTags:"percorso, layer percorso",itemSnippet:"Percorso e indicazioni per",rootFolder:"Home",Minutes:"minuti", Meters:"metri",Miles:"miglia",StartTime:"Ora di inizio percorso:",costAttributeMissing:"Il layer del percorso caricato non corrisponde al servizio del percorso: manca il costo dell'attributo.",differentVersion:"\u00c8 stata rilevata una nuova versione del layer percorso, \u00e8 possibile che non tutti i dati siano stati caricati."}},browseLayersDlg:{browseTitle:"Sfoglia layer atlante dinamico",categoryAll:"Tutte le categorie",categoryImagery:"Immagini",subCategoryBasemapImagery:"Immagini di mappe di base", subCategoryMultiSpectral:"Immagini multispettrali",subCategoryTemporal:"Immagini nel tempo",subCategoryEvent:"Immagini di eventi",categoryBasemaps:"Mappe di base",subCategoryEsriBasemaps:"Mappe di base Esri",subCategoryPartnerBasemaps:"Mappe di base partner",subCategoryUserBasemaps:"Mappe di base utente",categoryHistoricalMaps:"Mappe storiche",categoryDemographics:"Dati demografici e sullo stile di vita",subCategoryIncome:"Reddito e spese",subCategoryPopulation:"Popolazione e alloggi",subCategorySegmentation:"Segmentazione e comportamenti", subCategoryBusiness:"Attivit\u00e0 e professioni",subCategoryAtRisk:"A rischio",categoryLandscape:"Paesaggio",subCategoryClimate:"Clima e meteo",subCategoryEcology:"Ecologia",subCategorySpecies:"Biologia delle specie",subCategoryDisturbance:"Disturbo e impatto",subCategoryElevation:"Elevazione",subCategoryLand:"Copertura del suolo",subCategoryHazards:"Rischi naturali",subCategoryOceans:"Oceani",subCategorySoils:"Suoli/Geologia",subCategorySubsurface:"Sottosuolo",subCategoryWater:"Acqua",subCategoryWeather:"Meteo", categoryEarthObservations:"Osservazioni terrestri",categoryUrbanSystems:"Sistemi urbani",subCategory3DCities:"Citt\u00e0 3D",subCategoryMovement:"Spostamento",subCategoryParcels:"Lotti",subCategoryPeople:"Persone",subCategoryPlanning:"Pianificazione",subCategoryPublic:"Pubblico",subCategoryWork:"Lavoro",categoryTransportation:"Trasporti",categoryBoundaries:"Confini e luoghi",subCategoryBoundaries:"Confini",subCategoryPlaces:"Luoghi",categoryHexBins:"File binari esadecimali",searchFor:"Cerca",errorLabel:"Errore", searchTitle:"Ricerca",error:{wildCardSearchError:"Le ricerche con caratteri jolly non sono supportate."}},gallery:{noFilterFields:"Il layer ${name} non contiene campi utilizzabili per il filtro.",addToViewer:"Aggiungi layer a mappa",noItemsToDisplay:"Non \u00e8 attualmente disponibile alcun elemento da visualizzare.",searchFor:"Cerca",searching:"Ricerca in corso"},browseItems:{items:{organizationLabel:"La mia organizzazione",onlineLabel:"ArcGIS Online",contentLabel:"Contenuto personale",favoritesLabel:"I miei preferiti", portalOrg:"Portal for ArcGIS"},title:"Seleziona mappa Web",searchTitle:"Cerca",ok:"OK",cancel:"Annulla",placeholder:"Immettere il termine da cercare",instructionsLeft:"Selezionare l'operazione da eseguire?",instructionsRight:"Selezionare un'app configurabile.",go:"Vai",selectDetails:"SELECT",configure:"Crea",learnMoreConfigurableApps:"Ulteriori informazioni sulle app configurabili",noValidLayerMsg:"Nessun layer soddisfa i criteri del parametro di input."},_localized:{}},"dojo/cldr/nls/number":{scientificFormat:"#E0", "currencySpacing-afterCurrency-currencyMatch":"[:^S:]",infinity:"\u221e",superscriptingExponent:"\u00d7",list:";",percentSign:"%",minusSign:"-","currencySpacing-beforeCurrency-surroundingMatch":"[:digit:]","decimalFormat-short":"000\u00a0Bln","currencySpacing-afterCurrency-insertBetween":"\u00a0",nan:"NaN",plusSign:"+","currencySpacing-afterCurrency-surroundingMatch":"[:digit:]","currencySpacing-beforeCurrency-currencyMatch":"[:^S:]",currencyFormat:"#,##0.00\u00a0\u00a4",perMille:"\u2030",group:".", percentFormat:"#,##0%","decimalFormat-long":"000 bilioni",decimalFormat:"#,##0.###",decimal:",","currencySpacing-beforeCurrency-insertBetween":"\u00a0",exponential:"E",_localized:{}},"dojo/cldr/nls/gregorian":{"dateFormatItem-Ehm":"E h.mm a","days-standAlone-short":"dom lun mar mer gio ven sab".split(" "),"months-format-narrow":"GFMAMGLASOND".split(""),"field-second-relative+0":"ora","quarters-standAlone-narrow":["1","2","3","4"],"field-weekday":"giorno della settimana","dateFormatItem-yQQQ":"QQQ y", "dateFormatItem-yMEd":"E d/M/y","field-wed-relative+0":"questo mercoled\u00ec","field-wed-relative+1":"mercoled\u00ec prossimo","dateFormatItem-GyMMMEd":"E d MMM y G","dateFormatItem-MMMEd":"E d MMM",eraNarrow:["aC","BCE","dC","CE"],"field-tue-relative+-1":"marted\u00ec scorso","days-format-short":"dom lun mar mer gio ven sab".split(" "),"dateTimeFormats-appendItem-Day-Of-Week":"{0} {1}","dateFormat-long":"dd MMMM y","field-fri-relative+-1":"venerd\u00ec scorso","field-wed-relative+-1":"mercoled\u00ec scorso", "months-format-wide":"gennaio febbraio marzo aprile maggio giugno luglio agosto settembre ottobre novembre dicembre".split(" "),"dateTimeFormat-medium":"{1} {0}","dayPeriods-format-wide-pm":"PM","dateFormat-full":"EEEE d MMMM y","field-thu-relative+-1":"gioved\u00ec scorso","dateFormatItem-Md":"d/M","dayPeriods-format-abbr-am":"AM","dateTimeFormats-appendItem-Second":"{0} ({2}: {1})","dayPeriods-format-wide-noon":"noon","dateFormatItem-yMd":"d/M/y","field-era":"era","dateFormatItem-yM":"M/y","months-standAlone-wide":"Gennaio Febbraio Marzo Aprile Maggio Giugno Luglio Agosto Settembre Ottobre Novembre Dicembre".split(" "), "timeFormat-short":"HH:mm","quarters-format-wide":["1\u00ba trimestre","2\u00ba trimestre","3\u00ba trimestre","4\u00ba trimestre"],"dateFormatItem-yQQQQ":"QQQQ y","timeFormat-long":"HH:mm:ss z","field-year":"anno","dateFormatItem-yMMM":"MMM y","dateTimeFormats-appendItem-Era":"{1} {0}","field-hour":"ora","months-format-abbr":"gen feb mar apr mag giu lug ago set ott nov dic".split(" "),"field-sat-relative+0":"questo sabato","field-sat-relative+1":"sabato prossimo","timeFormat-full":"HH:mm:ss zzzz", "dateTimeFormats-appendItem-Week":"{0} ({2}: {1})","field-day-relative+0":"oggi","field-thu-relative+0":"questo gioved\u00ec","field-day-relative+1":"domani","field-thu-relative+1":"gioved\u00ec prossimo","dateFormatItem-GyMMMd":"d MMM y G","dateFormatItem-H":"HH","months-standAlone-abbr":"gen feb mar apr mag giu lug ago set ott nov dic".split(" "),"quarters-format-abbr":["T1","T2","T3","T4"],"quarters-standAlone-wide":["Primo trimestre","Secondo trimestre","Terzo trimestre","Quarto trimestre"],"dateFormatItem-Gy":"y G", "dateFormatItem-M":"L","days-standAlone-wide":"Domenica Luned\u00ec Marted\u00ec Mercoled\u00ec Gioved\u00ec Venerd\u00ec Sabato".split(" "),"dayPeriods-format-abbr-noon":"noon","timeFormat-medium":"HH:mm:ss","field-sun-relative+0":"questa domenica","dateFormatItem-Hm":"HH:mm","field-sun-relative+1":"domenica prossima","quarters-standAlone-abbr":["T1","T2","T3","T4"],eraAbbr:["aC","BCE","dC","CE"],"field-minute":"minuto","field-dayperiod":"periodo del giorno","days-standAlone-abbr":"dom lun mar mer gio ven sab".split(" "), "dateFormatItem-d":"d","dateFormatItem-ms":"mm:ss","quarters-format-narrow":["1","2","3","4"],"field-day-relative+-1":"ieri","dateTimeFormat-long":"{1} {0}","dayPeriods-format-narrow-am":"m.","dateFormatItem-h":"hh a","dateFormatItem-MMMd":"d MMM","dateFormatItem-MEd":"E d/M","dateTimeFormat-full":"{1} {0}","field-fri-relative+0":"questo venerd\u00ec","field-fri-relative+1":"venerd\u00ec prossimo","field-day":"giorno","days-format-wide":"domenica luned\u00ec marted\u00ec mercoled\u00ec gioved\u00ec venerd\u00ec sabato".split(" "), "field-zone":"fuso orario","months-standAlone-narrow":"GFMAMGLASOND".split(""),"dateFormatItem-y":"y","dateTimeFormats-appendItem-Day":"{0} ({2}: {1})","field-year-relative+-1":"anno scorso","field-month-relative+-1":"mese scorso","dateTimeFormats-appendItem-Year":"{1} {0}","dateFormatItem-hm":"hh:mm a","dateTimeFormats-appendItem-Hour":"{0} ({2}: {1})","dayPeriods-format-abbr-pm":"PM","days-format-abbr":"dom lun mar mer gio ven sab".split(" "),eraNames:["a.C.","BCE","d.C.","CE"],"dateFormatItem-yMMMd":"d MMM y", "days-format-narrow":"DLMMGVS".split(""),"field-month":"mese","days-standAlone-narrow":"DLMMGVS".split(""),"dateFormatItem-MMM":"LLL","field-tue-relative+0":"questo marted\u00ec","dateTimeFormats-appendItem-Quarter":"{0} ({2}: {1})","field-tue-relative+1":"marted\u00ec prossimo","dayPeriods-format-wide-am":"AM","dateTimeFormats-appendItem-Month":"{0} ({2}: {1})","dateTimeFormats-appendItem-Minute":"{0} ({2}: {1})","dateFormatItem-EHm":"E HH.mm","field-mon-relative+0":"questo luned\u00ec","field-mon-relative+1":"luned\u00ec prossimo", "dateFormat-short":"dd/MM/yy","dateFormatItem-EHms":"E HH:mm:ss","dateFormatItem-Ehms":"E h:mm:ss a","dayPeriods-format-narrow-noon":"n","field-second":"secondo","field-sat-relative+-1":"sabato scorso","dateFormatItem-yMMMEd":"E d MMM y","field-sun-relative+-1":"domenica scorsa","field-month-relative+0":"questo mese","field-month-relative+1":"mese prossimo","dateTimeFormats-appendItem-Timezone":"{0} {1}","dateFormatItem-Ed":"E d","field-week":"settimana","dateFormat-medium":"dd/MMM/y","field-week-relative+-1":"settimana scorsa", "field-year-relative+0":"quest'anno","field-year-relative+1":"anno prossimo","dayPeriods-format-narrow-pm":"p.","dateTimeFormat-short":"{1} {0}","dateFormatItem-Hms":"HH:mm:ss","dateFormatItem-hms":"hh:mm:ss a","dateFormatItem-GyMMM":"MMM y G","field-mon-relative+-1":"luned\u00ec scorso","field-week-relative+0":"questa settimana","field-week-relative+1":"settimana prossima","field-day-relative+2":"dopodomani","field-day-relative+-2":"l'altro ieri","dateFormatItem-yMMMM":"MMMM y",_localized:{}}});
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'settings.ui' # # Created by: PyQt5 UI code generator 5.7 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_SettingsWindow(object): def setupUi(self, SettingsWindow): SettingsWindow.setObjectName("SettingsWindow") SettingsWindow.resize(414, 230) self.centralwidget = QtWidgets.QWidget(SettingsWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.label_url = QtWidgets.QLabel(self.centralwidget) self.label_url.setObjectName("label_url") self.gridLayout.addWidget(self.label_url, 0, 0, 1, 1) self.line_edit_url = QtWidgets.QLineEdit(self.centralwidget) self.line_edit_url.setObjectName("line_edit_url") self.gridLayout.addWidget(self.line_edit_url, 0, 1, 1, 1) self.label_user = QtWidgets.QLabel(self.centralwidget) self.label_user.setObjectName("label_user") self.gridLayout.addWidget(self.label_user, 1, 0, 1, 1) self.line_edit_user = QtWidgets.QLineEdit(self.centralwidget) self.line_edit_user.setObjectName("line_edit_user") self.gridLayout.addWidget(self.line_edit_user, 1, 1, 1, 1) self.button_login = QtWidgets.QPushButton(self.centralwidget) self.button_login.setObjectName("button_login") self.gridLayout.addWidget(self.button_login, 1, 2, 1, 1) self.label_pass = QtWidgets.QLabel(self.centralwidget) self.label_pass.setObjectName("label_pass") self.gridLayout.addWidget(self.label_pass, 2, 0, 1, 1) self.line_edit_pass = QtWidgets.QLineEdit(self.centralwidget) self.line_edit_pass.setEchoMode(QtWidgets.QLineEdit.Password) self.line_edit_pass.setObjectName("line_edit_pass") self.gridLayout.addWidget(self.line_edit_pass, 2, 1, 1, 1) self.button_save = QtWidgets.QPushButton(self.centralwidget) self.button_save.setObjectName("button_save") self.gridLayout.addWidget(self.button_save, 3, 1, 1, 1) self.check_box_save_password = QtWidgets.QCheckBox(self.centralwidget) self.check_box_save_password.setObjectName("check_box_save_password") self.gridLayout.addWidget(self.check_box_save_password, 2, 2, 1, 1) SettingsWindow.setCentralWidget(self.centralwidget) self.retranslateUi(SettingsWindow) QtCore.QMetaObject.connectSlotsByName(SettingsWindow) def retranslateUi(self, SettingsWindow): _translate = QtCore.QCoreApplication.translate SettingsWindow.setWindowTitle(_translate("SettingsWindow", "Settings")) self.label_url.setText(_translate("SettingsWindow", "Base URL")) self.label_user.setText(_translate("SettingsWindow", "User")) self.button_login.setText(_translate("SettingsWindow", "Login")) self.label_pass.setText(_translate("SettingsWindow", "Pass")) self.button_save.setText(_translate("SettingsWindow", "Save")) self.check_box_save_password.setText(_translate("SettingsWindow", "Save"))
import React from 'react'; import {InteractionManager, View} from 'react-native'; import PropTypes from 'prop-types'; import _ from 'underscore'; import ExpensiMark from 'expensify-common/lib/ExpensiMark'; import reportActionPropTypes from './reportActionPropTypes'; import styles from '../../../styles/styles'; import Composer from '../../../components/Composer'; import * as Report from '../../../libs/actions/Report'; import * as ReportScrollManager from '../../../libs/ReportScrollManager'; import toggleReportActionComposeView from '../../../libs/toggleReportActionComposeView'; import withWindowDimensions, {windowDimensionsPropTypes} from '../../../components/withWindowDimensions'; import withLocalize, {withLocalizePropTypes} from '../../../components/withLocalize'; import Button from '../../../components/Button'; import ReportActionComposeFocusManager from '../../../libs/ReportActionComposeFocusManager'; import compose from '../../../libs/compose'; import * as ReportActionContextMenu from './ContextMenu/ReportActionContextMenu'; import VirtualKeyboard from '../../../libs/VirtualKeyboard'; const propTypes = { /** All the data of the action */ action: PropTypes.shape(reportActionPropTypes).isRequired, /** Draft message */ draftMessage: PropTypes.string.isRequired, /** ReportID that holds the comment we're editing */ reportID: PropTypes.number.isRequired, /** Position index of the report action in the overall report FlatList view */ index: PropTypes.number.isRequired, /** A ref to forward to the text input */ forwardedRef: PropTypes.func, /** Window Dimensions Props */ ...windowDimensionsPropTypes, /** Localization props */ ...withLocalizePropTypes, }; const defaultProps = { forwardedRef: () => {}, }; class ReportActionItemMessageEdit extends React.Component { constructor(props) { super(props); this.updateDraft = this.updateDraft.bind(this); this.deleteDraft = this.deleteDraft.bind(this); this.debouncedSaveDraft = _.debounce(this.debouncedSaveDraft.bind(this), 1000); this.publishDraft = this.publishDraft.bind(this); this.triggerSaveOrCancel = this.triggerSaveOrCancel.bind(this); this.onSelectionChange = this.onSelectionChange.bind(this); const parser = new ExpensiMark(); const draftMessage = parser.htmlToMarkdown(this.props.draftMessage); this.state = { draft: draftMessage, selection: { start: draftMessage.length, end: draftMessage.length, }, }; } /** * Update Selection on change cursor position. * * @param {Event} e */ onSelectionChange(e) { this.setState({selection: e.nativeEvent.selection}); } /** * Update the value of the draft in Onyx * * @param {String} newDraft */ updateDraft(newDraft) { this.textInput.setNativeProps({text: newDraft}); this.setState({draft: newDraft}); // This component is rendered only when draft is set to a non-empty string. In order to prevent component // unmount when user deletes content of textarea, we set previous message instead of empty string. if (newDraft.trim().length > 0) { this.debouncedSaveDraft(newDraft); } else { this.debouncedSaveDraft(this.props.action.message[0].html); } } /** * Delete the draft of the comment being edited. This will take the comment out of "edit mode" with the old content. */ deleteDraft() { this.debouncedSaveDraft.cancel(); Report.saveReportActionDraft(this.props.reportID, this.props.action.reportActionID, ''); toggleReportActionComposeView(true, this.props.isSmallScreenWidth); ReportActionComposeFocusManager.focus(); } /** * Save the draft of the comment. This debounced so that we're not ceaselessly saving your edit. Saving the draft * allows one to navigate somewhere else and come back to the comment and still have it in edit mode. * @param {String} newDraft */ debouncedSaveDraft(newDraft) { Report.saveReportActionDraft(this.props.reportID, this.props.action.reportActionID, newDraft); } /** * Save the draft of the comment to be the new comment message. This will take the comment out of "edit mode" with * the new content. */ publishDraft() { // To prevent re-mount after user saves edit before debounce duration (example: within 1 second), we cancel // debounce here. this.debouncedSaveDraft.cancel(); const trimmedNewDraft = this.state.draft.trim(); // When user tries to save the empty message, it will delete it. Prompt the user to confirm deleting. if (!trimmedNewDraft) { ReportActionContextMenu.showDeleteModal( this.props.reportID, this.props.action, false, this.deleteDraft, () => InteractionManager.runAfterInteractions(() => this.textInput.focus()), ); return; } Report.editReportComment(this.props.reportID, this.props.action, trimmedNewDraft); this.deleteDraft(); } /** * Key event handlers that short cut to saving/canceling. * * @param {Event} e */ triggerSaveOrCancel(e) { if (e && e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); this.publishDraft(); } else if (e && e.key === 'Escape') { e.preventDefault(); this.deleteDraft(); } } render() { return ( <View style={styles.chatItemMessage}> <View style={[styles.chatItemComposeBox, styles.flexRow, styles.chatItemComposeBoxColor]}> <Composer multiline ref={(el) => { this.textInput = el; this.props.forwardedRef(el); }} onChangeText={this.updateDraft} // Debounced saveDraftComment onKeyPress={this.triggerSaveOrCancel} defaultValue={this.state.draft} maxLines={16} // This is the same that slack has style={[styles.textInputCompose, styles.flex4]} onFocus={() => { ReportScrollManager.scrollToIndex({animated: true, index: this.props.index}, true); toggleReportActionComposeView(false, VirtualKeyboard.shouldAssumeIsOpen()); }} selection={this.state.selection} onSelectionChange={this.onSelectionChange} /> </View> <View style={[styles.flexRow, styles.mt1]}> <Button small style={[styles.mr2]} onPress={this.deleteDraft} text={this.props.translate('common.cancel')} /> <Button small success style={[styles.mr2]} onPress={this.publishDraft} text={this.props.translate('common.saveChanges')} /> </View> </View> ); } } ReportActionItemMessageEdit.propTypes = propTypes; ReportActionItemMessageEdit.defaultProps = defaultProps; export default compose( withLocalize, withWindowDimensions, )(React.forwardRef((props, ref) => ( /* eslint-disable-next-line react/jsx-props-no-spreading */ <ReportActionItemMessageEdit {...props} forwardedRef={ref} /> )));
import logging import os import tempfile import shutil from . import pyjson logger = logging.getLogger(__name__) class BaseStateCommitter(object): def load(self): """ Load and return the state """ raise NotImplementedError def commit(self, state): """ Commit the state """ raise NotImplementedError class JsonStateCommitter(BaseStateCommitter): def __init__(self, json_path): self._state_file = json_path @property def path(self): return self._state_file @property def state_file_exists(self) -> bool: return os.path.isfile(self._state_file) def load(self, default=None): """ Loads and reads from state file. If an error occurs, `default` will be returned, if it exists. """ try: with open(self._state_file) as json_data: return pyjson.load(json_data) except (ValueError, EnvironmentError) as e: if default is not None: logger.warning( f"Failed to load state from {self.path} due to {e}. Returning default: {default}.", exc_info=True, ) return default logger.error(f"Failed to load state from {self.path}: {e}", exc_info=True) raise e def commit(self, state): """ Write out the state in JSON format to a temporary file and rename it into place """ with tempfile.NamedTemporaryFile(delete=False) as f: try: f.write(pyjson.dumps(state).encode()) f.flush() shutil.copyfile(f.name, self._state_file) finally: try: os.unlink(f.name) except FileNotFoundError: logger.error( "Problem occurred in deleting temp file {} via os.unlink".format(f.name) )
import util from '@/util' export const loadReport = ({commit}, payload) => { commit('UPDATE_FLOW_DATA', payload.flowData) commit('UPDATE_SITE_DATA', payload.siteData) commit('UPDATE_REPORT_ID', payload.reportId) commit('UPDATE_SITE', payload.site) } export const quickSaveToTmpFile = ({getters}) => { util.saveTmp(getters.reportId, { reportId: getters.reportId, siteData: getters.siteData, flowData: getters.flowData, results: getters.results, site: getters.site }) } export const saveAs = ({getters}, location) => { // util.saveAs(location, { // reportId: getters.reportId, // siteData: getters.siteData, // flowData: getters.flowData, // results: getters.results, // site: getters.site // }) util.saveAsCsv( location, getters.siteData, getters.flowData, getters.results ) }
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * screen.c: code for displaying on the screen * * Output to the screen (console, terminal emulator or GUI window) is minimized * by remembering what is already on the screen, and only updating the parts * that changed. * * ScreenLines[off] Contains a copy of the whole screen, as it is currently * displayed (excluding text written by external commands). * ScreenAttrs[off] Contains the associated attributes. * LineOffset[row] Contains the offset into ScreenLines*[] and ScreenAttrs[] * for each line. * LineWraps[row] Flag for each line whether it wraps to the next line. * * For double-byte characters, two consecutive bytes in ScreenLines[] can form * one character which occupies two display cells. * For UTF-8 a multi-byte character is converted to Unicode and stored in * ScreenLinesUC[]. ScreenLines[] contains the first byte only. For an ASCII * character without composing chars ScreenLinesUC[] will be 0 and * ScreenLinesC[][] is not used. When the character occupies two display * cells the next byte in ScreenLines[] is 0. * ScreenLinesC[][] contain up to 'maxcombine' composing characters * (drawn on top of the first character). There is 0 after the last one used. * ScreenLines2[] is only used for euc-jp to store the second byte if the * first byte is 0x8e (single-width character). * * The screen_*() functions write to the screen and handle updating * ScreenLines[]. * * update_screen() is the function that updates all windows and status lines. * It is called form the main loop when must_redraw is non-zero. It may be * called from other places when an immediate screen update is needed. * * The part of the buffer that is displayed in a window is set with: * - w_topline (first buffer line in window) * - w_topfill (filler lines above the first line) * - w_leftcol (leftmost window cell in window), * - w_skipcol (skipped window cells of first line) * * Commands that only move the cursor around in a window, do not need to take * action to update the display. The main loop will check if w_topline is * valid and update it (scroll the window) when needed. * * Commands that scroll a window change w_topline and must call * check_cursor() to move the cursor into the visible part of the window, and * call redraw_later(VALID) to have the window displayed by update_screen() * later. * * Commands that change text in the buffer must call changed_bytes() or * changed_lines() to mark the area that changed and will require updating * later. The main loop will call update_screen(), which will update each * window that shows the changed buffer. This assumes text above the change * can remain displayed as it is. Text after the change may need updating for * scrolling, folding and syntax highlighting. * * Commands that change how a window is displayed (e.g., setting 'list') or * invalidate the contents of a window in another way (e.g., change fold * settings), must call redraw_later(NOT_VALID) to have the whole window * redisplayed by update_screen() later. * * Commands that change how a buffer is displayed (e.g., setting 'tabstop') * must call redraw_curbuf_later(NOT_VALID) to have all the windows for the * buffer redisplayed by update_screen() later. * * Commands that change highlighting and possibly cause a scroll too must call * redraw_later(SOME_VALID) to update the whole window but still use scrolling * to avoid redrawing everything. But the length of displayed lines must not * change, use NOT_VALID then. * * Commands that move the window position must call redraw_later(NOT_VALID). * TODO: should minimize redrawing by scrolling when possible. * * Commands that change everything (e.g., resizing the screen) must call * redraw_all_later(NOT_VALID) or redraw_all_later(CLEAR). * * Things that are handled indirectly: * - When messages scroll the screen up, msg_scrolled will be set and * update_screen() called to redraw. */ #include "vim.h" #define MB_FILLER_CHAR '<' /* character used when a double-width character * doesn't fit. */ /* * The attributes that are actually active for writing to the screen. */ static int screen_attr = 0; /* * Positioning the cursor is reduced by remembering the last position. * Mostly used by windgoto() and screen_char(). */ static int screen_cur_row, screen_cur_col; /* last known cursor position */ #ifdef FEAT_SEARCH_EXTRA static match_T search_hl; /* used for 'hlsearch' highlight matching */ #endif #ifdef FEAT_FOLDING static foldinfo_T win_foldinfo; /* info for 'foldcolumn' */ static int compute_foldcolumn __ARGS((win_T *wp, int col)); #endif /* * Buffer for one screen line (characters and attributes). */ static schar_T *current_ScreenLine; static void win_update __ARGS((win_T *wp)); static void win_draw_end __ARGS((win_T *wp, int c1, int c2, int row, int endrow, hlf_T hl)); #ifdef FEAT_FOLDING static void fold_line __ARGS((win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T lnum, int row)); static void fill_foldcolumn __ARGS((char_u *p, win_T *wp, int closed, linenr_T lnum)); static void copy_text_attr __ARGS((int off, char_u *buf, int len, int attr)); #endif static int win_line __ARGS((win_T *, linenr_T, int, int, int nochange)); static int char_needs_redraw __ARGS((int off_from, int off_to, int cols)); #ifdef FEAT_RIGHTLEFT static void screen_line __ARGS((int row, int coloff, int endcol, int clear_width, int rlflag)); # define SCREEN_LINE(r, o, e, c, rl) screen_line((r), (o), (e), (c), (rl)) #else static void screen_line __ARGS((int row, int coloff, int endcol, int clear_width)); # define SCREEN_LINE(r, o, e, c, rl) screen_line((r), (o), (e), (c)) #endif #ifdef FEAT_VERTSPLIT static void draw_vsep_win __ARGS((win_T *wp, int row)); #endif #ifdef FEAT_STL_OPT static void redraw_custom_statusline __ARGS((win_T *wp)); #endif #ifdef FEAT_SEARCH_EXTRA # define SEARCH_HL_PRIORITY 0 static void start_search_hl __ARGS((void)); static void end_search_hl __ARGS((void)); static void init_search_hl __ARGS((win_T *wp)); static void prepare_search_hl __ARGS((win_T *wp, linenr_T lnum)); static void next_search_hl __ARGS((win_T *win, match_T *shl, linenr_T lnum, colnr_T mincol, matchitem_T *cur)); static int next_search_hl_pos __ARGS((match_T *shl, linenr_T lnum, posmatch_T *pos, colnr_T mincol)); #endif static void screen_start_highlight __ARGS((int attr)); static void screen_char __ARGS((unsigned off, int row, int col)); #ifdef FEAT_MBYTE static void screen_char_2 __ARGS((unsigned off, int row, int col)); #endif static void screenclear2 __ARGS((void)); static void lineclear __ARGS((unsigned off, int width)); static void lineinvalid __ARGS((unsigned off, int width)); #ifdef FEAT_VERTSPLIT static void linecopy __ARGS((int to, int from, win_T *wp)); static void redraw_block __ARGS((int row, int end, win_T *wp)); #endif static int win_do_lines __ARGS((win_T *wp, int row, int line_count, int mayclear, int del)); static void win_rest_invalid __ARGS((win_T *wp)); static void msg_pos_mode __ARGS((void)); #if defined(FEAT_WINDOWS) static void draw_tabline __ARGS((void)); #endif #if defined(FEAT_WINDOWS) || defined(FEAT_WILDMENU) || defined(FEAT_STL_OPT) static int fillchar_status __ARGS((int *attr, int is_curwin)); #endif #ifdef FEAT_VERTSPLIT static int fillchar_vsep __ARGS((int *attr)); #endif #ifdef FEAT_STL_OPT static void win_redr_custom __ARGS((win_T *wp, int draw_ruler)); #endif #ifdef FEAT_CMDL_INFO static void win_redr_ruler __ARGS((win_T *wp, int always)); #endif #if defined(FEAT_CLIPBOARD) || defined(FEAT_VERTSPLIT) /* Ugly global: overrule attribute used by screen_char() */ static int screen_char_attr = 0; #endif /* * Redraw the current window later, with update_screen(type). * Set must_redraw only if not already set to a higher value. * e.g. if must_redraw is CLEAR, type NOT_VALID will do nothing. */ void redraw_later(type) int type; { redraw_win_later(curwin, type); } void redraw_win_later(wp, type) win_T *wp; int type; { if (wp->w_redr_type < type) { wp->w_redr_type = type; if (type >= NOT_VALID) wp->w_lines_valid = 0; if (must_redraw < type) /* must_redraw is the maximum of all windows */ must_redraw = type; } } /* * Force a complete redraw later. Also resets the highlighting. To be used * after executing a shell command that messes up the screen. */ void redraw_later_clear() { redraw_all_later(CLEAR); #ifdef FEAT_GUI if (gui.in_use) /* Use a code that will reset gui.highlight_mask in * gui_stop_highlight(). */ screen_attr = HL_ALL + 1; else #endif /* Use attributes that is very unlikely to appear in text. */ screen_attr = HL_BOLD | HL_UNDERLINE | HL_INVERSE; } /* * Mark all windows to be redrawn later. */ void redraw_all_later(type) int type; { win_T *wp; FOR_ALL_WINDOWS(wp) { redraw_win_later(wp, type); } } /* * Mark all windows that are editing the current buffer to be updated later. */ void redraw_curbuf_later(type) int type; { redraw_buf_later(curbuf, type); } void redraw_buf_later(buf, type) buf_T *buf; int type; { win_T *wp; FOR_ALL_WINDOWS(wp) { if (wp->w_buffer == buf) redraw_win_later(wp, type); } } /* * Redraw as soon as possible. When the command line is not scrolled redraw * right away and restore what was on the command line. * Return a code indicating what happened. */ int redraw_asap(type) int type; { int rows; int cols = screen_Columns; int r; int ret = 0; schar_T *screenline; /* copy from ScreenLines[] */ sattr_T *screenattr; /* copy from ScreenAttrs[] */ #ifdef FEAT_MBYTE int i; u8char_T *screenlineUC = NULL; /* copy from ScreenLinesUC[] */ u8char_T *screenlineC[MAX_MCO]; /* copy from ScreenLinesC[][] */ schar_T *screenline2 = NULL; /* copy from ScreenLines2[] */ #endif redraw_later(type); if (msg_scrolled || (State != NORMAL && State != NORMAL_BUSY) || exiting) return ret; /* Allocate space to save the text displayed in the command line area. */ rows = screen_Rows - cmdline_row; screenline = (schar_T *)lalloc( (long_u)(rows * cols * sizeof(schar_T)), FALSE); screenattr = (sattr_T *)lalloc( (long_u)(rows * cols * sizeof(sattr_T)), FALSE); if (screenline == NULL || screenattr == NULL) ret = 2; #ifdef FEAT_MBYTE if (enc_utf8) { screenlineUC = (u8char_T *)lalloc( (long_u)(rows * cols * sizeof(u8char_T)), FALSE); if (screenlineUC == NULL) ret = 2; for (i = 0; i < p_mco; ++i) { screenlineC[i] = (u8char_T *)lalloc( (long_u)(rows * cols * sizeof(u8char_T)), FALSE); if (screenlineC[i] == NULL) ret = 2; } } if (enc_dbcs == DBCS_JPNU) { screenline2 = (schar_T *)lalloc( (long_u)(rows * cols * sizeof(schar_T)), FALSE); if (screenline2 == NULL) ret = 2; } #endif if (ret != 2) { /* Save the text displayed in the command line area. */ for (r = 0; r < rows; ++r) { mch_memmove(screenline + r * cols, ScreenLines + LineOffset[cmdline_row + r], (size_t)cols * sizeof(schar_T)); mch_memmove(screenattr + r * cols, ScreenAttrs + LineOffset[cmdline_row + r], (size_t)cols * sizeof(sattr_T)); #ifdef FEAT_MBYTE if (enc_utf8) { mch_memmove(screenlineUC + r * cols, ScreenLinesUC + LineOffset[cmdline_row + r], (size_t)cols * sizeof(u8char_T)); for (i = 0; i < p_mco; ++i) mch_memmove(screenlineC[i] + r * cols, ScreenLinesC[i] + LineOffset[cmdline_row + r], (size_t)cols * sizeof(u8char_T)); } if (enc_dbcs == DBCS_JPNU) mch_memmove(screenline2 + r * cols, ScreenLines2 + LineOffset[cmdline_row + r], (size_t)cols * sizeof(schar_T)); #endif } update_screen(0); ret = 3; if (must_redraw == 0) { int off = (int)(current_ScreenLine - ScreenLines); /* Restore the text displayed in the command line area. */ for (r = 0; r < rows; ++r) { mch_memmove(current_ScreenLine, screenline + r * cols, (size_t)cols * sizeof(schar_T)); mch_memmove(ScreenAttrs + off, screenattr + r * cols, (size_t)cols * sizeof(sattr_T)); #ifdef FEAT_MBYTE if (enc_utf8) { mch_memmove(ScreenLinesUC + off, screenlineUC + r * cols, (size_t)cols * sizeof(u8char_T)); for (i = 0; i < p_mco; ++i) mch_memmove(ScreenLinesC[i] + off, screenlineC[i] + r * cols, (size_t)cols * sizeof(u8char_T)); } if (enc_dbcs == DBCS_JPNU) mch_memmove(ScreenLines2 + off, screenline2 + r * cols, (size_t)cols * sizeof(schar_T)); #endif SCREEN_LINE(cmdline_row + r, 0, cols, cols, FALSE); } ret = 4; } } vim_free(screenline); vim_free(screenattr); #ifdef FEAT_MBYTE if (enc_utf8) { vim_free(screenlineUC); for (i = 0; i < p_mco; ++i) vim_free(screenlineC[i]); } if (enc_dbcs == DBCS_JPNU) vim_free(screenline2); #endif /* Show the intro message when appropriate. */ maybe_intro_message(); setcursor(); return ret; } /* * Changed something in the current window, at buffer line "lnum", that * requires that line and possibly other lines to be redrawn. * Used when entering/leaving Insert mode with the cursor on a folded line. * Used to remove the "$" from a change command. * Note that when also inserting/deleting lines w_redraw_top and w_redraw_bot * may become invalid and the whole window will have to be redrawn. */ void redrawWinline(lnum, invalid) linenr_T lnum; int invalid UNUSED; /* window line height is invalid now */ { #ifdef FEAT_FOLDING int i; #endif if (curwin->w_redraw_top == 0 || curwin->w_redraw_top > lnum) curwin->w_redraw_top = lnum; if (curwin->w_redraw_bot == 0 || curwin->w_redraw_bot < lnum) curwin->w_redraw_bot = lnum; redraw_later(VALID); #ifdef FEAT_FOLDING if (invalid) { /* A w_lines[] entry for this lnum has become invalid. */ i = find_wl_entry(curwin, lnum); if (i >= 0) curwin->w_lines[i].wl_valid = FALSE; } #endif } /* * update all windows that are editing the current buffer */ void update_curbuf(type) int type; { redraw_curbuf_later(type); update_screen(type); } /* * update_screen() * * Based on the current value of curwin->w_topline, transfer a screenfull * of stuff from Filemem to ScreenLines[], and update curwin->w_botline. */ void update_screen(type) int type; { win_T *wp; static int did_intro = FALSE; #if defined(FEAT_SEARCH_EXTRA) || defined(FEAT_CLIPBOARD) int did_one; #endif /* Don't do anything if the screen structures are (not yet) valid. */ if (!screen_valid(TRUE)) return; if (must_redraw) { if (type < must_redraw) /* use maximal type */ type = must_redraw; /* must_redraw is reset here, so that when we run into some weird * reason to redraw while busy redrawing (e.g., asynchronous * scrolling), or update_topline() in win_update() will cause a * scroll, the screen will be redrawn later or in win_update(). */ must_redraw = 0; } /* Need to update w_lines[]. */ if (curwin->w_lines_valid == 0 && type < NOT_VALID) type = NOT_VALID; /* Postpone the redrawing when it's not needed and when being called * recursively. */ if (!redrawing() || updating_screen) { redraw_later(type); /* remember type for next time */ must_redraw = type; if (type > INVERTED_ALL) curwin->w_lines_valid = 0; /* don't use w_lines[].wl_size now */ return; } updating_screen = TRUE; #ifdef FEAT_SYN_HL ++display_tick; /* let syntax code know we're in a next round of * display updating */ #endif /* * if the screen was scrolled up when displaying a message, scroll it down */ if (msg_scrolled) { clear_cmdline = TRUE; if (msg_scrolled > Rows - 5) /* clearing is faster */ type = CLEAR; else if (type != CLEAR) { check_for_delay(FALSE); if (screen_ins_lines(0, 0, msg_scrolled, (int)Rows, NULL) == FAIL) type = CLEAR; FOR_ALL_WINDOWS(wp) { if (W_WINROW(wp) < msg_scrolled) { if (W_WINROW(wp) + wp->w_height > msg_scrolled && wp->w_redr_type < REDRAW_TOP && wp->w_lines_valid > 0 && wp->w_topline == wp->w_lines[0].wl_lnum) { wp->w_upd_rows = msg_scrolled - W_WINROW(wp); wp->w_redr_type = REDRAW_TOP; } else { wp->w_redr_type = NOT_VALID; #ifdef FEAT_WINDOWS if (W_WINROW(wp) + wp->w_height + W_STATUS_HEIGHT(wp) <= msg_scrolled) wp->w_redr_status = TRUE; #endif } } } redraw_cmdline = TRUE; #ifdef FEAT_WINDOWS redraw_tabline = TRUE; #endif } msg_scrolled = 0; need_wait_return = FALSE; } /* reset cmdline_row now (may have been changed temporarily) */ compute_cmdrow(); /* Check for changed highlighting */ if (need_highlight_changed) highlight_changed(); if (type == CLEAR) /* first clear screen */ { screenclear(); /* will reset clear_cmdline */ type = NOT_VALID; } if (clear_cmdline) /* going to clear cmdline (done below) */ check_for_delay(FALSE); #ifdef FEAT_LINEBREAK /* Force redraw when width of 'number' or 'relativenumber' column * changes. */ if (curwin->w_redr_type < NOT_VALID && curwin->w_nrwidth != ((curwin->w_p_nu || curwin->w_p_rnu) ? number_width(curwin) : 0)) curwin->w_redr_type = NOT_VALID; #endif /* * Only start redrawing if there is really something to do. */ if (type == INVERTED) update_curswant(); if (curwin->w_redr_type < type && !((type == VALID && curwin->w_lines[0].wl_valid #ifdef FEAT_DIFF && curwin->w_topfill == curwin->w_old_topfill && curwin->w_botfill == curwin->w_old_botfill #endif && curwin->w_topline == curwin->w_lines[0].wl_lnum) || (type == INVERTED && VIsual_active && curwin->w_old_cursor_lnum == curwin->w_cursor.lnum && curwin->w_old_visual_mode == VIsual_mode && (curwin->w_valid & VALID_VIRTCOL) && curwin->w_old_curswant == curwin->w_curswant) )) curwin->w_redr_type = type; #ifdef FEAT_WINDOWS /* Redraw the tab pages line if needed. */ if (redraw_tabline || type >= NOT_VALID) draw_tabline(); #endif #ifdef FEAT_SYN_HL /* * Correct stored syntax highlighting info for changes in each displayed * buffer. Each buffer must only be done once. */ FOR_ALL_WINDOWS(wp) { if (wp->w_buffer->b_mod_set) { # ifdef FEAT_WINDOWS win_T *wwp; /* Check if we already did this buffer. */ for (wwp = firstwin; wwp != wp; wwp = wwp->w_next) if (wwp->w_buffer == wp->w_buffer) break; # endif if ( # ifdef FEAT_WINDOWS wwp == wp && # endif syntax_present(wp)) syn_stack_apply_changes(wp->w_buffer); } } #endif /* * Go from top to bottom through the windows, redrawing the ones that need * it. */ #if defined(FEAT_SEARCH_EXTRA) || defined(FEAT_CLIPBOARD) did_one = FALSE; #endif #ifdef FEAT_SEARCH_EXTRA search_hl.rm.regprog = NULL; #endif FOR_ALL_WINDOWS(wp) { if (wp->w_redr_type != 0) { cursor_off(); #if defined(FEAT_SEARCH_EXTRA) || defined(FEAT_CLIPBOARD) if (!did_one) { did_one = TRUE; # ifdef FEAT_SEARCH_EXTRA start_search_hl(); # endif # ifdef FEAT_CLIPBOARD /* When Visual area changed, may have to update selection. */ if (clip_star.available && clip_isautosel_star()) clip_update_selection(&clip_star); if (clip_plus.available && clip_isautosel_plus()) clip_update_selection(&clip_plus); # endif #ifdef FEAT_GUI /* Remove the cursor before starting to do anything, because * scrolling may make it difficult to redraw the text under * it. */ if (gui.in_use) gui_undraw_cursor(); #endif } #endif win_update(wp); } #ifdef FEAT_WINDOWS /* redraw status line after the window to minimize cursor movement */ if (wp->w_redr_status) { cursor_off(); win_redr_status(wp); } #endif } #if defined(FEAT_SEARCH_EXTRA) end_search_hl(); #endif #ifdef FEAT_INS_EXPAND /* May need to redraw the popup menu. */ if (pum_visible()) pum_redraw(); #endif #ifdef FEAT_WINDOWS /* Reset b_mod_set flags. Going through all windows is probably faster * than going through all buffers (there could be many buffers). */ for (wp = firstwin; wp != NULL; wp = wp->w_next) wp->w_buffer->b_mod_set = FALSE; #else curbuf->b_mod_set = FALSE; #endif updating_screen = FALSE; #ifdef FEAT_GUI gui_may_resize_shell(); #endif /* Clear or redraw the command line. Done last, because scrolling may * mess up the command line. */ if (clear_cmdline || redraw_cmdline) showmode(); /* May put up an introductory message when not editing a file */ if (!did_intro) maybe_intro_message(); did_intro = TRUE; #ifdef FEAT_GUI /* Redraw the cursor and update the scrollbars when all screen updating is * done. */ if (gui.in_use) { out_flush(); /* required before updating the cursor */ if (did_one) gui_update_cursor(FALSE, FALSE); gui_update_scrollbars(FALSE); } #endif } #if defined(FEAT_CONCEAL) || defined(PROTO) /* * Return TRUE if the cursor line in window "wp" may be concealed, according * to the 'concealcursor' option. */ int conceal_cursor_line(wp) win_T *wp; { int c; if (*wp->w_p_cocu == NUL) return FALSE; if (get_real_state() & VISUAL) c = 'v'; else if (State & INSERT) c = 'i'; else if (State & NORMAL) c = 'n'; else if (State & CMDLINE) c = 'c'; else return FALSE; return vim_strchr(wp->w_p_cocu, c) != NULL; } /* * Check if the cursor line needs to be redrawn because of 'concealcursor'. */ void conceal_check_cursur_line() { if (curwin->w_p_cole > 0 && conceal_cursor_line(curwin)) { need_cursor_line_redraw = TRUE; /* Need to recompute cursor column, e.g., when starting Visual mode * without concealing. */ curs_columns(TRUE); } } void update_single_line(wp, lnum) win_T *wp; linenr_T lnum; { int row; int j; if (lnum >= wp->w_topline && lnum < wp->w_botline && foldedCount(wp, lnum, &win_foldinfo) == 0) { # ifdef FEAT_GUI /* Remove the cursor before starting to do anything, because scrolling * may make it difficult to redraw the text under it. */ if (gui.in_use) gui_undraw_cursor(); # endif row = 0; for (j = 0; j < wp->w_lines_valid; ++j) { if (lnum == wp->w_lines[j].wl_lnum) { screen_start(); /* not sure of screen cursor */ # ifdef FEAT_SEARCH_EXTRA init_search_hl(wp); start_search_hl(); prepare_search_hl(wp, lnum); # endif win_line(wp, lnum, row, row + wp->w_lines[j].wl_size, FALSE); # if defined(FEAT_SEARCH_EXTRA) end_search_hl(); # endif break; } row += wp->w_lines[j].wl_size; } # ifdef FEAT_GUI /* Redraw the cursor */ if (gui.in_use) { out_flush(); /* required before updating the cursor */ gui_update_cursor(FALSE, FALSE); } # endif } need_cursor_line_redraw = FALSE; } #endif #if defined(FEAT_SIGNS) || defined(FEAT_GUI) static void update_prepare __ARGS((void)); static void update_finish __ARGS((void)); /* * Prepare for updating one or more windows. * Caller must check for "updating_screen" already set to avoid recursiveness. */ static void update_prepare() { cursor_off(); updating_screen = TRUE; #ifdef FEAT_GUI /* Remove the cursor before starting to do anything, because scrolling may * make it difficult to redraw the text under it. */ if (gui.in_use) gui_undraw_cursor(); #endif #ifdef FEAT_SEARCH_EXTRA start_search_hl(); #endif } /* * Finish updating one or more windows. */ static void update_finish() { if (redraw_cmdline) showmode(); # ifdef FEAT_SEARCH_EXTRA end_search_hl(); # endif updating_screen = FALSE; # ifdef FEAT_GUI gui_may_resize_shell(); /* Redraw the cursor and update the scrollbars when all screen updating is * done. */ if (gui.in_use) { out_flush(); /* required before updating the cursor */ gui_update_cursor(FALSE, FALSE); gui_update_scrollbars(FALSE); } # endif } #endif #if defined(FEAT_SIGNS) || defined(PROTO) void update_debug_sign(buf, lnum) buf_T *buf; linenr_T lnum; { win_T *wp; int doit = FALSE; # ifdef FEAT_FOLDING win_foldinfo.fi_level = 0; # endif /* update/delete a specific mark */ FOR_ALL_WINDOWS(wp) { if (buf != NULL && lnum > 0) { if (wp->w_buffer == buf && lnum >= wp->w_topline && lnum < wp->w_botline) { if (wp->w_redraw_top == 0 || wp->w_redraw_top > lnum) wp->w_redraw_top = lnum; if (wp->w_redraw_bot == 0 || wp->w_redraw_bot < lnum) wp->w_redraw_bot = lnum; redraw_win_later(wp, VALID); } } else redraw_win_later(wp, VALID); if (wp->w_redr_type != 0) doit = TRUE; } /* Return when there is nothing to do, screen updating is already * happening (recursive call) or still starting up. */ if (!doit || updating_screen #ifdef FEAT_GUI || gui.starting #endif || starting) return; /* update all windows that need updating */ update_prepare(); # ifdef FEAT_WINDOWS for (wp = firstwin; wp; wp = wp->w_next) { if (wp->w_redr_type != 0) win_update(wp); if (wp->w_redr_status) win_redr_status(wp); } # else if (curwin->w_redr_type != 0) win_update(curwin); # endif update_finish(); } #endif #if defined(FEAT_GUI) || defined(PROTO) /* * Update a single window, its status line and maybe the command line msg. * Used for the GUI scrollbar. */ void updateWindow(wp) win_T *wp; { /* return if already busy updating */ if (updating_screen) return; update_prepare(); #ifdef FEAT_CLIPBOARD /* When Visual area changed, may have to update selection. */ if (clip_star.available && clip_isautosel_star()) clip_update_selection(&clip_star); if (clip_plus.available && clip_isautosel_plus()) clip_update_selection(&clip_plus); #endif win_update(wp); #ifdef FEAT_WINDOWS /* When the screen was cleared redraw the tab pages line. */ if (redraw_tabline) draw_tabline(); if (wp->w_redr_status # ifdef FEAT_CMDL_INFO || p_ru # endif # ifdef FEAT_STL_OPT || *p_stl != NUL || *wp->w_p_stl != NUL # endif ) win_redr_status(wp); #endif update_finish(); } #endif /* * Update a single window. * * This may cause the windows below it also to be redrawn (when clearing the * screen or scrolling lines). * * How the window is redrawn depends on wp->w_redr_type. Each type also * implies the one below it. * NOT_VALID redraw the whole window * SOME_VALID redraw the whole window but do scroll when possible * REDRAW_TOP redraw the top w_upd_rows window lines, otherwise like VALID * INVERTED redraw the changed part of the Visual area * INVERTED_ALL redraw the whole Visual area * VALID 1. scroll up/down to adjust for a changed w_topline * 2. update lines at the top when scrolled down * 3. redraw changed text: * - if wp->w_buffer->b_mod_set set, update lines between * b_mod_top and b_mod_bot. * - if wp->w_redraw_top non-zero, redraw lines between * wp->w_redraw_top and wp->w_redr_bot. * - continue redrawing when syntax status is invalid. * 4. if scrolled up, update lines at the bottom. * This results in three areas that may need updating: * top: from first row to top_end (when scrolled down) * mid: from mid_start to mid_end (update inversion or changed text) * bot: from bot_start to last row (when scrolled up) */ static void win_update(wp) win_T *wp; { buf_T *buf = wp->w_buffer; int type; int top_end = 0; /* Below last row of the top area that needs updating. 0 when no top area updating. */ int mid_start = 999;/* first row of the mid area that needs updating. 999 when no mid area updating. */ int mid_end = 0; /* Below last row of the mid area that needs updating. 0 when no mid area updating. */ int bot_start = 999;/* first row of the bot area that needs updating. 999 when no bot area updating */ int scrolled_down = FALSE; /* TRUE when scrolled down when w_topline got smaller a bit */ #ifdef FEAT_SEARCH_EXTRA matchitem_T *cur; /* points to the match list */ int top_to_mod = FALSE; /* redraw above mod_top */ #endif int row; /* current window row to display */ linenr_T lnum; /* current buffer lnum to display */ int idx; /* current index in w_lines[] */ int srow; /* starting row of the current line */ int eof = FALSE; /* if TRUE, we hit the end of the file */ int didline = FALSE; /* if TRUE, we finished the last line */ int i; long j; static int recursive = FALSE; /* being called recursively */ int old_botline = wp->w_botline; #ifdef FEAT_FOLDING long fold_count; #endif #ifdef FEAT_SYN_HL /* remember what happened to the previous line, to know if * check_visual_highlight() can be used */ #define DID_NONE 1 /* didn't update a line */ #define DID_LINE 2 /* updated a normal line */ #define DID_FOLD 3 /* updated a folded line */ int did_update = DID_NONE; linenr_T syntax_last_parsed = 0; /* last parsed text line */ #endif linenr_T mod_top = 0; linenr_T mod_bot = 0; #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) int save_got_int; #endif type = wp->w_redr_type; if (type == NOT_VALID) { #ifdef FEAT_WINDOWS wp->w_redr_status = TRUE; #endif wp->w_lines_valid = 0; } /* Window is zero-height: nothing to draw. */ if (wp->w_height == 0) { wp->w_redr_type = 0; return; } #ifdef FEAT_VERTSPLIT /* Window is zero-width: Only need to draw the separator. */ if (wp->w_width == 0) { /* draw the vertical separator right of this window */ draw_vsep_win(wp, 0); wp->w_redr_type = 0; return; } #endif #ifdef FEAT_SEARCH_EXTRA init_search_hl(wp); #endif #ifdef FEAT_LINEBREAK /* Force redraw when width of 'number' or 'relativenumber' column * changes. */ i = (wp->w_p_nu || wp->w_p_rnu) ? number_width(wp) : 0; if (wp->w_nrwidth != i) { type = NOT_VALID; wp->w_nrwidth = i; } else #endif if (buf->b_mod_set && buf->b_mod_xlines != 0 && wp->w_redraw_top != 0) { /* * When there are both inserted/deleted lines and specific lines to be * redrawn, w_redraw_top and w_redraw_bot may be invalid, just redraw * everything (only happens when redrawing is off for while). */ type = NOT_VALID; } else { /* * Set mod_top to the first line that needs displaying because of * changes. Set mod_bot to the first line after the changes. */ mod_top = wp->w_redraw_top; if (wp->w_redraw_bot != 0) mod_bot = wp->w_redraw_bot + 1; else mod_bot = 0; wp->w_redraw_top = 0; /* reset for next time */ wp->w_redraw_bot = 0; if (buf->b_mod_set) { if (mod_top == 0 || mod_top > buf->b_mod_top) { mod_top = buf->b_mod_top; #ifdef FEAT_SYN_HL /* Need to redraw lines above the change that may be included * in a pattern match. */ if (syntax_present(wp)) { mod_top -= buf->b_s.b_syn_sync_linebreaks; if (mod_top < 1) mod_top = 1; } #endif } if (mod_bot == 0 || mod_bot < buf->b_mod_bot) mod_bot = buf->b_mod_bot; #ifdef FEAT_SEARCH_EXTRA /* When 'hlsearch' is on and using a multi-line search pattern, a * change in one line may make the Search highlighting in a * previous line invalid. Simple solution: redraw all visible * lines above the change. * Same for a match pattern. */ if (search_hl.rm.regprog != NULL && re_multiline(search_hl.rm.regprog)) top_to_mod = TRUE; else { cur = wp->w_match_head; while (cur != NULL) { if (cur->match.regprog != NULL && re_multiline(cur->match.regprog)) { top_to_mod = TRUE; break; } cur = cur->next; } } #endif } #ifdef FEAT_FOLDING if (mod_top != 0 && hasAnyFolding(wp)) { linenr_T lnumt, lnumb; /* * A change in a line can cause lines above it to become folded or * unfolded. Find the top most buffer line that may be affected. * If the line was previously folded and displayed, get the first * line of that fold. If the line is folded now, get the first * folded line. Use the minimum of these two. */ /* Find last valid w_lines[] entry above mod_top. Set lnumt to * the line below it. If there is no valid entry, use w_topline. * Find the first valid w_lines[] entry below mod_bot. Set lnumb * to this line. If there is no valid entry, use MAXLNUM. */ lnumt = wp->w_topline; lnumb = MAXLNUM; for (i = 0; i < wp->w_lines_valid; ++i) if (wp->w_lines[i].wl_valid) { if (wp->w_lines[i].wl_lastlnum < mod_top) lnumt = wp->w_lines[i].wl_lastlnum + 1; if (lnumb == MAXLNUM && wp->w_lines[i].wl_lnum >= mod_bot) { lnumb = wp->w_lines[i].wl_lnum; /* When there is a fold column it might need updating * in the next line ("J" just above an open fold). */ if (compute_foldcolumn(wp, 0) > 0) ++lnumb; } } (void)hasFoldingWin(wp, mod_top, &mod_top, NULL, TRUE, NULL); if (mod_top > lnumt) mod_top = lnumt; /* Now do the same for the bottom line (one above mod_bot). */ --mod_bot; (void)hasFoldingWin(wp, mod_bot, NULL, &mod_bot, TRUE, NULL); ++mod_bot; if (mod_bot < lnumb) mod_bot = lnumb; } #endif /* When a change starts above w_topline and the end is below * w_topline, start redrawing at w_topline. * If the end of the change is above w_topline: do like no change was * made, but redraw the first line to find changes in syntax. */ if (mod_top != 0 && mod_top < wp->w_topline) { if (mod_bot > wp->w_topline) mod_top = wp->w_topline; #ifdef FEAT_SYN_HL else if (syntax_present(wp)) top_end = 1; #endif } /* When line numbers are displayed need to redraw all lines below * inserted/deleted lines. */ if (mod_top != 0 && buf->b_mod_xlines != 0 && wp->w_p_nu) mod_bot = MAXLNUM; } /* * When only displaying the lines at the top, set top_end. Used when * window has scrolled down for msg_scrolled. */ if (type == REDRAW_TOP) { j = 0; for (i = 0; i < wp->w_lines_valid; ++i) { j += wp->w_lines[i].wl_size; if (j >= wp->w_upd_rows) { top_end = j; break; } } if (top_end == 0) /* not found (cannot happen?): redraw everything */ type = NOT_VALID; else /* top area defined, the rest is VALID */ type = VALID; } /* Trick: we want to avoid clearing the screen twice. screenclear() will * set "screen_cleared" to TRUE. The special value MAYBE (which is still * non-zero and thus not FALSE) will indicate that screenclear() was not * called. */ if (screen_cleared) screen_cleared = MAYBE; /* * If there are no changes on the screen that require a complete redraw, * handle three cases: * 1: we are off the top of the screen by a few lines: scroll down * 2: wp->w_topline is below wp->w_lines[0].wl_lnum: may scroll up * 3: wp->w_topline is wp->w_lines[0].wl_lnum: find first entry in * w_lines[] that needs updating. */ if ((type == VALID || type == SOME_VALID || type == INVERTED || type == INVERTED_ALL) #ifdef FEAT_DIFF && !wp->w_botfill && !wp->w_old_botfill #endif ) { if (mod_top != 0 && wp->w_topline == mod_top) { /* * w_topline is the first changed line, the scrolling will be done * further down. */ } else if (wp->w_lines[0].wl_valid && (wp->w_topline < wp->w_lines[0].wl_lnum #ifdef FEAT_DIFF || (wp->w_topline == wp->w_lines[0].wl_lnum && wp->w_topfill > wp->w_old_topfill) #endif )) { /* * New topline is above old topline: May scroll down. */ #ifdef FEAT_FOLDING if (hasAnyFolding(wp)) { linenr_T ln; /* count the number of lines we are off, counting a sequence * of folded lines as one */ j = 0; for (ln = wp->w_topline; ln < wp->w_lines[0].wl_lnum; ++ln) { ++j; if (j >= wp->w_height - 2) break; (void)hasFoldingWin(wp, ln, NULL, &ln, TRUE, NULL); } } else #endif j = wp->w_lines[0].wl_lnum - wp->w_topline; if (j < wp->w_height - 2) /* not too far off */ { i = plines_m_win(wp, wp->w_topline, wp->w_lines[0].wl_lnum - 1); #ifdef FEAT_DIFF /* insert extra lines for previously invisible filler lines */ if (wp->w_lines[0].wl_lnum != wp->w_topline) i += diff_check_fill(wp, wp->w_lines[0].wl_lnum) - wp->w_old_topfill; #endif if (i < wp->w_height - 2) /* less than a screen off */ { /* * Try to insert the correct number of lines. * If not the last window, delete the lines at the bottom. * win_ins_lines may fail when the terminal can't do it. */ if (i > 0) check_for_delay(FALSE); if (win_ins_lines(wp, 0, i, FALSE, wp == firstwin) == OK) { if (wp->w_lines_valid != 0) { /* Need to update rows that are new, stop at the * first one that scrolled down. */ top_end = i; scrolled_down = TRUE; /* Move the entries that were scrolled, disable * the entries for the lines to be redrawn. */ if ((wp->w_lines_valid += j) > wp->w_height) wp->w_lines_valid = wp->w_height; for (idx = wp->w_lines_valid; idx - j >= 0; idx--) wp->w_lines[idx] = wp->w_lines[idx - j]; while (idx >= 0) wp->w_lines[idx--].wl_valid = FALSE; } } else mid_start = 0; /* redraw all lines */ } else mid_start = 0; /* redraw all lines */ } else mid_start = 0; /* redraw all lines */ } else { /* * New topline is at or below old topline: May scroll up. * When topline didn't change, find first entry in w_lines[] that * needs updating. */ /* try to find wp->w_topline in wp->w_lines[].wl_lnum */ j = -1; row = 0; for (i = 0; i < wp->w_lines_valid; i++) { if (wp->w_lines[i].wl_valid && wp->w_lines[i].wl_lnum == wp->w_topline) { j = i; break; } row += wp->w_lines[i].wl_size; } if (j == -1) { /* if wp->w_topline is not in wp->w_lines[].wl_lnum redraw all * lines */ mid_start = 0; } else { /* * Try to delete the correct number of lines. * wp->w_topline is at wp->w_lines[i].wl_lnum. */ #ifdef FEAT_DIFF /* If the topline didn't change, delete old filler lines, * otherwise delete filler lines of the new topline... */ if (wp->w_lines[0].wl_lnum == wp->w_topline) row += wp->w_old_topfill; else row += diff_check_fill(wp, wp->w_topline); /* ... but don't delete new filler lines. */ row -= wp->w_topfill; #endif if (row > 0) { check_for_delay(FALSE); if (win_del_lines(wp, 0, row, FALSE, wp == firstwin) == OK) bot_start = wp->w_height - row; else mid_start = 0; /* redraw all lines */ } if ((row == 0 || bot_start < 999) && wp->w_lines_valid != 0) { /* * Skip the lines (below the deleted lines) that are still * valid and don't need redrawing. Copy their info * upwards, to compensate for the deleted lines. Set * bot_start to the first row that needs redrawing. */ bot_start = 0; idx = 0; for (;;) { wp->w_lines[idx] = wp->w_lines[j]; /* stop at line that didn't fit, unless it is still * valid (no lines deleted) */ if (row > 0 && bot_start + row + (int)wp->w_lines[j].wl_size > wp->w_height) { wp->w_lines_valid = idx + 1; break; } bot_start += wp->w_lines[idx++].wl_size; /* stop at the last valid entry in w_lines[].wl_size */ if (++j >= wp->w_lines_valid) { wp->w_lines_valid = idx; break; } } #ifdef FEAT_DIFF /* Correct the first entry for filler lines at the top * when it won't get updated below. */ if (wp->w_p_diff && bot_start > 0) wp->w_lines[0].wl_size = plines_win_nofill(wp, wp->w_topline, TRUE) + wp->w_topfill; #endif } } } /* When starting redraw in the first line, redraw all lines. When * there is only one window it's probably faster to clear the screen * first. */ if (mid_start == 0) { mid_end = wp->w_height; if (lastwin == firstwin) { /* Clear the screen when it was not done by win_del_lines() or * win_ins_lines() above, "screen_cleared" is FALSE or MAYBE * then. */ if (screen_cleared != TRUE) screenclear(); #ifdef FEAT_WINDOWS /* The screen was cleared, redraw the tab pages line. */ if (redraw_tabline) draw_tabline(); #endif } } /* When win_del_lines() or win_ins_lines() caused the screen to be * cleared (only happens for the first window) or when screenclear() * was called directly above, "must_redraw" will have been set to * NOT_VALID, need to reset it here to avoid redrawing twice. */ if (screen_cleared == TRUE) must_redraw = 0; } else { /* Not VALID or INVERTED: redraw all lines. */ mid_start = 0; mid_end = wp->w_height; } if (type == SOME_VALID) { /* SOME_VALID: redraw all lines. */ mid_start = 0; mid_end = wp->w_height; type = NOT_VALID; } /* check if we are updating or removing the inverted part */ if ((VIsual_active && buf == curwin->w_buffer) || (wp->w_old_cursor_lnum != 0 && type != NOT_VALID)) { linenr_T from, to; if (VIsual_active) { if (VIsual_active && (VIsual_mode != wp->w_old_visual_mode || type == INVERTED_ALL)) { /* * If the type of Visual selection changed, redraw the whole * selection. Also when the ownership of the X selection is * gained or lost. */ if (curwin->w_cursor.lnum < VIsual.lnum) { from = curwin->w_cursor.lnum; to = VIsual.lnum; } else { from = VIsual.lnum; to = curwin->w_cursor.lnum; } /* redraw more when the cursor moved as well */ if (wp->w_old_cursor_lnum < from) from = wp->w_old_cursor_lnum; if (wp->w_old_cursor_lnum > to) to = wp->w_old_cursor_lnum; if (wp->w_old_visual_lnum < from) from = wp->w_old_visual_lnum; if (wp->w_old_visual_lnum > to) to = wp->w_old_visual_lnum; } else { /* * Find the line numbers that need to be updated: The lines * between the old cursor position and the current cursor * position. Also check if the Visual position changed. */ if (curwin->w_cursor.lnum < wp->w_old_cursor_lnum) { from = curwin->w_cursor.lnum; to = wp->w_old_cursor_lnum; } else { from = wp->w_old_cursor_lnum; to = curwin->w_cursor.lnum; if (from == 0) /* Visual mode just started */ from = to; } if (VIsual.lnum != wp->w_old_visual_lnum || VIsual.col != wp->w_old_visual_col) { if (wp->w_old_visual_lnum < from && wp->w_old_visual_lnum != 0) from = wp->w_old_visual_lnum; if (wp->w_old_visual_lnum > to) to = wp->w_old_visual_lnum; if (VIsual.lnum < from) from = VIsual.lnum; if (VIsual.lnum > to) to = VIsual.lnum; } } /* * If in block mode and changed column or curwin->w_curswant: * update all lines. * First compute the actual start and end column. */ if (VIsual_mode == Ctrl_V) { colnr_T fromc, toc; #if defined(FEAT_VIRTUALEDIT) && defined(FEAT_LINEBREAK) int save_ve_flags = ve_flags; if (curwin->w_p_lbr) ve_flags = VE_ALL; #endif getvcols(wp, &VIsual, &curwin->w_cursor, &fromc, &toc); #if defined(FEAT_VIRTUALEDIT) && defined(FEAT_LINEBREAK) ve_flags = save_ve_flags; #endif ++toc; if (curwin->w_curswant == MAXCOL) toc = MAXCOL; if (fromc != wp->w_old_cursor_fcol || toc != wp->w_old_cursor_lcol) { if (from > VIsual.lnum) from = VIsual.lnum; if (to < VIsual.lnum) to = VIsual.lnum; } wp->w_old_cursor_fcol = fromc; wp->w_old_cursor_lcol = toc; } } else { /* Use the line numbers of the old Visual area. */ if (wp->w_old_cursor_lnum < wp->w_old_visual_lnum) { from = wp->w_old_cursor_lnum; to = wp->w_old_visual_lnum; } else { from = wp->w_old_visual_lnum; to = wp->w_old_cursor_lnum; } } /* * There is no need to update lines above the top of the window. */ if (from < wp->w_topline) from = wp->w_topline; /* * If we know the value of w_botline, use it to restrict the update to * the lines that are visible in the window. */ if (wp->w_valid & VALID_BOTLINE) { if (from >= wp->w_botline) from = wp->w_botline - 1; if (to >= wp->w_botline) to = wp->w_botline - 1; } /* * Find the minimal part to be updated. * Watch out for scrolling that made entries in w_lines[] invalid. * E.g., CTRL-U makes the first half of w_lines[] invalid and sets * top_end; need to redraw from top_end to the "to" line. * A middle mouse click with a Visual selection may change the text * above the Visual area and reset wl_valid, do count these for * mid_end (in srow). */ if (mid_start > 0) { lnum = wp->w_topline; idx = 0; srow = 0; if (scrolled_down) mid_start = top_end; else mid_start = 0; while (lnum < from && idx < wp->w_lines_valid) /* find start */ { if (wp->w_lines[idx].wl_valid) mid_start += wp->w_lines[idx].wl_size; else if (!scrolled_down) srow += wp->w_lines[idx].wl_size; ++idx; # ifdef FEAT_FOLDING if (idx < wp->w_lines_valid && wp->w_lines[idx].wl_valid) lnum = wp->w_lines[idx].wl_lnum; else # endif ++lnum; } srow += mid_start; mid_end = wp->w_height; for ( ; idx < wp->w_lines_valid; ++idx) /* find end */ { if (wp->w_lines[idx].wl_valid && wp->w_lines[idx].wl_lnum >= to + 1) { /* Only update until first row of this line */ mid_end = srow; break; } srow += wp->w_lines[idx].wl_size; } } } if (VIsual_active && buf == curwin->w_buffer) { wp->w_old_visual_mode = VIsual_mode; wp->w_old_cursor_lnum = curwin->w_cursor.lnum; wp->w_old_visual_lnum = VIsual.lnum; wp->w_old_visual_col = VIsual.col; wp->w_old_curswant = curwin->w_curswant; } else { wp->w_old_visual_mode = 0; wp->w_old_cursor_lnum = 0; wp->w_old_visual_lnum = 0; wp->w_old_visual_col = 0; } #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) /* reset got_int, otherwise regexp won't work */ save_got_int = got_int; got_int = 0; #endif #ifdef FEAT_FOLDING win_foldinfo.fi_level = 0; #endif /* * Update all the window rows. */ idx = 0; /* first entry in w_lines[].wl_size */ row = 0; srow = 0; lnum = wp->w_topline; /* first line shown in window */ for (;;) { /* stop updating when reached the end of the window (check for _past_ * the end of the window is at the end of the loop) */ if (row == wp->w_height) { didline = TRUE; break; } /* stop updating when hit the end of the file */ if (lnum > buf->b_ml.ml_line_count) { eof = TRUE; break; } /* Remember the starting row of the line that is going to be dealt * with. It is used further down when the line doesn't fit. */ srow = row; /* * Update a line when it is in an area that needs updating, when it * has changes or w_lines[idx] is invalid. * bot_start may be halfway a wrapped line after using * win_del_lines(), check if the current line includes it. * When syntax folding is being used, the saved syntax states will * already have been updated, we can't see where the syntax state is * the same again, just update until the end of the window. */ if (row < top_end || (row >= mid_start && row < mid_end) #ifdef FEAT_SEARCH_EXTRA || top_to_mod #endif || idx >= wp->w_lines_valid || (row + wp->w_lines[idx].wl_size > bot_start) || (mod_top != 0 && (lnum == mod_top || (lnum >= mod_top && (lnum < mod_bot #ifdef FEAT_SYN_HL || did_update == DID_FOLD || (did_update == DID_LINE && syntax_present(wp) && ( # ifdef FEAT_FOLDING (foldmethodIsSyntax(wp) && hasAnyFolding(wp)) || # endif syntax_check_changed(lnum))) #endif #ifdef FEAT_SEARCH_EXTRA /* match in fixed position might need redraw * if lines were inserted or deleted */ || (wp->w_match_head != NULL && buf->b_mod_xlines != 0) #endif ))))) { #ifdef FEAT_SEARCH_EXTRA if (lnum == mod_top) top_to_mod = FALSE; #endif /* * When at start of changed lines: May scroll following lines * up or down to minimize redrawing. * Don't do this when the change continues until the end. * Don't scroll when dollar_vcol >= 0, keep the "$". */ if (lnum == mod_top && mod_bot != MAXLNUM && !(dollar_vcol >= 0 && mod_bot == mod_top + 1)) { int old_rows = 0; int new_rows = 0; int xtra_rows; linenr_T l; /* Count the old number of window rows, using w_lines[], which * should still contain the sizes for the lines as they are * currently displayed. */ for (i = idx; i < wp->w_lines_valid; ++i) { /* Only valid lines have a meaningful wl_lnum. Invalid * lines are part of the changed area. */ if (wp->w_lines[i].wl_valid && wp->w_lines[i].wl_lnum == mod_bot) break; old_rows += wp->w_lines[i].wl_size; #ifdef FEAT_FOLDING if (wp->w_lines[i].wl_valid && wp->w_lines[i].wl_lastlnum + 1 == mod_bot) { /* Must have found the last valid entry above mod_bot. * Add following invalid entries. */ ++i; while (i < wp->w_lines_valid && !wp->w_lines[i].wl_valid) old_rows += wp->w_lines[i++].wl_size; break; } #endif } if (i >= wp->w_lines_valid) { /* We can't find a valid line below the changed lines, * need to redraw until the end of the window. * Inserting/deleting lines has no use. */ bot_start = 0; } else { /* Able to count old number of rows: Count new window * rows, and may insert/delete lines */ j = idx; for (l = lnum; l < mod_bot; ++l) { #ifdef FEAT_FOLDING if (hasFoldingWin(wp, l, NULL, &l, TRUE, NULL)) ++new_rows; else #endif #ifdef FEAT_DIFF if (l == wp->w_topline) new_rows += plines_win_nofill(wp, l, TRUE) + wp->w_topfill; else #endif new_rows += plines_win(wp, l, TRUE); ++j; if (new_rows > wp->w_height - row - 2) { /* it's getting too much, must redraw the rest */ new_rows = 9999; break; } } xtra_rows = new_rows - old_rows; if (xtra_rows < 0) { /* May scroll text up. If there is not enough * remaining text or scrolling fails, must redraw the * rest. If scrolling works, must redraw the text * below the scrolled text. */ if (row - xtra_rows >= wp->w_height - 2) mod_bot = MAXLNUM; else { check_for_delay(FALSE); if (win_del_lines(wp, row, -xtra_rows, FALSE, FALSE) == FAIL) mod_bot = MAXLNUM; else bot_start = wp->w_height + xtra_rows; } } else if (xtra_rows > 0) { /* May scroll text down. If there is not enough * remaining text of scrolling fails, must redraw the * rest. */ if (row + xtra_rows >= wp->w_height - 2) mod_bot = MAXLNUM; else { check_for_delay(FALSE); if (win_ins_lines(wp, row + old_rows, xtra_rows, FALSE, FALSE) == FAIL) mod_bot = MAXLNUM; else if (top_end > row + old_rows) /* Scrolled the part at the top that requires * updating down. */ top_end += xtra_rows; } } /* When not updating the rest, may need to move w_lines[] * entries. */ if (mod_bot != MAXLNUM && i != j) { if (j < i) { int x = row + new_rows; /* move entries in w_lines[] upwards */ for (;;) { /* stop at last valid entry in w_lines[] */ if (i >= wp->w_lines_valid) { wp->w_lines_valid = j; break; } wp->w_lines[j] = wp->w_lines[i]; /* stop at a line that won't fit */ if (x + (int)wp->w_lines[j].wl_size > wp->w_height) { wp->w_lines_valid = j + 1; break; } x += wp->w_lines[j++].wl_size; ++i; } if (bot_start > x) bot_start = x; } else /* j > i */ { /* move entries in w_lines[] downwards */ j -= i; wp->w_lines_valid += j; if (wp->w_lines_valid > wp->w_height) wp->w_lines_valid = wp->w_height; for (i = wp->w_lines_valid; i - j >= idx; --i) wp->w_lines[i] = wp->w_lines[i - j]; /* The w_lines[] entries for inserted lines are * now invalid, but wl_size may be used above. * Reset to zero. */ while (i >= idx) { wp->w_lines[i].wl_size = 0; wp->w_lines[i--].wl_valid = FALSE; } } } } } #ifdef FEAT_FOLDING /* * When lines are folded, display one line for all of them. * Otherwise, display normally (can be several display lines when * 'wrap' is on). */ fold_count = foldedCount(wp, lnum, &win_foldinfo); if (fold_count != 0) { fold_line(wp, fold_count, &win_foldinfo, lnum, row); ++row; --fold_count; wp->w_lines[idx].wl_folded = TRUE; wp->w_lines[idx].wl_lastlnum = lnum + fold_count; # ifdef FEAT_SYN_HL did_update = DID_FOLD; # endif } else #endif if (idx < wp->w_lines_valid && wp->w_lines[idx].wl_valid && wp->w_lines[idx].wl_lnum == lnum && lnum > wp->w_topline && !(dy_flags & DY_LASTLINE) && srow + wp->w_lines[idx].wl_size > wp->w_height #ifdef FEAT_DIFF && diff_check_fill(wp, lnum) == 0 #endif ) { /* This line is not going to fit. Don't draw anything here, * will draw "@ " lines below. */ row = wp->w_height + 1; } else { #ifdef FEAT_SEARCH_EXTRA prepare_search_hl(wp, lnum); #endif #ifdef FEAT_SYN_HL /* Let the syntax stuff know we skipped a few lines. */ if (syntax_last_parsed != 0 && syntax_last_parsed + 1 < lnum && syntax_present(wp)) syntax_end_parsing(syntax_last_parsed + 1); #endif /* * Display one line. */ row = win_line(wp, lnum, srow, wp->w_height, mod_top == 0); #ifdef FEAT_FOLDING wp->w_lines[idx].wl_folded = FALSE; wp->w_lines[idx].wl_lastlnum = lnum; #endif #ifdef FEAT_SYN_HL did_update = DID_LINE; syntax_last_parsed = lnum; #endif } wp->w_lines[idx].wl_lnum = lnum; wp->w_lines[idx].wl_valid = TRUE; if (row > wp->w_height) /* past end of screen */ { /* we may need the size of that too long line later on */ if (dollar_vcol == -1) wp->w_lines[idx].wl_size = plines_win(wp, lnum, TRUE); ++idx; break; } if (dollar_vcol == -1) wp->w_lines[idx].wl_size = row - srow; ++idx; #ifdef FEAT_FOLDING lnum += fold_count + 1; #else ++lnum; #endif } else { /* This line does not need updating, advance to the next one */ row += wp->w_lines[idx++].wl_size; if (row > wp->w_height) /* past end of screen */ break; #ifdef FEAT_FOLDING lnum = wp->w_lines[idx - 1].wl_lastlnum + 1; #else ++lnum; #endif #ifdef FEAT_SYN_HL did_update = DID_NONE; #endif } if (lnum > buf->b_ml.ml_line_count) { eof = TRUE; break; } } /* * End of loop over all window lines. */ if (idx > wp->w_lines_valid) wp->w_lines_valid = idx; #ifdef FEAT_SYN_HL /* * Let the syntax stuff know we stop parsing here. */ if (syntax_last_parsed != 0 && syntax_present(wp)) syntax_end_parsing(syntax_last_parsed + 1); #endif /* * If we didn't hit the end of the file, and we didn't finish the last * line we were working on, then the line didn't fit. */ wp->w_empty_rows = 0; #ifdef FEAT_DIFF wp->w_filler_rows = 0; #endif if (!eof && !didline) { if (lnum == wp->w_topline) { /* * Single line that does not fit! * Don't overwrite it, it can be edited. */ wp->w_botline = lnum + 1; } #ifdef FEAT_DIFF else if (diff_check_fill(wp, lnum) >= wp->w_height - srow) { /* Window ends in filler lines. */ wp->w_botline = lnum; wp->w_filler_rows = wp->w_height - srow; } #endif else if (dy_flags & DY_LASTLINE) /* 'display' has "lastline" */ { /* * Last line isn't finished: Display "@@@" at the end. */ screen_fill(W_WINROW(wp) + wp->w_height - 1, W_WINROW(wp) + wp->w_height, (int)W_ENDCOL(wp) - 3, (int)W_ENDCOL(wp), '@', '@', hl_attr(HLF_AT)); set_empty_rows(wp, srow); wp->w_botline = lnum; } else { win_draw_end(wp, '@', ' ', srow, wp->w_height, HLF_AT); wp->w_botline = lnum; } } else { #ifdef FEAT_VERTSPLIT draw_vsep_win(wp, row); #endif if (eof) /* we hit the end of the file */ { wp->w_botline = buf->b_ml.ml_line_count + 1; #ifdef FEAT_DIFF j = diff_check_fill(wp, wp->w_botline); if (j > 0 && !wp->w_botfill) { /* * Display filler lines at the end of the file */ if (char2cells(fill_diff) > 1) i = '-'; else i = fill_diff; if (row + j > wp->w_height) j = wp->w_height - row; win_draw_end(wp, i, i, row, row + (int)j, HLF_DED); row += j; } #endif } else if (dollar_vcol == -1) wp->w_botline = lnum; /* make sure the rest of the screen is blank */ /* put '~'s on rows that aren't part of the file. */ win_draw_end(wp, '~', ' ', row, wp->w_height, HLF_AT); } /* Reset the type of redrawing required, the window has been updated. */ wp->w_redr_type = 0; #ifdef FEAT_DIFF wp->w_old_topfill = wp->w_topfill; wp->w_old_botfill = wp->w_botfill; #endif if (dollar_vcol == -1) { /* * There is a trick with w_botline. If we invalidate it on each * change that might modify it, this will cause a lot of expensive * calls to plines() in update_topline() each time. Therefore the * value of w_botline is often approximated, and this value is used to * compute the value of w_topline. If the value of w_botline was * wrong, check that the value of w_topline is correct (cursor is on * the visible part of the text). If it's not, we need to redraw * again. Mostly this just means scrolling up a few lines, so it * doesn't look too bad. Only do this for the current window (where * changes are relevant). */ wp->w_valid |= VALID_BOTLINE; if (wp == curwin && wp->w_botline != old_botline && !recursive) { recursive = TRUE; curwin->w_valid &= ~VALID_TOPLINE; update_topline(); /* may invalidate w_botline again */ if (must_redraw != 0) { /* Don't update for changes in buffer again. */ i = curbuf->b_mod_set; curbuf->b_mod_set = FALSE; win_update(curwin); must_redraw = 0; curbuf->b_mod_set = i; } recursive = FALSE; } } #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) /* restore got_int, unless CTRL-C was hit while redrawing */ if (!got_int) got_int = save_got_int; #endif } #ifdef FEAT_SIGNS static int draw_signcolumn __ARGS((win_T *wp)); /* * Return TRUE when window "wp" has a column to draw signs in. */ static int draw_signcolumn(wp) win_T *wp; { return (wp->w_buffer->b_signlist != NULL # ifdef FEAT_NETBEANS_INTG || wp->w_buffer->b_has_sign_column # endif ); } #endif /* * Clear the rest of the window and mark the unused lines with "c1". use "c2" * as the filler character. */ static void win_draw_end(wp, c1, c2, row, endrow, hl) win_T *wp; int c1; int c2; int row; int endrow; hlf_T hl; { #if defined(FEAT_FOLDING) || defined(FEAT_SIGNS) || defined(FEAT_CMDWIN) int n = 0; # define FDC_OFF n #else # define FDC_OFF 0 #endif #ifdef FEAT_FOLDING int fdc = compute_foldcolumn(wp, 0); #endif #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { /* No check for cmdline window: should never be right-left. */ # ifdef FEAT_FOLDING n = fdc; if (n > 0) { /* draw the fold column at the right */ if (n > W_WIDTH(wp)) n = W_WIDTH(wp); screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow, W_ENDCOL(wp) - n, (int)W_ENDCOL(wp), ' ', ' ', hl_attr(HLF_FC)); } # endif # ifdef FEAT_SIGNS if (draw_signcolumn(wp)) { int nn = n + 2; /* draw the sign column left of the fold column */ if (nn > W_WIDTH(wp)) nn = W_WIDTH(wp); screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow, W_ENDCOL(wp) - nn, (int)W_ENDCOL(wp) - n, ' ', ' ', hl_attr(HLF_SC)); n = nn; } # endif screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow, W_WINCOL(wp), W_ENDCOL(wp) - 1 - FDC_OFF, c2, c2, hl_attr(hl)); screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow, W_ENDCOL(wp) - 1 - FDC_OFF, W_ENDCOL(wp) - FDC_OFF, c1, c2, hl_attr(hl)); } else #endif { #ifdef FEAT_CMDWIN if (cmdwin_type != 0 && wp == curwin) { /* draw the cmdline character in the leftmost column */ n = 1; if (n > wp->w_width) n = wp->w_width; screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow, W_WINCOL(wp), (int)W_WINCOL(wp) + n, cmdwin_type, ' ', hl_attr(HLF_AT)); } #endif #ifdef FEAT_FOLDING if (fdc > 0) { int nn = n + fdc; /* draw the fold column at the left */ if (nn > W_WIDTH(wp)) nn = W_WIDTH(wp); screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow, W_WINCOL(wp) + n, (int)W_WINCOL(wp) + nn, ' ', ' ', hl_attr(HLF_FC)); n = nn; } #endif #ifdef FEAT_SIGNS if (draw_signcolumn(wp)) { int nn = n + 2; /* draw the sign column after the fold column */ if (nn > W_WIDTH(wp)) nn = W_WIDTH(wp); screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow, W_WINCOL(wp) + n, (int)W_WINCOL(wp) + nn, ' ', ' ', hl_attr(HLF_SC)); n = nn; } #endif screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow, W_WINCOL(wp) + FDC_OFF, (int)W_ENDCOL(wp), c1, c2, hl_attr(hl)); } set_empty_rows(wp, row); } #ifdef FEAT_SYN_HL static int advance_color_col __ARGS((int vcol, int **color_cols)); /* * Advance **color_cols and return TRUE when there are columns to draw. */ static int advance_color_col(vcol, color_cols) int vcol; int **color_cols; { while (**color_cols >= 0 && vcol > **color_cols) ++*color_cols; return (**color_cols >= 0); } #endif #ifdef FEAT_FOLDING /* * Compute the width of the foldcolumn. Based on 'foldcolumn' and how much * space is available for window "wp", minus "col". */ static int compute_foldcolumn(wp, col) win_T *wp; int col; { int fdc = wp->w_p_fdc; int wmw = wp == curwin && p_wmw == 0 ? 1 : p_wmw; int wwidth = W_WIDTH(wp); if (fdc > wwidth - (col + wmw)) fdc = wwidth - (col + wmw); return fdc; } /* * Display one folded line. */ static void fold_line(wp, fold_count, foldinfo, lnum, row) win_T *wp; long fold_count; foldinfo_T *foldinfo; linenr_T lnum; int row; { char_u buf[51]; pos_T *top, *bot; linenr_T lnume = lnum + fold_count - 1; int len; char_u *text; int fdc; int col; int txtcol; int off = (int)(current_ScreenLine - ScreenLines); int ri; /* Build the fold line: * 1. Add the cmdwin_type for the command-line window * 2. Add the 'foldcolumn' * 3. Add the 'number' or 'relativenumber' column * 4. Compose the text * 5. Add the text * 6. set highlighting for the Visual area an other text */ col = 0; /* * 1. Add the cmdwin_type for the command-line window * Ignores 'rightleft', this window is never right-left. */ #ifdef FEAT_CMDWIN if (cmdwin_type != 0 && wp == curwin) { ScreenLines[off] = cmdwin_type; ScreenAttrs[off] = hl_attr(HLF_AT); #ifdef FEAT_MBYTE if (enc_utf8) ScreenLinesUC[off] = 0; #endif ++col; } #endif /* * 2. Add the 'foldcolumn' * Reduce the width when there is not enough space. */ fdc = compute_foldcolumn(wp, col); if (fdc > 0) { fill_foldcolumn(buf, wp, TRUE, lnum); #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { int i; copy_text_attr(off + W_WIDTH(wp) - fdc - col, buf, fdc, hl_attr(HLF_FC)); /* reverse the fold column */ for (i = 0; i < fdc; ++i) ScreenLines[off + W_WIDTH(wp) - i - 1 - col] = buf[i]; } else #endif copy_text_attr(off + col, buf, fdc, hl_attr(HLF_FC)); col += fdc; } #ifdef FEAT_RIGHTLEFT # define RL_MEMSET(p, v, l) if (wp->w_p_rl) \ for (ri = 0; ri < l; ++ri) \ ScreenAttrs[off + (W_WIDTH(wp) - (p) - (l)) + ri] = v; \ else \ for (ri = 0; ri < l; ++ri) \ ScreenAttrs[off + (p) + ri] = v #else # define RL_MEMSET(p, v, l) for (ri = 0; ri < l; ++ri) \ ScreenAttrs[off + (p) + ri] = v #endif /* Set all attributes of the 'number' or 'relativenumber' column and the * text */ RL_MEMSET(col, hl_attr(HLF_FL), W_WIDTH(wp) - col); #ifdef FEAT_SIGNS /* If signs are being displayed, add two spaces. */ if (draw_signcolumn(wp)) { len = W_WIDTH(wp) - col; if (len > 0) { if (len > 2) len = 2; # ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) /* the line number isn't reversed */ copy_text_attr(off + W_WIDTH(wp) - len - col, (char_u *)" ", len, hl_attr(HLF_FL)); else # endif copy_text_attr(off + col, (char_u *)" ", len, hl_attr(HLF_FL)); col += len; } } #endif /* * 3. Add the 'number' or 'relativenumber' column */ if (wp->w_p_nu || wp->w_p_rnu) { len = W_WIDTH(wp) - col; if (len > 0) { int w = number_width(wp); long num; char *fmt = "%*ld "; if (len > w + 1) len = w + 1; if (wp->w_p_nu && !wp->w_p_rnu) /* 'number' + 'norelativenumber' */ num = (long)lnum; else { /* 'relativenumber', don't use negative numbers */ num = labs((long)get_cursor_rel_lnum(wp, lnum)); if (num == 0 && wp->w_p_nu && wp->w_p_rnu) { /* 'number' + 'relativenumber': cursor line shows absolute * line number */ num = lnum; fmt = "%-*ld "; } } sprintf((char *)buf, fmt, w, num); #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) /* the line number isn't reversed */ copy_text_attr(off + W_WIDTH(wp) - len - col, buf, len, hl_attr(HLF_FL)); else #endif copy_text_attr(off + col, buf, len, hl_attr(HLF_FL)); col += len; } } /* * 4. Compose the folded-line string with 'foldtext', if set. */ text = get_foldtext(wp, lnum, lnume, foldinfo, buf); txtcol = col; /* remember where text starts */ /* * 5. move the text to current_ScreenLine. Fill up with "fill_fold". * Right-left text is put in columns 0 - number-col, normal text is put * in columns number-col - window-width. */ #ifdef FEAT_MBYTE if (has_mbyte) { int cells; int u8c, u8cc[MAX_MCO]; int i; int idx; int c_len; char_u *p; # ifdef FEAT_ARABIC int prev_c = 0; /* previous Arabic character */ int prev_c1 = 0; /* first composing char for prev_c */ # endif # ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) idx = off; else # endif idx = off + col; /* Store multibyte characters in ScreenLines[] et al. correctly. */ for (p = text; *p != NUL; ) { cells = (*mb_ptr2cells)(p); c_len = (*mb_ptr2len)(p); if (col + cells > W_WIDTH(wp) # ifdef FEAT_RIGHTLEFT - (wp->w_p_rl ? col : 0) # endif ) break; ScreenLines[idx] = *p; if (enc_utf8) { u8c = utfc_ptr2char(p, u8cc); if (*p < 0x80 && u8cc[0] == 0) { ScreenLinesUC[idx] = 0; #ifdef FEAT_ARABIC prev_c = u8c; #endif } else { #ifdef FEAT_ARABIC if (p_arshape && !p_tbidi && ARABIC_CHAR(u8c)) { /* Do Arabic shaping. */ int pc, pc1, nc; int pcc[MAX_MCO]; int firstbyte = *p; /* The idea of what is the previous and next * character depends on 'rightleft'. */ if (wp->w_p_rl) { pc = prev_c; pc1 = prev_c1; nc = utf_ptr2char(p + c_len); prev_c1 = u8cc[0]; } else { pc = utfc_ptr2char(p + c_len, pcc); nc = prev_c; pc1 = pcc[0]; } prev_c = u8c; u8c = arabic_shape(u8c, &firstbyte, &u8cc[0], pc, pc1, nc); ScreenLines[idx] = firstbyte; } else prev_c = u8c; #endif /* Non-BMP character: display as ? or fullwidth ?. */ #ifdef UNICODE16 if (u8c >= 0x10000) ScreenLinesUC[idx] = (cells == 2) ? 0xff1f : (int)'?'; else #endif ScreenLinesUC[idx] = u8c; for (i = 0; i < Screen_mco; ++i) { ScreenLinesC[i][idx] = u8cc[i]; if (u8cc[i] == 0) break; } } if (cells > 1) ScreenLines[idx + 1] = 0; } else if (enc_dbcs == DBCS_JPNU && *p == 0x8e) /* double-byte single width character */ ScreenLines2[idx] = p[1]; else if (cells > 1) /* double-width character */ ScreenLines[idx + 1] = p[1]; col += cells; idx += cells; p += c_len; } } else #endif { len = (int)STRLEN(text); if (len > W_WIDTH(wp) - col) len = W_WIDTH(wp) - col; if (len > 0) { #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) STRNCPY(current_ScreenLine, text, len); else #endif STRNCPY(current_ScreenLine + col, text, len); col += len; } } /* Fill the rest of the line with the fold filler */ #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) col -= txtcol; #endif while (col < W_WIDTH(wp) #ifdef FEAT_RIGHTLEFT - (wp->w_p_rl ? txtcol : 0) #endif ) { #ifdef FEAT_MBYTE if (enc_utf8) { if (fill_fold >= 0x80) { ScreenLinesUC[off + col] = fill_fold; ScreenLinesC[0][off + col] = 0; } else ScreenLinesUC[off + col] = 0; } #endif ScreenLines[off + col++] = fill_fold; } if (text != buf) vim_free(text); /* * 6. set highlighting for the Visual area an other text. * If all folded lines are in the Visual area, highlight the line. */ if (VIsual_active && wp->w_buffer == curwin->w_buffer) { if (ltoreq(curwin->w_cursor, VIsual)) { /* Visual is after curwin->w_cursor */ top = &curwin->w_cursor; bot = &VIsual; } else { /* Visual is before curwin->w_cursor */ top = &VIsual; bot = &curwin->w_cursor; } if (lnum >= top->lnum && lnume <= bot->lnum && (VIsual_mode != 'v' || ((lnum > top->lnum || (lnum == top->lnum && top->col == 0)) && (lnume < bot->lnum || (lnume == bot->lnum && (bot->col - (*p_sel == 'e')) >= (colnr_T)STRLEN(ml_get_buf(wp->w_buffer, lnume, FALSE))))))) { if (VIsual_mode == Ctrl_V) { /* Visual block mode: highlight the chars part of the block */ if (wp->w_old_cursor_fcol + txtcol < (colnr_T)W_WIDTH(wp)) { if (wp->w_old_cursor_lcol != MAXCOL && wp->w_old_cursor_lcol + txtcol < (colnr_T)W_WIDTH(wp)) len = wp->w_old_cursor_lcol; else len = W_WIDTH(wp) - txtcol; RL_MEMSET(wp->w_old_cursor_fcol + txtcol, hl_attr(HLF_V), len - (int)wp->w_old_cursor_fcol); } } else { /* Set all attributes of the text */ RL_MEMSET(txtcol, hl_attr(HLF_V), W_WIDTH(wp) - txtcol); } } } #ifdef FEAT_SYN_HL /* Show colorcolumn in the fold line, but let cursorcolumn override it. */ if (wp->w_p_cc_cols) { int i = 0; int j = wp->w_p_cc_cols[i]; int old_txtcol = txtcol; while (j > -1) { txtcol += j; if (wp->w_p_wrap) txtcol -= wp->w_skipcol; else txtcol -= wp->w_leftcol; if (txtcol >= 0 && txtcol < W_WIDTH(wp)) ScreenAttrs[off + txtcol] = hl_combine_attr( ScreenAttrs[off + txtcol], hl_attr(HLF_MC)); txtcol = old_txtcol; j = wp->w_p_cc_cols[++i]; } } /* Show 'cursorcolumn' in the fold line. */ if (wp->w_p_cuc) { txtcol += wp->w_virtcol; if (wp->w_p_wrap) txtcol -= wp->w_skipcol; else txtcol -= wp->w_leftcol; if (txtcol >= 0 && txtcol < W_WIDTH(wp)) ScreenAttrs[off + txtcol] = hl_combine_attr( ScreenAttrs[off + txtcol], hl_attr(HLF_CUC)); } #endif SCREEN_LINE(row + W_WINROW(wp), W_WINCOL(wp), (int)W_WIDTH(wp), (int)W_WIDTH(wp), FALSE); /* * Update w_cline_height and w_cline_folded if the cursor line was * updated (saves a call to plines() later). */ if (wp == curwin && lnum <= curwin->w_cursor.lnum && lnume >= curwin->w_cursor.lnum) { curwin->w_cline_row = row; curwin->w_cline_height = 1; curwin->w_cline_folded = TRUE; curwin->w_valid |= (VALID_CHEIGHT|VALID_CROW); } } /* * Copy "buf[len]" to ScreenLines["off"] and set attributes to "attr". */ static void copy_text_attr(off, buf, len, attr) int off; char_u *buf; int len; int attr; { int i; mch_memmove(ScreenLines + off, buf, (size_t)len); # ifdef FEAT_MBYTE if (enc_utf8) vim_memset(ScreenLinesUC + off, 0, sizeof(u8char_T) * (size_t)len); # endif for (i = 0; i < len; ++i) ScreenAttrs[off + i] = attr; } /* * Fill the foldcolumn at "p" for window "wp". * Only to be called when 'foldcolumn' > 0. */ static void fill_foldcolumn(p, wp, closed, lnum) char_u *p; win_T *wp; int closed; /* TRUE of FALSE */ linenr_T lnum; /* current line number */ { int i = 0; int level; int first_level; int empty; int fdc = compute_foldcolumn(wp, 0); /* Init to all spaces. */ vim_memset(p, ' ', (size_t)fdc); level = win_foldinfo.fi_level; if (level > 0) { /* If there is only one column put more info in it. */ empty = (fdc == 1) ? 0 : 1; /* If the column is too narrow, we start at the lowest level that * fits and use numbers to indicated the depth. */ first_level = level - fdc - closed + 1 + empty; if (first_level < 1) first_level = 1; for (i = 0; i + empty < fdc; ++i) { if (win_foldinfo.fi_lnum == lnum && first_level + i >= win_foldinfo.fi_low_level) p[i] = '-'; else if (first_level == 1) p[i] = '|'; else if (first_level + i <= 9) p[i] = '0' + first_level + i; else p[i] = '>'; if (first_level + i == level) break; } } if (closed) p[i >= fdc ? i - 1 : i] = '+'; } #endif /* FEAT_FOLDING */ /* * Display line "lnum" of window 'wp' on the screen. * Start at row "startrow", stop when "endrow" is reached. * wp->w_virtcol needs to be valid. * * Return the number of last row the line occupies. */ static int win_line(wp, lnum, startrow, endrow, nochange) win_T *wp; linenr_T lnum; int startrow; int endrow; int nochange UNUSED; /* not updating for changed text */ { int col; /* visual column on screen */ unsigned off; /* offset in ScreenLines/ScreenAttrs */ int c = 0; /* init for GCC */ long vcol = 0; /* virtual column (for tabs) */ #ifdef FEAT_LINEBREAK long vcol_sbr = -1; /* virtual column after showbreak */ #endif long vcol_prev = -1; /* "vcol" of previous character */ char_u *line; /* current line */ char_u *ptr; /* current position in "line" */ int row; /* row in the window, excl w_winrow */ int screen_row; /* row on the screen, incl w_winrow */ char_u extra[18]; /* "%ld" and 'fdc' must fit in here */ int n_extra = 0; /* number of extra chars */ char_u *p_extra = NULL; /* string of extra chars, plus NUL */ char_u *p_extra_free = NULL; /* p_extra needs to be freed */ int c_extra = NUL; /* extra chars, all the same */ int extra_attr = 0; /* attributes when n_extra != 0 */ static char_u *at_end_str = (char_u *)""; /* used for p_extra when displaying lcs_eol at end-of-line */ int lcs_eol_one = lcs_eol; /* lcs_eol until it's been used */ int lcs_prec_todo = lcs_prec; /* lcs_prec until it's been used */ /* saved "extra" items for when draw_state becomes WL_LINE (again) */ int saved_n_extra = 0; char_u *saved_p_extra = NULL; int saved_c_extra = 0; int saved_char_attr = 0; int n_attr = 0; /* chars with special attr */ int saved_attr2 = 0; /* char_attr saved for n_attr */ int n_attr3 = 0; /* chars with overruling special attr */ int saved_attr3 = 0; /* char_attr saved for n_attr3 */ int n_skip = 0; /* nr of chars to skip for 'nowrap' */ int fromcol, tocol; /* start/end of inverting */ int fromcol_prev = -2; /* start of inverting after cursor */ int noinvcur = FALSE; /* don't invert the cursor */ pos_T *top, *bot; int lnum_in_visual_area = FALSE; pos_T pos; long v; int char_attr = 0; /* attributes for next character */ int attr_pri = FALSE; /* char_attr has priority */ int area_highlighting = FALSE; /* Visual or incsearch highlighting in this line */ int attr = 0; /* attributes for area highlighting */ int area_attr = 0; /* attributes desired by highlighting */ int search_attr = 0; /* attributes desired by 'hlsearch' */ #ifdef FEAT_SYN_HL int vcol_save_attr = 0; /* saved attr for 'cursorcolumn' */ int syntax_attr = 0; /* attributes desired by syntax */ int has_syntax = FALSE; /* this buffer has syntax highl. */ int save_did_emsg; int eol_hl_off = 0; /* 1 if highlighted char after EOL */ int draw_color_col = FALSE; /* highlight colorcolumn */ int *color_cols = NULL; /* pointer to according columns array */ #endif #ifdef FEAT_SPELL int has_spell = FALSE; /* this buffer has spell checking */ # define SPWORDLEN 150 char_u nextline[SPWORDLEN * 2];/* text with start of the next line */ int nextlinecol = 0; /* column where nextline[] starts */ int nextline_idx = 0; /* index in nextline[] where next line starts */ int spell_attr = 0; /* attributes desired by spelling */ int word_end = 0; /* last byte with same spell_attr */ static linenr_T checked_lnum = 0; /* line number for "checked_col" */ static int checked_col = 0; /* column in "checked_lnum" up to which * there are no spell errors */ static int cap_col = -1; /* column to check for Cap word */ static linenr_T capcol_lnum = 0; /* line number where "cap_col" used */ int cur_checked_col = 0; /* checked column for current line */ #endif int extra_check; /* has syntax or linebreak */ #ifdef FEAT_MBYTE int multi_attr = 0; /* attributes desired by multibyte */ int mb_l = 1; /* multi-byte byte length */ int mb_c = 0; /* decoded multi-byte character */ int mb_utf8 = FALSE; /* screen char is UTF-8 char */ int u8cc[MAX_MCO]; /* composing UTF-8 chars */ #endif #ifdef FEAT_DIFF int filler_lines; /* nr of filler lines to be drawn */ int filler_todo; /* nr of filler lines still to do + 1 */ hlf_T diff_hlf = (hlf_T)0; /* type of diff highlighting */ int change_start = MAXCOL; /* first col of changed area */ int change_end = -1; /* last col of changed area */ #endif colnr_T trailcol = MAXCOL; /* start of trailing spaces */ #ifdef FEAT_LINEBREAK int need_showbreak = FALSE; #endif #if defined(FEAT_SIGNS) || (defined(FEAT_QUICKFIX) && defined(FEAT_WINDOWS)) \ || defined(FEAT_SYN_HL) || defined(FEAT_DIFF) # define LINE_ATTR int line_attr = 0; /* attribute for the whole line */ #endif #ifdef FEAT_SEARCH_EXTRA matchitem_T *cur; /* points to the match list */ match_T *shl; /* points to search_hl or a match */ int shl_flag; /* flag to indicate whether search_hl has been processed or not */ int pos_inprogress; /* marks that position match search is in progress */ int prevcol_hl_flag; /* flag to indicate whether prevcol equals startcol of search_hl or one of the matches */ #endif #ifdef FEAT_ARABIC int prev_c = 0; /* previous Arabic character */ int prev_c1 = 0; /* first composing char for prev_c */ #endif #if defined(LINE_ATTR) int did_line_attr = 0; #endif /* draw_state: items that are drawn in sequence: */ #define WL_START 0 /* nothing done yet */ #ifdef FEAT_CMDWIN # define WL_CMDLINE WL_START + 1 /* cmdline window column */ #else # define WL_CMDLINE WL_START #endif #ifdef FEAT_FOLDING # define WL_FOLD WL_CMDLINE + 1 /* 'foldcolumn' */ #else # define WL_FOLD WL_CMDLINE #endif #ifdef FEAT_SIGNS # define WL_SIGN WL_FOLD + 1 /* column for signs */ #else # define WL_SIGN WL_FOLD /* column for signs */ #endif #define WL_NR WL_SIGN + 1 /* line number */ #ifdef FEAT_LINEBREAK # define WL_BRI WL_NR + 1 /* 'breakindent' */ #else # define WL_BRI WL_NR #endif #if defined(FEAT_LINEBREAK) || defined(FEAT_DIFF) # define WL_SBR WL_BRI + 1 /* 'showbreak' or 'diff' */ #else # define WL_SBR WL_BRI #endif #define WL_LINE WL_SBR + 1 /* text in the line */ int draw_state = WL_START; /* what to draw next */ #if defined(FEAT_XIM) && (defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MACVIM)) int feedback_col = 0; int feedback_old_attr = -1; #endif #ifdef FEAT_CONCEAL int syntax_flags = 0; int syntax_seqnr = 0; int prev_syntax_id = 0; int conceal_attr = hl_attr(HLF_CONCEAL); int is_concealing = FALSE; int boguscols = 0; /* nonexistent columns added to force wrapping */ int vcol_off = 0; /* offset for concealed characters */ int did_wcol = FALSE; int match_conc = FALSE; /* cchar for match functions */ int has_match_conc = FALSE; /* match wants to conceal */ int old_boguscols = 0; # define VCOL_HLC (vcol - vcol_off) # define FIX_FOR_BOGUSCOLS \ { \ n_extra += vcol_off; \ vcol -= vcol_off; \ vcol_off = 0; \ col -= boguscols; \ old_boguscols = boguscols; \ boguscols = 0; \ } #else # define VCOL_HLC (vcol) #endif if (startrow > endrow) /* past the end already! */ return startrow; row = startrow; screen_row = row + W_WINROW(wp); /* * To speed up the loop below, set extra_check when there is linebreak, * trailing white space and/or syntax processing to be done. */ #ifdef FEAT_LINEBREAK extra_check = wp->w_p_lbr; #else extra_check = 0; #endif #ifdef FEAT_SYN_HL if (syntax_present(wp) && !wp->w_s->b_syn_error) { /* Prepare for syntax highlighting in this line. When there is an * error, stop syntax highlighting. */ save_did_emsg = did_emsg; did_emsg = FALSE; syntax_start(wp, lnum); if (did_emsg) wp->w_s->b_syn_error = TRUE; else { did_emsg = save_did_emsg; has_syntax = TRUE; extra_check = TRUE; } } /* Check for columns to display for 'colorcolumn'. */ color_cols = wp->w_p_cc_cols; if (color_cols != NULL) draw_color_col = advance_color_col(VCOL_HLC, &color_cols); #endif #ifdef FEAT_SPELL if (wp->w_p_spell && *wp->w_s->b_p_spl != NUL && wp->w_s->b_langp.ga_len > 0 && *(char **)(wp->w_s->b_langp.ga_data) != NULL) { /* Prepare for spell checking. */ has_spell = TRUE; extra_check = TRUE; /* Get the start of the next line, so that words that wrap to the next * line are found too: "et<line-break>al.". * Trick: skip a few chars for C/shell/Vim comments */ nextline[SPWORDLEN] = NUL; if (lnum < wp->w_buffer->b_ml.ml_line_count) { line = ml_get_buf(wp->w_buffer, lnum + 1, FALSE); spell_cat_line(nextline + SPWORDLEN, line, SPWORDLEN); } /* When a word wrapped from the previous line the start of the current * line is valid. */ if (lnum == checked_lnum) cur_checked_col = checked_col; checked_lnum = 0; /* When there was a sentence end in the previous line may require a * word starting with capital in this line. In line 1 always check * the first word. */ if (lnum != capcol_lnum) cap_col = -1; if (lnum == 1) cap_col = 0; capcol_lnum = 0; } #endif /* * handle visual active in this window */ fromcol = -10; tocol = MAXCOL; if (VIsual_active && wp->w_buffer == curwin->w_buffer) { /* Visual is after curwin->w_cursor */ if (ltoreq(curwin->w_cursor, VIsual)) { top = &curwin->w_cursor; bot = &VIsual; } else /* Visual is before curwin->w_cursor */ { top = &VIsual; bot = &curwin->w_cursor; } lnum_in_visual_area = (lnum >= top->lnum && lnum <= bot->lnum); if (VIsual_mode == Ctrl_V) /* block mode */ { if (lnum_in_visual_area) { fromcol = wp->w_old_cursor_fcol; tocol = wp->w_old_cursor_lcol; } } else /* non-block mode */ { if (lnum > top->lnum && lnum <= bot->lnum) fromcol = 0; else if (lnum == top->lnum) { if (VIsual_mode == 'V') /* linewise */ fromcol = 0; else { getvvcol(wp, top, (colnr_T *)&fromcol, NULL, NULL); if (gchar_pos(top) == NUL) tocol = fromcol + 1; } } if (VIsual_mode != 'V' && lnum == bot->lnum) { if (*p_sel == 'e' && bot->col == 0 #ifdef FEAT_VIRTUALEDIT && bot->coladd == 0 #endif ) { fromcol = -10; tocol = MAXCOL; } else if (bot->col == MAXCOL) tocol = MAXCOL; else { pos = *bot; if (*p_sel == 'e') getvvcol(wp, &pos, (colnr_T *)&tocol, NULL, NULL); else { getvvcol(wp, &pos, NULL, NULL, (colnr_T *)&tocol); ++tocol; } } } } #ifndef MSDOS /* Check if the character under the cursor should not be inverted */ if (!highlight_match && lnum == curwin->w_cursor.lnum && wp == curwin # ifdef FEAT_GUI && !gui.in_use # endif ) noinvcur = TRUE; #endif /* if inverting in this line set area_highlighting */ if (fromcol >= 0) { area_highlighting = TRUE; attr = hl_attr(HLF_V); #if defined(FEAT_CLIPBOARD) && defined(FEAT_X11) if ((clip_star.available && !clip_star.owned && clip_isautosel_star()) || (clip_plus.available && !clip_plus.owned && clip_isautosel_plus())) attr = hl_attr(HLF_VNC); #endif } } /* * handle 'incsearch' and ":s///c" highlighting */ else if (highlight_match && wp == curwin && lnum >= curwin->w_cursor.lnum && lnum <= curwin->w_cursor.lnum + search_match_lines) { if (lnum == curwin->w_cursor.lnum) getvcol(curwin, &(curwin->w_cursor), (colnr_T *)&fromcol, NULL, NULL); else fromcol = 0; if (lnum == curwin->w_cursor.lnum + search_match_lines) { pos.lnum = lnum; pos.col = search_match_endcol; getvcol(curwin, &pos, (colnr_T *)&tocol, NULL, NULL); } else tocol = MAXCOL; /* do at least one character; happens when past end of line */ if (fromcol == tocol) tocol = fromcol + 1; area_highlighting = TRUE; attr = hl_attr(HLF_I); } #ifdef FEAT_DIFF filler_lines = diff_check(wp, lnum); if (filler_lines < 0) { if (filler_lines == -1) { if (diff_find_change(wp, lnum, &change_start, &change_end)) diff_hlf = HLF_ADD; /* added line */ else if (change_start == 0) diff_hlf = HLF_TXD; /* changed text */ else diff_hlf = HLF_CHD; /* changed line */ } else diff_hlf = HLF_ADD; /* added line */ filler_lines = 0; area_highlighting = TRUE; } if (lnum == wp->w_topline) filler_lines = wp->w_topfill; filler_todo = filler_lines; #endif #ifdef LINE_ATTR # ifdef FEAT_SIGNS /* If this line has a sign with line highlighting set line_attr. */ v = buf_getsigntype(wp->w_buffer, lnum, SIGN_LINEHL); if (v != 0) line_attr = sign_get_attr((int)v, TRUE); # endif # if defined(FEAT_QUICKFIX) && defined(FEAT_WINDOWS) /* Highlight the current line in the quickfix window. */ if (bt_quickfix(wp->w_buffer) && qf_current_entry(wp) == lnum) line_attr = hl_attr(HLF_L); # endif if (line_attr != 0) area_highlighting = TRUE; #endif line = ml_get_buf(wp->w_buffer, lnum, FALSE); ptr = line; #ifdef FEAT_SPELL if (has_spell) { /* For checking first word with a capital skip white space. */ if (cap_col == 0) cap_col = (int)(skipwhite(line) - line); /* To be able to spell-check over line boundaries copy the end of the * current line into nextline[]. Above the start of the next line was * copied to nextline[SPWORDLEN]. */ if (nextline[SPWORDLEN] == NUL) { /* No next line or it is empty. */ nextlinecol = MAXCOL; nextline_idx = 0; } else { v = (long)STRLEN(line); if (v < SPWORDLEN) { /* Short line, use it completely and append the start of the * next line. */ nextlinecol = 0; mch_memmove(nextline, line, (size_t)v); STRMOVE(nextline + v, nextline + SPWORDLEN); nextline_idx = v + 1; } else { /* Long line, use only the last SPWORDLEN bytes. */ nextlinecol = v - SPWORDLEN; mch_memmove(nextline, line + nextlinecol, SPWORDLEN); nextline_idx = SPWORDLEN + 1; } } } #endif /* find start of trailing whitespace */ if (wp->w_p_list && lcs_trail) { trailcol = (colnr_T)STRLEN(ptr); while (trailcol > (colnr_T)0 && vim_iswhite(ptr[trailcol - 1])) --trailcol; trailcol += (colnr_T) (ptr - line); extra_check = TRUE; } /* * 'nowrap' or 'wrap' and a single line that doesn't fit: Advance to the * first character to be displayed. */ if (wp->w_p_wrap) v = wp->w_skipcol; else v = wp->w_leftcol; if (v > 0) { #ifdef FEAT_MBYTE char_u *prev_ptr = ptr; #endif while (vcol < v && *ptr != NUL) { c = win_lbr_chartabsize(wp, line, ptr, (colnr_T)vcol, NULL); vcol += c; #ifdef FEAT_MBYTE prev_ptr = ptr; #endif mb_ptr_adv(ptr); } /* When: * - 'cuc' is set, or * - 'colorcolumn' is set, or * - 'virtualedit' is set, or * - the visual mode is active, * the end of the line may be before the start of the displayed part. */ if (vcol < v && ( #ifdef FEAT_SYN_HL wp->w_p_cuc || draw_color_col || #endif #ifdef FEAT_VIRTUALEDIT virtual_active() || #endif (VIsual_active && wp->w_buffer == curwin->w_buffer))) { vcol = v; } /* Handle a character that's not completely on the screen: Put ptr at * that character but skip the first few screen characters. */ if (vcol > v) { vcol -= c; #ifdef FEAT_MBYTE ptr = prev_ptr; #else --ptr; #endif n_skip = v - vcol; } /* * Adjust for when the inverted text is before the screen, * and when the start of the inverted text is before the screen. */ if (tocol <= vcol) fromcol = 0; else if (fromcol >= 0 && fromcol < vcol) fromcol = vcol; #ifdef FEAT_LINEBREAK /* When w_skipcol is non-zero, first line needs 'showbreak' */ if (wp->w_p_wrap) need_showbreak = TRUE; #endif #ifdef FEAT_SPELL /* When spell checking a word we need to figure out the start of the * word and if it's badly spelled or not. */ if (has_spell) { int len; colnr_T linecol = (colnr_T)(ptr - line); hlf_T spell_hlf = HLF_COUNT; pos = wp->w_cursor; wp->w_cursor.lnum = lnum; wp->w_cursor.col = linecol; len = spell_move_to(wp, FORWARD, TRUE, TRUE, &spell_hlf); /* spell_move_to() may call ml_get() and make "line" invalid */ line = ml_get_buf(wp->w_buffer, lnum, FALSE); ptr = line + linecol; if (len == 0 || (int)wp->w_cursor.col > ptr - line) { /* no bad word found at line start, don't check until end of a * word */ spell_hlf = HLF_COUNT; word_end = (int)(spell_to_word_end(ptr, wp) - line + 1); } else { /* bad word found, use attributes until end of word */ word_end = wp->w_cursor.col + len + 1; /* Turn index into actual attributes. */ if (spell_hlf != HLF_COUNT) spell_attr = highlight_attr[spell_hlf]; } wp->w_cursor = pos; # ifdef FEAT_SYN_HL /* Need to restart syntax highlighting for this line. */ if (has_syntax) syntax_start(wp, lnum); # endif } #endif } /* * Correct highlighting for cursor that can't be disabled. * Avoids having to check this for each character. */ if (fromcol >= 0) { if (noinvcur) { if ((colnr_T)fromcol == wp->w_virtcol) { /* highlighting starts at cursor, let it start just after the * cursor */ fromcol_prev = fromcol; fromcol = -1; } else if ((colnr_T)fromcol < wp->w_virtcol) /* restart highlighting after the cursor */ fromcol_prev = wp->w_virtcol; } if (fromcol >= tocol) fromcol = -1; } #ifdef FEAT_SEARCH_EXTRA /* * Handle highlighting the last used search pattern and matches. * Do this for both search_hl and the match list. */ cur = wp->w_match_head; shl_flag = FALSE; while (cur != NULL || shl_flag == FALSE) { if (shl_flag == FALSE) { shl = &search_hl; shl_flag = TRUE; } else shl = &cur->hl; shl->startcol = MAXCOL; shl->endcol = MAXCOL; shl->attr_cur = 0; v = (long)(ptr - line); if (cur != NULL) cur->pos.cur = 0; next_search_hl(wp, shl, lnum, (colnr_T)v, cur); /* Need to get the line again, a multi-line regexp may have made it * invalid. */ line = ml_get_buf(wp->w_buffer, lnum, FALSE); ptr = line + v; if (shl->lnum != 0 && shl->lnum <= lnum) { if (shl->lnum == lnum) shl->startcol = shl->rm.startpos[0].col; else shl->startcol = 0; if (lnum == shl->lnum + shl->rm.endpos[0].lnum - shl->rm.startpos[0].lnum) shl->endcol = shl->rm.endpos[0].col; else shl->endcol = MAXCOL; /* Highlight one character for an empty match. */ if (shl->startcol == shl->endcol) { #ifdef FEAT_MBYTE if (has_mbyte && line[shl->endcol] != NUL) shl->endcol += (*mb_ptr2len)(line + shl->endcol); else #endif ++shl->endcol; } if ((long)shl->startcol < v) /* match at leftcol */ { shl->attr_cur = shl->attr; search_attr = shl->attr; } area_highlighting = TRUE; } if (shl != &search_hl && cur != NULL) cur = cur->next; } #endif #ifdef FEAT_SYN_HL /* Cursor line highlighting for 'cursorline' in the current window. Not * when Visual mode is active, because it's not clear what is selected * then. */ if (wp->w_p_cul && lnum == wp->w_cursor.lnum && !(wp == curwin && VIsual_active)) { line_attr = hl_attr(HLF_CUL); area_highlighting = TRUE; } #endif off = (unsigned)(current_ScreenLine - ScreenLines); col = 0; #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { /* Rightleft window: process the text in the normal direction, but put * it in current_ScreenLine[] from right to left. Start at the * rightmost column of the window. */ col = W_WIDTH(wp) - 1; off += col; } #endif /* * Repeat for the whole displayed line. */ for (;;) { #ifdef FEAT_CONCEAL has_match_conc = FALSE; #endif /* Skip this quickly when working on the text. */ if (draw_state != WL_LINE) { #ifdef FEAT_CMDWIN if (draw_state == WL_CMDLINE - 1 && n_extra == 0) { draw_state = WL_CMDLINE; if (cmdwin_type != 0 && wp == curwin) { /* Draw the cmdline character. */ n_extra = 1; c_extra = cmdwin_type; char_attr = hl_attr(HLF_AT); } } #endif #ifdef FEAT_FOLDING if (draw_state == WL_FOLD - 1 && n_extra == 0) { int fdc = compute_foldcolumn(wp, 0); draw_state = WL_FOLD; if (fdc > 0) { /* Draw the 'foldcolumn'. */ fill_foldcolumn(extra, wp, FALSE, lnum); n_extra = fdc; p_extra = extra; p_extra[n_extra] = NUL; c_extra = NUL; char_attr = hl_attr(HLF_FC); } } #endif #ifdef FEAT_SIGNS if (draw_state == WL_SIGN - 1 && n_extra == 0) { draw_state = WL_SIGN; /* Show the sign column when there are any signs in this * buffer or when using Netbeans. */ if (draw_signcolumn(wp)) { int text_sign; # ifdef FEAT_SIGN_ICONS int icon_sign; # endif /* Draw two cells with the sign value or blank. */ c_extra = ' '; char_attr = hl_attr(HLF_SC); n_extra = 2; if (row == startrow #ifdef FEAT_DIFF + filler_lines && filler_todo <= 0 #endif ) { text_sign = buf_getsigntype(wp->w_buffer, lnum, SIGN_TEXT); # ifdef FEAT_SIGN_ICONS icon_sign = buf_getsigntype(wp->w_buffer, lnum, SIGN_ICON); if (gui.in_use && icon_sign != 0) { /* Use the image in this position. */ c_extra = SIGN_BYTE; # ifdef FEAT_NETBEANS_INTG if (buf_signcount(wp->w_buffer, lnum) > 1) c_extra = MULTISIGN_BYTE; # endif char_attr = icon_sign; } else # endif if (text_sign != 0) { p_extra = sign_get_text(text_sign); if (p_extra != NULL) { c_extra = NUL; n_extra = (int)STRLEN(p_extra); } char_attr = sign_get_attr(text_sign, FALSE); } } } } #endif if (draw_state == WL_NR - 1 && n_extra == 0) { draw_state = WL_NR; /* Display the absolute or relative line number. After the * first fill with blanks when the 'n' flag isn't in 'cpo' */ if ((wp->w_p_nu || wp->w_p_rnu) && (row == startrow #ifdef FEAT_DIFF + filler_lines #endif || vim_strchr(p_cpo, CPO_NUMCOL) == NULL)) { /* Draw the line number (empty space after wrapping). */ if (row == startrow #ifdef FEAT_DIFF + filler_lines #endif ) { long num; char *fmt = "%*ld "; if (wp->w_p_nu && !wp->w_p_rnu) /* 'number' + 'norelativenumber' */ num = (long)lnum; else { /* 'relativenumber', don't use negative numbers */ num = labs((long)get_cursor_rel_lnum(wp, lnum)); if (num == 0 && wp->w_p_nu && wp->w_p_rnu) { /* 'number' + 'relativenumber' */ num = lnum; fmt = "%-*ld "; } } sprintf((char *)extra, fmt, number_width(wp), num); if (wp->w_skipcol > 0) for (p_extra = extra; *p_extra == ' '; ++p_extra) *p_extra = '-'; #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) /* reverse line numbers */ rl_mirror(extra); #endif p_extra = extra; c_extra = NUL; } else c_extra = ' '; n_extra = number_width(wp) + 1; char_attr = hl_attr(HLF_N); #ifdef FEAT_SYN_HL /* When 'cursorline' is set highlight the line number of * the current line differently. * TODO: Can we use CursorLine instead of CursorLineNr * when CursorLineNr isn't set? */ if ((wp->w_p_cul || wp->w_p_rnu) && lnum == wp->w_cursor.lnum) char_attr = hl_attr(HLF_CLN); #endif } } #ifdef FEAT_LINEBREAK if (wp->w_p_brisbr && draw_state == WL_BRI - 1 && n_extra == 0 && *p_sbr != NUL) /* draw indent after showbreak value */ draw_state = WL_BRI; else if (wp->w_p_brisbr && draw_state == WL_SBR && n_extra == 0) /* After the showbreak, draw the breakindent */ draw_state = WL_BRI - 1; /* draw 'breakindent': indent wrapped text accordingly */ if (draw_state == WL_BRI - 1 && n_extra == 0) { draw_state = WL_BRI; if (wp->w_p_bri && n_extra == 0 && row != startrow # ifdef FEAT_DIFF && filler_lines == 0 # endif ) { char_attr = 0; /* was: hl_attr(HLF_AT); */ # ifdef FEAT_DIFF if (diff_hlf != (hlf_T)0) { char_attr = hl_attr(diff_hlf); # ifdef FEAT_SYN_HL if (wp->w_p_cul && lnum == wp->w_cursor.lnum) char_attr = hl_combine_attr(char_attr, hl_attr(HLF_CUL)); # endif } # endif p_extra = NULL; c_extra = ' '; n_extra = get_breakindent_win(wp, ml_get_buf(wp->w_buffer, lnum, FALSE)); /* Correct end of highlighted area for 'breakindent', * required when 'linebreak' is also set. */ if (tocol == vcol) tocol += n_extra; } } #endif #if defined(FEAT_LINEBREAK) || defined(FEAT_DIFF) if (draw_state == WL_SBR - 1 && n_extra == 0) { draw_state = WL_SBR; # ifdef FEAT_DIFF if (filler_todo > 0) { /* Draw "deleted" diff line(s). */ if (char2cells(fill_diff) > 1) c_extra = '-'; else c_extra = fill_diff; # ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) n_extra = col + 1; else # endif n_extra = W_WIDTH(wp) - col; char_attr = hl_attr(HLF_DED); } # endif # ifdef FEAT_LINEBREAK if (*p_sbr != NUL && need_showbreak) { /* Draw 'showbreak' at the start of each broken line. */ p_extra = p_sbr; c_extra = NUL; n_extra = (int)STRLEN(p_sbr); char_attr = hl_attr(HLF_AT); need_showbreak = FALSE; vcol_sbr = vcol + MB_CHARLEN(p_sbr); /* Correct end of highlighted area for 'showbreak', * required when 'linebreak' is also set. */ if (tocol == vcol) tocol += n_extra; #ifdef FEAT_SYN_HL /* combine 'showbreak' with 'cursorline' */ if (wp->w_p_cul && lnum == wp->w_cursor.lnum) char_attr = hl_combine_attr(char_attr, hl_attr(HLF_CUL)); #endif } # endif } #endif if (draw_state == WL_LINE - 1 && n_extra == 0) { draw_state = WL_LINE; if (saved_n_extra) { /* Continue item from end of wrapped line. */ n_extra = saved_n_extra; c_extra = saved_c_extra; p_extra = saved_p_extra; char_attr = saved_char_attr; } else char_attr = 0; } } /* When still displaying '$' of change command, stop at cursor */ if (dollar_vcol >= 0 && wp == curwin && lnum == wp->w_cursor.lnum && vcol >= (long)wp->w_virtcol #ifdef FEAT_DIFF && filler_todo <= 0 #endif ) { SCREEN_LINE(screen_row, W_WINCOL(wp), col, -(int)W_WIDTH(wp), wp->w_p_rl); /* Pretend we have finished updating the window. Except when * 'cursorcolumn' is set. */ #ifdef FEAT_SYN_HL if (wp->w_p_cuc) row = wp->w_cline_row + wp->w_cline_height; else #endif row = wp->w_height; break; } if (draw_state == WL_LINE && area_highlighting) { /* handle Visual or match highlighting in this line */ if (vcol == fromcol #ifdef FEAT_MBYTE || (has_mbyte && vcol + 1 == fromcol && n_extra == 0 && (*mb_ptr2cells)(ptr) > 1) #endif || ((int)vcol_prev == fromcol_prev && vcol_prev < vcol /* not at margin */ && vcol < tocol)) area_attr = attr; /* start highlighting */ else if (area_attr != 0 && (vcol == tocol || (noinvcur && (colnr_T)vcol == wp->w_virtcol))) area_attr = 0; /* stop highlighting */ #ifdef FEAT_SEARCH_EXTRA if (!n_extra) { /* * Check for start/end of search pattern match. * After end, check for start/end of next match. * When another match, have to check for start again. * Watch out for matching an empty string! * Do this for 'search_hl' and the match list (ordered by * priority). */ v = (long)(ptr - line); cur = wp->w_match_head; shl_flag = FALSE; while (cur != NULL || shl_flag == FALSE) { if (shl_flag == FALSE && ((cur != NULL && cur->priority > SEARCH_HL_PRIORITY) || cur == NULL)) { shl = &search_hl; shl_flag = TRUE; } else shl = &cur->hl; if (cur != NULL) cur->pos.cur = 0; pos_inprogress = TRUE; while (shl->rm.regprog != NULL || (cur != NULL && pos_inprogress)) { if (shl->startcol != MAXCOL && v >= (long)shl->startcol && v < (long)shl->endcol) { #ifdef FEAT_MBYTE int tmp_col = v + MB_PTR2LEN(ptr); if (shl->endcol < tmp_col) shl->endcol = tmp_col; #endif shl->attr_cur = shl->attr; #ifdef FEAT_CONCEAL if (cur != NULL && syn_name2id((char_u *)"Conceal") == cur->hlg_id) { has_match_conc = TRUE; match_conc = cur->conceal_char; } else has_match_conc = match_conc = FALSE; #endif } else if (v == (long)shl->endcol) { shl->attr_cur = 0; #ifdef FEAT_CONCEAL prev_syntax_id = 0; #endif next_search_hl(wp, shl, lnum, (colnr_T)v, cur); pos_inprogress = cur == NULL || cur->pos.cur == 0 ? FALSE : TRUE; /* Need to get the line again, a multi-line regexp * may have made it invalid. */ line = ml_get_buf(wp->w_buffer, lnum, FALSE); ptr = line + v; if (shl->lnum == lnum) { shl->startcol = shl->rm.startpos[0].col; if (shl->rm.endpos[0].lnum == 0) shl->endcol = shl->rm.endpos[0].col; else shl->endcol = MAXCOL; if (shl->startcol == shl->endcol) { /* highlight empty match, try again after * it */ #ifdef FEAT_MBYTE if (has_mbyte) shl->endcol += (*mb_ptr2len)(line + shl->endcol); else #endif ++shl->endcol; } /* Loop to check if the match starts at the * current position */ continue; } } break; } if (shl != &search_hl && cur != NULL) cur = cur->next; } /* Use attributes from match with highest priority among * 'search_hl' and the match list. */ search_attr = search_hl.attr_cur; cur = wp->w_match_head; shl_flag = FALSE; while (cur != NULL || shl_flag == FALSE) { if (shl_flag == FALSE && ((cur != NULL && cur->priority > SEARCH_HL_PRIORITY) || cur == NULL)) { shl = &search_hl; shl_flag = TRUE; } else shl = &cur->hl; if (shl->attr_cur != 0) search_attr = shl->attr_cur; if (shl != &search_hl && cur != NULL) cur = cur->next; } } #endif #ifdef FEAT_DIFF if (diff_hlf != (hlf_T)0) { if (diff_hlf == HLF_CHD && ptr - line >= change_start && n_extra == 0) diff_hlf = HLF_TXD; /* changed text */ if (diff_hlf == HLF_TXD && ptr - line > change_end && n_extra == 0) diff_hlf = HLF_CHD; /* changed line */ line_attr = hl_attr(diff_hlf); if (wp->w_p_cul && lnum == wp->w_cursor.lnum) line_attr = hl_combine_attr(line_attr, hl_attr(HLF_CUL)); } #endif /* Decide which of the highlight attributes to use. */ attr_pri = TRUE; #ifdef LINE_ATTR if (area_attr != 0) char_attr = hl_combine_attr(line_attr, area_attr); else if (search_attr != 0) char_attr = hl_combine_attr(line_attr, search_attr); /* Use line_attr when not in the Visual or 'incsearch' area * (area_attr may be 0 when "noinvcur" is set). */ else if (line_attr != 0 && ((fromcol == -10 && tocol == MAXCOL) || vcol < fromcol || vcol_prev < fromcol_prev || vcol >= tocol)) char_attr = line_attr; #else if (area_attr != 0) char_attr = area_attr; else if (search_attr != 0) char_attr = search_attr; #endif else { attr_pri = FALSE; #ifdef FEAT_SYN_HL if (has_syntax) char_attr = syntax_attr; else #endif char_attr = 0; } } /* * Get the next character to put on the screen. */ /* * The "p_extra" points to the extra stuff that is inserted to * represent special characters (non-printable stuff) and other * things. When all characters are the same, c_extra is used. * "p_extra" must end in a NUL to avoid mb_ptr2len() reads past * "p_extra[n_extra]". * For the '$' of the 'list' option, n_extra == 1, p_extra == "". */ if (n_extra > 0) { if (c_extra != NUL) { c = c_extra; #ifdef FEAT_MBYTE mb_c = c; /* doesn't handle non-utf-8 multi-byte! */ if (enc_utf8 && (*mb_char2len)(c) > 1) { mb_utf8 = TRUE; u8cc[0] = 0; c = 0xc0; } else mb_utf8 = FALSE; #endif } else { c = *p_extra; #ifdef FEAT_MBYTE if (has_mbyte) { mb_c = c; if (enc_utf8) { /* If the UTF-8 character is more than one byte: * Decode it into "mb_c". */ mb_l = (*mb_ptr2len)(p_extra); mb_utf8 = FALSE; if (mb_l > n_extra) mb_l = 1; else if (mb_l > 1) { mb_c = utfc_ptr2char(p_extra, u8cc); mb_utf8 = TRUE; c = 0xc0; } } else { /* if this is a DBCS character, put it in "mb_c" */ mb_l = MB_BYTE2LEN(c); if (mb_l >= n_extra) mb_l = 1; else if (mb_l > 1) mb_c = (c << 8) + p_extra[1]; } if (mb_l == 0) /* at the NUL at end-of-line */ mb_l = 1; /* If a double-width char doesn't fit display a '>' in the * last column. */ if (( # ifdef FEAT_RIGHTLEFT wp->w_p_rl ? (col <= 0) : # endif (col >= W_WIDTH(wp) - 1)) && (*mb_char2cells)(mb_c) == 2) { c = '>'; mb_c = c; mb_l = 1; mb_utf8 = FALSE; multi_attr = hl_attr(HLF_AT); /* put the pointer back to output the double-width * character at the start of the next line. */ ++n_extra; --p_extra; } else { n_extra -= mb_l - 1; p_extra += mb_l - 1; } } #endif ++p_extra; } --n_extra; } else { if (p_extra_free != NULL) { vim_free(p_extra_free); p_extra_free = NULL; } /* * Get a character from the line itself. */ c = *ptr; #ifdef FEAT_MBYTE if (has_mbyte) { mb_c = c; if (enc_utf8) { /* If the UTF-8 character is more than one byte: Decode it * into "mb_c". */ mb_l = (*mb_ptr2len)(ptr); mb_utf8 = FALSE; if (mb_l > 1) { mb_c = utfc_ptr2char(ptr, u8cc); /* Overlong encoded ASCII or ASCII with composing char * is displayed normally, except a NUL. */ if (mb_c < 0x80) c = mb_c; mb_utf8 = TRUE; /* At start of the line we can have a composing char. * Draw it as a space with a composing char. */ if (utf_iscomposing(mb_c)) { int i; for (i = Screen_mco - 1; i > 0; --i) u8cc[i] = u8cc[i - 1]; u8cc[0] = mb_c; mb_c = ' '; } } if ((mb_l == 1 && c >= 0x80) || (mb_l >= 1 && mb_c == 0) || (mb_l > 1 && (!vim_isprintc(mb_c) # ifdef UNICODE16 || mb_c >= 0x10000 # endif ))) { /* * Illegal UTF-8 byte: display as <xx>. * Non-BMP character : display as ? or fullwidth ?. */ # ifdef UNICODE16 if (mb_c < 0x10000) # endif { transchar_hex(extra, mb_c); # ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) /* reverse */ rl_mirror(extra); # endif } # ifdef UNICODE16 else if (utf_char2cells(mb_c) != 2) STRCPY(extra, "?"); else /* 0xff1f in UTF-8: full-width '?' */ STRCPY(extra, "\357\274\237"); # endif p_extra = extra; c = *p_extra; mb_c = mb_ptr2char_adv(&p_extra); mb_utf8 = (c >= 0x80); n_extra = (int)STRLEN(p_extra); c_extra = NUL; if (area_attr == 0 && search_attr == 0) { n_attr = n_extra + 1; extra_attr = hl_attr(HLF_8); saved_attr2 = char_attr; /* save current attr */ } } else if (mb_l == 0) /* at the NUL at end-of-line */ mb_l = 1; #ifdef FEAT_ARABIC else if (p_arshape && !p_tbidi && ARABIC_CHAR(mb_c)) { /* Do Arabic shaping. */ int pc, pc1, nc; int pcc[MAX_MCO]; /* The idea of what is the previous and next * character depends on 'rightleft'. */ if (wp->w_p_rl) { pc = prev_c; pc1 = prev_c1; nc = utf_ptr2char(ptr + mb_l); prev_c1 = u8cc[0]; } else { pc = utfc_ptr2char(ptr + mb_l, pcc); nc = prev_c; pc1 = pcc[0]; } prev_c = mb_c; mb_c = arabic_shape(mb_c, &c, &u8cc[0], pc, pc1, nc); } else prev_c = mb_c; #endif } else /* enc_dbcs */ { mb_l = MB_BYTE2LEN(c); if (mb_l == 0) /* at the NUL at end-of-line */ mb_l = 1; else if (mb_l > 1) { /* We assume a second byte below 32 is illegal. * Hopefully this is OK for all double-byte encodings! */ if (ptr[1] >= 32) mb_c = (c << 8) + ptr[1]; else { if (ptr[1] == NUL) { /* head byte at end of line */ mb_l = 1; transchar_nonprint(extra, c); } else { /* illegal tail byte */ mb_l = 2; STRCPY(extra, "XX"); } p_extra = extra; n_extra = (int)STRLEN(extra) - 1; c_extra = NUL; c = *p_extra++; if (area_attr == 0 && search_attr == 0) { n_attr = n_extra + 1; extra_attr = hl_attr(HLF_8); saved_attr2 = char_attr; /* save current attr */ } mb_c = c; } } } /* If a double-width char doesn't fit display a '>' in the * last column; the character is displayed at the start of the * next line. */ if (( # ifdef FEAT_RIGHTLEFT wp->w_p_rl ? (col <= 0) : # endif (col >= W_WIDTH(wp) - 1)) && (*mb_char2cells)(mb_c) == 2) { c = '>'; mb_c = c; mb_utf8 = FALSE; mb_l = 1; multi_attr = hl_attr(HLF_AT); /* Put pointer back so that the character will be * displayed at the start of the next line. */ --ptr; } else if (*ptr != NUL) ptr += mb_l - 1; /* If a double-width char doesn't fit at the left side display * a '<' in the first column. Don't do this for unprintable * characters. */ if (n_skip > 0 && mb_l > 1 && n_extra == 0) { n_extra = 1; c_extra = MB_FILLER_CHAR; c = ' '; if (area_attr == 0 && search_attr == 0) { n_attr = n_extra + 1; extra_attr = hl_attr(HLF_AT); saved_attr2 = char_attr; /* save current attr */ } mb_c = c; mb_utf8 = FALSE; mb_l = 1; } } #endif ++ptr; /* 'list': change char 160 to lcs_nbsp and space to lcs_space. */ if (wp->w_p_list && (((c == 160 #ifdef FEAT_MBYTE || (mb_utf8 && (mb_c == 160 || mb_c == 0x202f)) #endif ) && lcs_nbsp) || (c == ' ' && lcs_space && ptr - line <= trailcol))) { c = (c == ' ') ? lcs_space : lcs_nbsp; if (area_attr == 0 && search_attr == 0) { n_attr = 1; extra_attr = hl_attr(HLF_8); saved_attr2 = char_attr; /* save current attr */ } #ifdef FEAT_MBYTE mb_c = c; if (enc_utf8 && (*mb_char2len)(c) > 1) { mb_utf8 = TRUE; u8cc[0] = 0; c = 0xc0; } else mb_utf8 = FALSE; #endif } if (extra_check) { #ifdef FEAT_SPELL int can_spell = TRUE; #endif #ifdef FEAT_SYN_HL /* Get syntax attribute, unless still at the start of the line * (double-wide char that doesn't fit). */ v = (long)(ptr - line); if (has_syntax && v > 0) { /* Get the syntax attribute for the character. If there * is an error, disable syntax highlighting. */ save_did_emsg = did_emsg; did_emsg = FALSE; syntax_attr = get_syntax_attr((colnr_T)v - 1, # ifdef FEAT_SPELL has_spell ? &can_spell : # endif NULL, FALSE); if (did_emsg) { wp->w_s->b_syn_error = TRUE; has_syntax = FALSE; } else did_emsg = save_did_emsg; /* Need to get the line again, a multi-line regexp may * have made it invalid. */ line = ml_get_buf(wp->w_buffer, lnum, FALSE); ptr = line + v; if (!attr_pri) char_attr = syntax_attr; else char_attr = hl_combine_attr(syntax_attr, char_attr); # ifdef FEAT_CONCEAL /* no concealing past the end of the line, it interferes * with line highlighting */ if (c == NUL) syntax_flags = 0; else syntax_flags = get_syntax_info(&syntax_seqnr); # endif } #endif #ifdef FEAT_SPELL /* Check spelling (unless at the end of the line). * Only do this when there is no syntax highlighting, the * @Spell cluster is not used or the current syntax item * contains the @Spell cluster. */ if (has_spell && v >= word_end && v > cur_checked_col) { spell_attr = 0; # ifdef FEAT_SYN_HL if (!attr_pri) char_attr = syntax_attr; # endif if (c != 0 && ( # ifdef FEAT_SYN_HL !has_syntax || # endif can_spell)) { char_u *prev_ptr, *p; int len; hlf_T spell_hlf = HLF_COUNT; # ifdef FEAT_MBYTE if (has_mbyte) { prev_ptr = ptr - mb_l; v -= mb_l - 1; } else # endif prev_ptr = ptr - 1; /* Use nextline[] if possible, it has the start of the * next line concatenated. */ if ((prev_ptr - line) - nextlinecol >= 0) p = nextline + (prev_ptr - line) - nextlinecol; else p = prev_ptr; cap_col -= (int)(prev_ptr - line); len = spell_check(wp, p, &spell_hlf, &cap_col, nochange); word_end = v + len; /* In Insert mode only highlight a word that * doesn't touch the cursor. */ if (spell_hlf != HLF_COUNT && (State & INSERT) != 0 && wp->w_cursor.lnum == lnum && wp->w_cursor.col >= (colnr_T)(prev_ptr - line) && wp->w_cursor.col < (colnr_T)word_end) { spell_hlf = HLF_COUNT; spell_redraw_lnum = lnum; } if (spell_hlf == HLF_COUNT && p != prev_ptr && (p - nextline) + len > nextline_idx) { /* Remember that the good word continues at the * start of the next line. */ checked_lnum = lnum + 1; checked_col = (int)((p - nextline) + len - nextline_idx); } /* Turn index into actual attributes. */ if (spell_hlf != HLF_COUNT) spell_attr = highlight_attr[spell_hlf]; if (cap_col > 0) { if (p != prev_ptr && (p - nextline) + cap_col >= nextline_idx) { /* Remember that the word in the next line * must start with a capital. */ capcol_lnum = lnum + 1; cap_col = (int)((p - nextline) + cap_col - nextline_idx); } else /* Compute the actual column. */ cap_col += (int)(prev_ptr - line); } } } if (spell_attr != 0) { if (!attr_pri) char_attr = hl_combine_attr(char_attr, spell_attr); else char_attr = hl_combine_attr(spell_attr, char_attr); } #endif #ifdef FEAT_LINEBREAK /* * Found last space before word: check for line break. */ if (wp->w_p_lbr && vim_isbreak(c) && !vim_isbreak(*ptr)) { # ifdef FEAT_MBYTE int mb_off = has_mbyte ? (*mb_head_off)(line, ptr - 1) : 0; # endif char_u *p = ptr - ( # ifdef FEAT_MBYTE mb_off + # endif 1); /* TODO: is passing p for start of the line OK? */ n_extra = win_lbr_chartabsize(wp, line, p, (colnr_T)vcol, NULL) - 1; if (c == TAB && n_extra + col > W_WIDTH(wp)) n_extra = (int)wp->w_buffer->b_p_ts - vcol % (int)wp->w_buffer->b_p_ts - 1; # ifdef FEAT_MBYTE c_extra = mb_off > 0 ? MB_FILLER_CHAR : ' '; # else c_extra = ' '; # endif if (vim_iswhite(c)) { #ifdef FEAT_CONCEAL if (c == TAB) /* See "Tab alignment" below. */ FIX_FOR_BOGUSCOLS; #endif if (!wp->w_p_list) c = ' '; } } #endif if (trailcol != MAXCOL && ptr > line + trailcol && c == ' ') { c = lcs_trail; if (!attr_pri) { n_attr = 1; extra_attr = hl_attr(HLF_8); saved_attr2 = char_attr; /* save current attr */ } #ifdef FEAT_MBYTE mb_c = c; if (enc_utf8 && (*mb_char2len)(c) > 1) { mb_utf8 = TRUE; u8cc[0] = 0; c = 0xc0; } else mb_utf8 = FALSE; #endif } } /* * Handling of non-printable characters. */ if (!(chartab[c & 0xff] & CT_PRINT_CHAR)) { /* * when getting a character from the file, we may have to * turn it into something else on the way to putting it * into "ScreenLines". */ if (c == TAB && (!wp->w_p_list || lcs_tab1)) { int tab_len = 0; long vcol_adjusted = vcol; /* removed showbreak length */ #ifdef FEAT_LINEBREAK /* only adjust the tab_len, when at the first column * after the showbreak value was drawn */ if (*p_sbr != NUL && vcol == vcol_sbr && wp->w_p_wrap) vcol_adjusted = vcol - MB_CHARLEN(p_sbr); #endif /* tab amount depends on current column */ tab_len = (int)wp->w_buffer->b_p_ts - vcol_adjusted % (int)wp->w_buffer->b_p_ts - 1; #ifdef FEAT_LINEBREAK if (!wp->w_p_lbr || !wp->w_p_list) #endif /* tab amount depends on current column */ n_extra = tab_len; #ifdef FEAT_LINEBREAK else { char_u *p; int len = n_extra; int i; int saved_nextra = n_extra; #ifdef FEAT_CONCEAL if (vcol_off > 0) /* there are characters to conceal */ tab_len += vcol_off; /* boguscols before FIX_FOR_BOGUSCOLS macro from above */ if (wp->w_p_list && lcs_tab1 && old_boguscols > 0 && n_extra > tab_len) tab_len += n_extra - tab_len; #endif /* if n_extra > 0, it gives the number of chars, to * use for a tab, else we need to calculate the width * for a tab */ #ifdef FEAT_MBYTE len = (tab_len * mb_char2len(lcs_tab2)); if (n_extra > 0) len += n_extra - tab_len; #endif c = lcs_tab1; p = alloc((unsigned)(len + 1)); vim_memset(p, ' ', len); p[len] = NUL; p_extra_free = p; for (i = 0; i < tab_len; i++) { #ifdef FEAT_MBYTE mb_char2bytes(lcs_tab2, p); p += mb_char2len(lcs_tab2); n_extra += mb_char2len(lcs_tab2) - (saved_nextra > 0 ? 1 : 0); #else p[i] = lcs_tab2; #endif } p_extra = p_extra_free; #ifdef FEAT_CONCEAL /* n_extra will be increased by FIX_FOX_BOGUSCOLS * macro below, so need to adjust for that here */ if (vcol_off > 0) n_extra -= vcol_off; #endif } #endif #ifdef FEAT_CONCEAL { int vc_saved = vcol_off; /* Tab alignment should be identical regardless of * 'conceallevel' value. So tab compensates of all * previous concealed characters, and thus resets * vcol_off and boguscols accumulated so far in the * line. Note that the tab can be longer than * 'tabstop' when there are concealed characters. */ FIX_FOR_BOGUSCOLS; /* Make sure, the highlighting for the tab char will be * correctly set further below (effectively reverts the * FIX_FOR_BOGSUCOLS macro */ if (n_extra == tab_len + vc_saved && wp->w_p_list && lcs_tab1) tab_len += vc_saved; } #endif #ifdef FEAT_MBYTE mb_utf8 = FALSE; /* don't draw as UTF-8 */ #endif if (wp->w_p_list) { c = lcs_tab1; #ifdef FEAT_LINEBREAK if (wp->w_p_lbr) c_extra = NUL; /* using p_extra from above */ else #endif c_extra = lcs_tab2; n_attr = tab_len + 1; extra_attr = hl_attr(HLF_8); saved_attr2 = char_attr; /* save current attr */ #ifdef FEAT_MBYTE mb_c = c; if (enc_utf8 && (*mb_char2len)(c) > 1) { mb_utf8 = TRUE; u8cc[0] = 0; c = 0xc0; } #endif } else { c_extra = ' '; c = ' '; } } else if (c == NUL && (wp->w_p_list || ((fromcol >= 0 || fromcol_prev >= 0) && tocol > vcol && VIsual_mode != Ctrl_V && ( # ifdef FEAT_RIGHTLEFT wp->w_p_rl ? (col >= 0) : # endif (col < W_WIDTH(wp))) && !(noinvcur && lnum == wp->w_cursor.lnum && (colnr_T)vcol == wp->w_virtcol))) && lcs_eol_one > 0) { /* Display a '$' after the line or highlight an extra * character if the line break is included. */ #if defined(FEAT_DIFF) || defined(LINE_ATTR) /* For a diff line the highlighting continues after the * "$". */ if ( # ifdef FEAT_DIFF diff_hlf == (hlf_T)0 # ifdef LINE_ATTR && # endif # endif # ifdef LINE_ATTR line_attr == 0 # endif ) #endif { #ifdef FEAT_VIRTUALEDIT /* In virtualedit, visual selections may extend * beyond end of line. */ if (area_highlighting && virtual_active() && tocol != MAXCOL && vcol < tocol) n_extra = 0; else #endif { p_extra = at_end_str; n_extra = 1; c_extra = NUL; } } if (wp->w_p_list && lcs_eol > 0) c = lcs_eol; else c = ' '; lcs_eol_one = -1; --ptr; /* put it back at the NUL */ if (!attr_pri) { extra_attr = hl_attr(HLF_AT); n_attr = 1; } #ifdef FEAT_MBYTE mb_c = c; if (enc_utf8 && (*mb_char2len)(c) > 1) { mb_utf8 = TRUE; u8cc[0] = 0; c = 0xc0; } else mb_utf8 = FALSE; /* don't draw as UTF-8 */ #endif } else if (c != NUL) { p_extra = transchar(c); if (n_extra == 0) n_extra = byte2cells(c) - 1; #ifdef FEAT_RIGHTLEFT if ((dy_flags & DY_UHEX) && wp->w_p_rl) rl_mirror(p_extra); /* reverse "<12>" */ #endif c_extra = NUL; #ifdef FEAT_LINEBREAK if (wp->w_p_lbr) { char_u *p; c = *p_extra; p = alloc((unsigned)n_extra + 1); vim_memset(p, ' ', n_extra); STRNCPY(p, p_extra + 1, STRLEN(p_extra) - 1); p[n_extra] = NUL; p_extra_free = p_extra = p; } else #endif { n_extra = byte2cells(c) - 1; c = *p_extra++; } if (!attr_pri) { n_attr = n_extra + 1; extra_attr = hl_attr(HLF_8); saved_attr2 = char_attr; /* save current attr */ } #ifdef FEAT_MBYTE mb_utf8 = FALSE; /* don't draw as UTF-8 */ #endif } #ifdef FEAT_VIRTUALEDIT else if (VIsual_active && (VIsual_mode == Ctrl_V || VIsual_mode == 'v') && virtual_active() && tocol != MAXCOL && vcol < tocol && ( # ifdef FEAT_RIGHTLEFT wp->w_p_rl ? (col >= 0) : # endif (col < W_WIDTH(wp)))) { c = ' '; --ptr; /* put it back at the NUL */ } #endif #if defined(LINE_ATTR) else if (( # ifdef FEAT_DIFF diff_hlf != (hlf_T)0 || # endif line_attr != 0 ) && ( # ifdef FEAT_RIGHTLEFT wp->w_p_rl ? (col >= 0) : # endif (col # ifdef FEAT_CONCEAL - boguscols # endif < W_WIDTH(wp)))) { /* Highlight until the right side of the window */ c = ' '; --ptr; /* put it back at the NUL */ /* Remember we do the char for line highlighting. */ ++did_line_attr; /* don't do search HL for the rest of the line */ if (line_attr != 0 && char_attr == search_attr && col > 0) char_attr = line_attr; # ifdef FEAT_DIFF if (diff_hlf == HLF_TXD) { diff_hlf = HLF_CHD; if (attr == 0 || char_attr != attr) { char_attr = hl_attr(diff_hlf); if (wp->w_p_cul && lnum == wp->w_cursor.lnum) char_attr = hl_combine_attr(char_attr, hl_attr(HLF_CUL)); } } # endif } #endif } #ifdef FEAT_CONCEAL if ( wp->w_p_cole > 0 && (wp != curwin || lnum != wp->w_cursor.lnum || conceal_cursor_line(wp) ) && ( (syntax_flags & HL_CONCEAL) != 0 || has_match_conc) && !(lnum_in_visual_area && vim_strchr(wp->w_p_cocu, 'v') == NULL)) { char_attr = conceal_attr; if (prev_syntax_id != syntax_seqnr && (syn_get_sub_char() != NUL || match_conc || wp->w_p_cole == 1) && wp->w_p_cole != 3) { /* First time at this concealed item: display one * character. */ if (match_conc) c = match_conc; else if (syn_get_sub_char() != NUL) c = syn_get_sub_char(); else if (lcs_conceal != NUL) c = lcs_conceal; else c = ' '; prev_syntax_id = syntax_seqnr; if (n_extra > 0) vcol_off += n_extra; vcol += n_extra; if (wp->w_p_wrap && n_extra > 0) { # ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { col -= n_extra; boguscols -= n_extra; } else # endif { boguscols += n_extra; col += n_extra; } } n_extra = 0; n_attr = 0; } else if (n_skip == 0) { is_concealing = TRUE; n_skip = 1; } # ifdef FEAT_MBYTE mb_c = c; if (enc_utf8 && (*mb_char2len)(c) > 1) { mb_utf8 = TRUE; u8cc[0] = 0; c = 0xc0; } else mb_utf8 = FALSE; /* don't draw as UTF-8 */ # endif } else { prev_syntax_id = 0; is_concealing = FALSE; } #endif /* FEAT_CONCEAL */ } #ifdef FEAT_CONCEAL /* In the cursor line and we may be concealing characters: correct * the cursor column when we reach its position. */ if (!did_wcol && draw_state == WL_LINE && wp == curwin && lnum == wp->w_cursor.lnum && conceal_cursor_line(wp) && (int)wp->w_virtcol <= vcol + n_skip) { wp->w_wcol = col - boguscols; wp->w_wrow = row; did_wcol = TRUE; } #endif /* Don't override visual selection highlighting. */ if (n_attr > 0 && draw_state == WL_LINE && !attr_pri) char_attr = extra_attr; #if defined(FEAT_XIM) && (defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MACVIM)) /* XIM don't send preedit_start and preedit_end, but they send * preedit_changed and commit. Thus Vim can't set "im_is_active", use * im_is_preediting() here. */ if ( # ifndef FEAT_GUI_MACVIM xic != NULL && # endif lnum == wp->w_cursor.lnum && (State & INSERT) # ifndef FEAT_GUI_MACVIM && !p_imdisable # endif && im_is_preediting() && draw_state == WL_LINE) { colnr_T tcol; if (preedit_end_col == MAXCOL) getvcol(curwin, &(wp->w_cursor), &tcol, NULL, NULL); else tcol = preedit_end_col; if ((long)preedit_start_col <= vcol && vcol < (long)tcol) { if (feedback_old_attr < 0) { feedback_col = 0; feedback_old_attr = char_attr; } char_attr = im_get_feedback_attr(feedback_col); if (char_attr < 0) char_attr = feedback_old_attr; feedback_col++; } else if (feedback_old_attr >= 0) { char_attr = feedback_old_attr; feedback_old_attr = -1; feedback_col = 0; } } #endif /* * Handle the case where we are in column 0 but not on the first * character of the line and the user wants us to show us a * special character (via 'listchars' option "precedes:<char>". */ if (lcs_prec_todo != NUL && wp->w_p_list && (wp->w_p_wrap ? wp->w_skipcol > 0 : wp->w_leftcol > 0) #ifdef FEAT_DIFF && filler_todo <= 0 #endif && draw_state > WL_NR && c != NUL) { c = lcs_prec; lcs_prec_todo = NUL; #ifdef FEAT_MBYTE if (has_mbyte && (*mb_char2cells)(mb_c) > 1) { /* Double-width character being overwritten by the "precedes" * character, need to fill up half the character. */ c_extra = MB_FILLER_CHAR; n_extra = 1; n_attr = 2; extra_attr = hl_attr(HLF_AT); } mb_c = c; if (enc_utf8 && (*mb_char2len)(c) > 1) { mb_utf8 = TRUE; u8cc[0] = 0; c = 0xc0; } else mb_utf8 = FALSE; /* don't draw as UTF-8 */ #endif if (!attr_pri) { saved_attr3 = char_attr; /* save current attr */ char_attr = hl_attr(HLF_AT); /* later copied to char_attr */ n_attr3 = 1; } } /* * At end of the text line or just after the last character. */ if (c == NUL #if defined(LINE_ATTR) || did_line_attr == 1 #endif ) { #ifdef FEAT_SEARCH_EXTRA long prevcol = (long)(ptr - line) - (c == NUL); /* we're not really at that column when skipping some text */ if ((long)(wp->w_p_wrap ? wp->w_skipcol : wp->w_leftcol) > prevcol) ++prevcol; #endif /* Invert at least one char, used for Visual and empty line or * highlight match at end of line. If it's beyond the last * char on the screen, just overwrite that one (tricky!) Not * needed when a '$' was displayed for 'list'. */ #ifdef FEAT_SEARCH_EXTRA prevcol_hl_flag = FALSE; if (prevcol == (long)search_hl.startcol) prevcol_hl_flag = TRUE; else { cur = wp->w_match_head; while (cur != NULL) { if (prevcol == (long)cur->hl.startcol) { prevcol_hl_flag = TRUE; break; } cur = cur->next; } } #endif if (lcs_eol == lcs_eol_one && ((area_attr != 0 && vcol == fromcol && (VIsual_mode != Ctrl_V || lnum == VIsual.lnum || lnum == curwin->w_cursor.lnum) && c == NUL) #ifdef FEAT_SEARCH_EXTRA /* highlight 'hlsearch' match at end of line */ || (prevcol_hl_flag == TRUE # if defined(LINE_ATTR) && did_line_attr <= 1 # endif ) #endif )) { int n = 0; #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { if (col < 0) n = 1; } else #endif { if (col >= W_WIDTH(wp)) n = -1; } if (n != 0) { /* At the window boundary, highlight the last character * instead (better than nothing). */ off += n; col += n; } else { /* Add a blank character to highlight. */ ScreenLines[off] = ' '; #ifdef FEAT_MBYTE if (enc_utf8) ScreenLinesUC[off] = 0; #endif } #ifdef FEAT_SEARCH_EXTRA if (area_attr == 0) { /* Use attributes from match with highest priority among * 'search_hl' and the match list. */ char_attr = search_hl.attr; cur = wp->w_match_head; shl_flag = FALSE; while (cur != NULL || shl_flag == FALSE) { if (shl_flag == FALSE && ((cur != NULL && cur->priority > SEARCH_HL_PRIORITY) || cur == NULL)) { shl = &search_hl; shl_flag = TRUE; } else shl = &cur->hl; if ((ptr - line) - 1 == (long)shl->startcol) char_attr = shl->attr; if (shl != &search_hl && cur != NULL) cur = cur->next; } } #endif ScreenAttrs[off] = char_attr; #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { --col; --off; } else #endif { ++col; ++off; } ++vcol; #ifdef FEAT_SYN_HL eol_hl_off = 1; #endif } } /* * At end of the text line. */ if (c == NUL) { #ifdef FEAT_SYN_HL if (eol_hl_off > 0 && vcol - eol_hl_off == (long)wp->w_virtcol && lnum == wp->w_cursor.lnum) { /* highlight last char after line */ --col; --off; --vcol; } /* Highlight 'cursorcolumn' & 'colorcolumn' past end of the line. */ if (wp->w_p_wrap) v = wp->w_skipcol; else v = wp->w_leftcol; /* check if line ends before left margin */ if (vcol < v + col - win_col_off(wp)) vcol = v + col - win_col_off(wp); #ifdef FEAT_CONCEAL /* Get rid of the boguscols now, we want to draw until the right * edge for 'cursorcolumn'. */ col -= boguscols; boguscols = 0; #endif if (draw_color_col) draw_color_col = advance_color_col(VCOL_HLC, &color_cols); if (((wp->w_p_cuc && (int)wp->w_virtcol >= VCOL_HLC - eol_hl_off && (int)wp->w_virtcol < W_WIDTH(wp) * (row - startrow + 1) + v && lnum != wp->w_cursor.lnum) || draw_color_col) # ifdef FEAT_RIGHTLEFT && !wp->w_p_rl # endif ) { int rightmost_vcol = 0; int i; if (wp->w_p_cuc) rightmost_vcol = wp->w_virtcol; if (draw_color_col) /* determine rightmost colorcolumn to possibly draw */ for (i = 0; color_cols[i] >= 0; ++i) if (rightmost_vcol < color_cols[i]) rightmost_vcol = color_cols[i]; while (col < W_WIDTH(wp)) { ScreenLines[off] = ' '; #ifdef FEAT_MBYTE if (enc_utf8) ScreenLinesUC[off] = 0; #endif ++col; if (draw_color_col) draw_color_col = advance_color_col(VCOL_HLC, &color_cols); if (wp->w_p_cuc && VCOL_HLC == (long)wp->w_virtcol) ScreenAttrs[off++] = hl_attr(HLF_CUC); else if (draw_color_col && VCOL_HLC == *color_cols) ScreenAttrs[off++] = hl_attr(HLF_MC); else ScreenAttrs[off++] = 0; if (VCOL_HLC >= rightmost_vcol) break; ++vcol; } } #endif SCREEN_LINE(screen_row, W_WINCOL(wp), col, (int)W_WIDTH(wp), wp->w_p_rl); row++; /* * Update w_cline_height and w_cline_folded if the cursor line was * updated (saves a call to plines() later). */ if (wp == curwin && lnum == curwin->w_cursor.lnum) { curwin->w_cline_row = startrow; curwin->w_cline_height = row - startrow; #ifdef FEAT_FOLDING curwin->w_cline_folded = FALSE; #endif curwin->w_valid |= (VALID_CHEIGHT|VALID_CROW); } break; } /* line continues beyond line end */ if (lcs_ext && !wp->w_p_wrap #ifdef FEAT_DIFF && filler_todo <= 0 #endif && ( #ifdef FEAT_RIGHTLEFT wp->w_p_rl ? col == 0 : #endif col == W_WIDTH(wp) - 1) && (*ptr != NUL || (wp->w_p_list && lcs_eol_one > 0) || (n_extra && (c_extra != NUL || *p_extra != NUL)))) { c = lcs_ext; char_attr = hl_attr(HLF_AT); #ifdef FEAT_MBYTE mb_c = c; if (enc_utf8 && (*mb_char2len)(c) > 1) { mb_utf8 = TRUE; u8cc[0] = 0; c = 0xc0; } else mb_utf8 = FALSE; #endif } #ifdef FEAT_SYN_HL /* advance to the next 'colorcolumn' */ if (draw_color_col) draw_color_col = advance_color_col(VCOL_HLC, &color_cols); /* Highlight the cursor column if 'cursorcolumn' is set. But don't * highlight the cursor position itself. * Also highlight the 'colorcolumn' if it is different than * 'cursorcolumn' */ vcol_save_attr = -1; if (draw_state == WL_LINE && !lnum_in_visual_area) { if (wp->w_p_cuc && VCOL_HLC == (long)wp->w_virtcol && lnum != wp->w_cursor.lnum) { vcol_save_attr = char_attr; char_attr = hl_combine_attr(char_attr, hl_attr(HLF_CUC)); } else if (draw_color_col && VCOL_HLC == *color_cols) { vcol_save_attr = char_attr; char_attr = hl_combine_attr(char_attr, hl_attr(HLF_MC)); } } #endif /* * Store character to be displayed. * Skip characters that are left of the screen for 'nowrap'. */ vcol_prev = vcol; if (draw_state < WL_LINE || n_skip <= 0) { /* * Store the character. */ #if defined(FEAT_RIGHTLEFT) && defined(FEAT_MBYTE) if (has_mbyte && wp->w_p_rl && (*mb_char2cells)(mb_c) > 1) { /* A double-wide character is: put first halve in left cell. */ --off; --col; } #endif ScreenLines[off] = c; #ifdef FEAT_MBYTE if (enc_dbcs == DBCS_JPNU) { if ((mb_c & 0xff00) == 0x8e00) ScreenLines[off] = 0x8e; ScreenLines2[off] = mb_c & 0xff; } else if (enc_utf8) { if (mb_utf8) { int i; ScreenLinesUC[off] = mb_c; if ((c & 0xff) == 0) ScreenLines[off] = 0x80; /* avoid storing zero */ for (i = 0; i < Screen_mco; ++i) { ScreenLinesC[i][off] = u8cc[i]; if (u8cc[i] == 0) break; } } else ScreenLinesUC[off] = 0; } if (multi_attr) { ScreenAttrs[off] = multi_attr; multi_attr = 0; } else #endif ScreenAttrs[off] = char_attr; #ifdef FEAT_MBYTE if (has_mbyte && (*mb_char2cells)(mb_c) > 1) { /* Need to fill two screen columns. */ ++off; ++col; if (enc_utf8) /* UTF-8: Put a 0 in the second screen char. */ ScreenLines[off] = 0; else /* DBCS: Put second byte in the second screen char. */ ScreenLines[off] = mb_c & 0xff; ++vcol; /* When "tocol" is halfway a character, set it to the end of * the character, otherwise highlighting won't stop. */ if (tocol == vcol) ++tocol; #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { /* now it's time to backup one cell */ --off; --col; } #endif } #endif #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { --off; --col; } else #endif { ++off; ++col; } } #ifdef FEAT_CONCEAL else if (wp->w_p_cole > 0 && is_concealing) { --n_skip; ++vcol_off; if (n_extra > 0) vcol_off += n_extra; if (wp->w_p_wrap) { /* * Special voodoo required if 'wrap' is on. * * Advance the column indicator to force the line * drawing to wrap early. This will make the line * take up the same screen space when parts are concealed, * so that cursor line computations aren't messed up. * * To avoid the fictitious advance of 'col' causing * trailing junk to be written out of the screen line * we are building, 'boguscols' keeps track of the number * of bad columns we have advanced. */ if (n_extra > 0) { vcol += n_extra; # ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { col -= n_extra; boguscols -= n_extra; } else # endif { col += n_extra; boguscols += n_extra; } n_extra = 0; n_attr = 0; } # ifdef FEAT_MBYTE if (has_mbyte && (*mb_char2cells)(mb_c) > 1) { /* Need to fill two screen columns. */ # ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { --boguscols; --col; } else # endif { ++boguscols; ++col; } } # endif # ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { --boguscols; --col; } else # endif { ++boguscols; ++col; } } else { if (n_extra > 0) { vcol += n_extra; n_extra = 0; n_attr = 0; } } } #endif /* FEAT_CONCEAL */ else --n_skip; /* Only advance the "vcol" when after the 'number' or 'relativenumber' * column. */ if (draw_state > WL_NR #ifdef FEAT_DIFF && filler_todo <= 0 #endif ) ++vcol; #ifdef FEAT_SYN_HL if (vcol_save_attr >= 0) char_attr = vcol_save_attr; #endif /* restore attributes after "predeces" in 'listchars' */ if (draw_state > WL_NR && n_attr3 > 0 && --n_attr3 == 0) char_attr = saved_attr3; /* restore attributes after last 'listchars' or 'number' char */ if (n_attr > 0 && draw_state == WL_LINE && --n_attr == 0) char_attr = saved_attr2; /* * At end of screen line and there is more to come: Display the line * so far. If there is no more to display it is caught above. */ if (( #ifdef FEAT_RIGHTLEFT wp->w_p_rl ? (col < 0) : #endif (col >= W_WIDTH(wp))) && (*ptr != NUL #ifdef FEAT_DIFF || filler_todo > 0 #endif || (wp->w_p_list && lcs_eol != NUL && p_extra != at_end_str) || (n_extra != 0 && (c_extra != NUL || *p_extra != NUL))) ) { #ifdef FEAT_CONCEAL SCREEN_LINE(screen_row, W_WINCOL(wp), col - boguscols, (int)W_WIDTH(wp), wp->w_p_rl); boguscols = 0; #else SCREEN_LINE(screen_row, W_WINCOL(wp), col, (int)W_WIDTH(wp), wp->w_p_rl); #endif ++row; ++screen_row; /* When not wrapping and finished diff lines, or when displayed * '$' and highlighting until last column, break here. */ if ((!wp->w_p_wrap #ifdef FEAT_DIFF && filler_todo <= 0 #endif ) || lcs_eol_one == -1) break; /* When the window is too narrow draw all "@" lines. */ if (draw_state != WL_LINE #ifdef FEAT_DIFF && filler_todo <= 0 #endif ) { win_draw_end(wp, '@', ' ', row, wp->w_height, HLF_AT); #ifdef FEAT_VERTSPLIT draw_vsep_win(wp, row); #endif row = endrow; } /* When line got too long for screen break here. */ if (row == endrow) { ++row; break; } if (screen_cur_row == screen_row - 1 #ifdef FEAT_DIFF && filler_todo <= 0 #endif && W_WIDTH(wp) == Columns) { /* Remember that the line wraps, used for modeless copy. */ LineWraps[screen_row - 1] = TRUE; /* * Special trick to make copy/paste of wrapped lines work with * xterm/screen: write an extra character beyond the end of * the line. This will work with all terminal types * (regardless of the xn,am settings). * Only do this on a fast tty. * Only do this if the cursor is on the current line * (something has been written in it). * Don't do this for the GUI. * Don't do this for double-width characters. * Don't do this for a window not at the right screen border. */ if (p_tf #ifdef FEAT_GUI && !gui.in_use #endif #ifdef FEAT_MBYTE && !(has_mbyte && ((*mb_off2cells)(LineOffset[screen_row], LineOffset[screen_row] + screen_Columns) == 2 || (*mb_off2cells)(LineOffset[screen_row - 1] + (int)Columns - 2, LineOffset[screen_row] + screen_Columns) == 2)) #endif ) { /* First make sure we are at the end of the screen line, * then output the same character again to let the * terminal know about the wrap. If the terminal doesn't * auto-wrap, we overwrite the character. */ if (screen_cur_col != W_WIDTH(wp)) screen_char(LineOffset[screen_row - 1] + (unsigned)Columns - 1, screen_row - 1, (int)(Columns - 1)); #ifdef FEAT_MBYTE /* When there is a multi-byte character, just output a * space to keep it simple. */ if (has_mbyte && MB_BYTE2LEN(ScreenLines[LineOffset[ screen_row - 1] + (Columns - 1)]) > 1) out_char(' '); else #endif out_char(ScreenLines[LineOffset[screen_row - 1] + (Columns - 1)]); /* force a redraw of the first char on the next line */ ScreenAttrs[LineOffset[screen_row]] = (sattr_T)-1; screen_start(); /* don't know where cursor is now */ } } col = 0; off = (unsigned)(current_ScreenLine - ScreenLines); #ifdef FEAT_RIGHTLEFT if (wp->w_p_rl) { col = W_WIDTH(wp) - 1; /* col is not used if breaking! */ off += col; } #endif /* reset the drawing state for the start of a wrapped line */ draw_state = WL_START; saved_n_extra = n_extra; saved_p_extra = p_extra; saved_c_extra = c_extra; saved_char_attr = char_attr; n_extra = 0; lcs_prec_todo = lcs_prec; #ifdef FEAT_LINEBREAK # ifdef FEAT_DIFF if (filler_todo <= 0) # endif need_showbreak = TRUE; #endif #ifdef FEAT_DIFF --filler_todo; /* When the filler lines are actually below the last line of the * file, don't draw the line itself, break here. */ if (filler_todo == 0 && wp->w_botfill) break; #endif } } /* for every character in the line */ #ifdef FEAT_SPELL /* After an empty line check first word for capital. */ if (*skipwhite(line) == NUL) { capcol_lnum = lnum + 1; cap_col = 0; } #endif return row; } #ifdef FEAT_MBYTE static int comp_char_differs __ARGS((int, int)); /* * Return if the composing characters at "off_from" and "off_to" differ. * Only to be used when ScreenLinesUC[off_from] != 0. */ static int comp_char_differs(off_from, off_to) int off_from; int off_to; { int i; for (i = 0; i < Screen_mco; ++i) { if (ScreenLinesC[i][off_from] != ScreenLinesC[i][off_to]) return TRUE; if (ScreenLinesC[i][off_from] == 0) break; } return FALSE; } #endif /* * Check whether the given character needs redrawing: * - the (first byte of the) character is different * - the attributes are different * - the character is multi-byte and the next byte is different * - the character is two cells wide and the second cell differs. */ static int char_needs_redraw(off_from, off_to, cols) int off_from; int off_to; int cols; { if (cols > 0 && ((ScreenLines[off_from] != ScreenLines[off_to] || ScreenAttrs[off_from] != ScreenAttrs[off_to]) #ifdef FEAT_MBYTE || (enc_dbcs != 0 && MB_BYTE2LEN(ScreenLines[off_from]) > 1 && (enc_dbcs == DBCS_JPNU && ScreenLines[off_from] == 0x8e ? ScreenLines2[off_from] != ScreenLines2[off_to] : (cols > 1 && ScreenLines[off_from + 1] != ScreenLines[off_to + 1]))) || (enc_utf8 && (ScreenLinesUC[off_from] != ScreenLinesUC[off_to] || (ScreenLinesUC[off_from] != 0 && comp_char_differs(off_from, off_to)) || ((*mb_off2cells)(off_from, off_from + cols) > 1 && ScreenLines[off_from + 1] != ScreenLines[off_to + 1]))) #endif )) return TRUE; return FALSE; } /* * Move one "cooked" screen line to the screen, but only the characters that * have actually changed. Handle insert/delete character. * "coloff" gives the first column on the screen for this line. * "endcol" gives the columns where valid characters are. * "clear_width" is the width of the window. It's > 0 if the rest of the line * needs to be cleared, negative otherwise. * "rlflag" is TRUE in a rightleft window: * When TRUE and "clear_width" > 0, clear columns 0 to "endcol" * When FALSE and "clear_width" > 0, clear columns "endcol" to "clear_width" */ static void screen_line(row, coloff, endcol, clear_width #ifdef FEAT_RIGHTLEFT , rlflag #endif ) int row; int coloff; int endcol; int clear_width; #ifdef FEAT_RIGHTLEFT int rlflag; #endif { unsigned off_from; unsigned off_to; #ifdef FEAT_MBYTE unsigned max_off_from; unsigned max_off_to; #endif int col = 0; #if defined(FEAT_GUI) || defined(UNIX) || defined(FEAT_VERTSPLIT) int hl; #endif int force = FALSE; /* force update rest of the line */ int redraw_this /* bool: does character need redraw? */ #ifdef FEAT_GUI = TRUE /* For GUI when while-loop empty */ #endif ; int redraw_next; /* redraw_this for next character */ #ifdef FEAT_MBYTE int clear_next = FALSE; int char_cells; /* 1: normal char */ /* 2: occupies two display cells */ # define CHAR_CELLS char_cells #else # define CHAR_CELLS 1 #endif /* Check for illegal row and col, just in case. */ if (row >= Rows) row = Rows - 1; if (endcol > Columns) endcol = Columns; # ifdef FEAT_CLIPBOARD clip_may_clear_selection(row, row); # endif off_from = (unsigned)(current_ScreenLine - ScreenLines); off_to = LineOffset[row] + coloff; #ifdef FEAT_MBYTE max_off_from = off_from + screen_Columns; max_off_to = LineOffset[row] + screen_Columns; #endif #ifdef FEAT_RIGHTLEFT if (rlflag) { /* Clear rest first, because it's left of the text. */ if (clear_width > 0) { while (col <= endcol && ScreenLines[off_to] == ' ' && ScreenAttrs[off_to] == 0 # ifdef FEAT_MBYTE && (!enc_utf8 || ScreenLinesUC[off_to] == 0) # endif ) { ++off_to; ++col; } if (col <= endcol) screen_fill(row, row + 1, col + coloff, endcol + coloff + 1, ' ', ' ', 0); } col = endcol + 1; off_to = LineOffset[row] + col + coloff; off_from += col; endcol = (clear_width > 0 ? clear_width : -clear_width); } #endif /* FEAT_RIGHTLEFT */ redraw_next = char_needs_redraw(off_from, off_to, endcol - col); while (col < endcol) { #ifdef FEAT_MBYTE if (has_mbyte && (col + 1 < endcol)) char_cells = (*mb_off2cells)(off_from, max_off_from); else char_cells = 1; #endif redraw_this = redraw_next; redraw_next = force || char_needs_redraw(off_from + CHAR_CELLS, off_to + CHAR_CELLS, endcol - col - CHAR_CELLS); #ifdef FEAT_GUI /* If the next character was bold, then redraw the current character to * remove any pixels that might have spilt over into us. This only * happens in the GUI. */ if (redraw_next && gui.in_use) { hl = ScreenAttrs[off_to + CHAR_CELLS]; if (hl > HL_ALL) hl = syn_attr2attr(hl); # ifndef FEAT_GUI_MACVIM /* see comment on subpixel antialiasing */ if (hl & HL_BOLD) # endif redraw_this = TRUE; } #endif if (redraw_this) { /* * Special handling when 'xs' termcap flag set (hpterm): * Attributes for characters are stored at the position where the * cursor is when writing the highlighting code. The * start-highlighting code must be written with the cursor on the * first highlighted character. The stop-highlighting code must * be written with the cursor just after the last highlighted * character. * Overwriting a character doesn't remove it's highlighting. Need * to clear the rest of the line, and force redrawing it * completely. */ if ( p_wiv && !force #ifdef FEAT_GUI && !gui.in_use #endif && ScreenAttrs[off_to] != 0 && ScreenAttrs[off_from] != ScreenAttrs[off_to]) { /* * Need to remove highlighting attributes here. */ windgoto(row, col + coloff); out_str(T_CE); /* clear rest of this screen line */ screen_start(); /* don't know where cursor is now */ force = TRUE; /* force redraw of rest of the line */ redraw_next = TRUE; /* or else next char would miss out */ /* * If the previous character was highlighted, need to stop * highlighting at this character. */ if (col + coloff > 0 && ScreenAttrs[off_to - 1] != 0) { screen_attr = ScreenAttrs[off_to - 1]; term_windgoto(row, col + coloff); screen_stop_highlight(); } else screen_attr = 0; /* highlighting has stopped */ } #ifdef FEAT_MBYTE if (enc_dbcs != 0) { /* Check if overwriting a double-byte with a single-byte or * the other way around requires another character to be * redrawn. For UTF-8 this isn't needed, because comparing * ScreenLinesUC[] is sufficient. */ if (char_cells == 1 && col + 1 < endcol && (*mb_off2cells)(off_to, max_off_to) > 1) { /* Writing a single-cell character over a double-cell * character: need to redraw the next cell. */ ScreenLines[off_to + 1] = 0; redraw_next = TRUE; } else if (char_cells == 2 && col + 2 < endcol && (*mb_off2cells)(off_to, max_off_to) == 1 && (*mb_off2cells)(off_to + 1, max_off_to) > 1) { /* Writing the second half of a double-cell character over * a double-cell character: need to redraw the second * cell. */ ScreenLines[off_to + 2] = 0; redraw_next = TRUE; } if (enc_dbcs == DBCS_JPNU) ScreenLines2[off_to] = ScreenLines2[off_from]; } /* When writing a single-width character over a double-width * character and at the end of the redrawn text, need to clear out * the right halve of the old character. * Also required when writing the right halve of a double-width * char over the left halve of an existing one. */ if (has_mbyte && col + char_cells == endcol && ((char_cells == 1 && (*mb_off2cells)(off_to, max_off_to) > 1) || (char_cells == 2 && (*mb_off2cells)(off_to, max_off_to) == 1 && (*mb_off2cells)(off_to + 1, max_off_to) > 1))) clear_next = TRUE; #endif ScreenLines[off_to] = ScreenLines[off_from]; #ifdef FEAT_MBYTE if (enc_utf8) { ScreenLinesUC[off_to] = ScreenLinesUC[off_from]; if (ScreenLinesUC[off_from] != 0) { int i; for (i = 0; i < Screen_mco; ++i) ScreenLinesC[i][off_to] = ScreenLinesC[i][off_from]; } } if (char_cells == 2) ScreenLines[off_to + 1] = ScreenLines[off_from + 1]; #endif #if defined(FEAT_GUI) || defined(UNIX) /* The bold trick makes a single column of pixels appear in the * next character. When a bold character is removed, the next * character should be redrawn too. This happens for our own GUI * and for some xterms. */ if ( # ifdef FEAT_GUI gui.in_use # endif # if defined(FEAT_GUI) && defined(UNIX) || # endif # ifdef UNIX term_is_xterm # endif ) { hl = ScreenAttrs[off_to]; if (hl > HL_ALL) hl = syn_attr2attr(hl); # ifndef FEAT_GUI_MACVIM /* see comment on subpixel antialiasing */ if (hl & HL_BOLD) # endif redraw_next = TRUE; } #endif ScreenAttrs[off_to] = ScreenAttrs[off_from]; #ifdef FEAT_MBYTE /* For simplicity set the attributes of second half of a * double-wide character equal to the first half. */ if (char_cells == 2) ScreenAttrs[off_to + 1] = ScreenAttrs[off_from]; if (enc_dbcs != 0 && char_cells == 2) screen_char_2(off_to, row, col + coloff); else #endif screen_char(off_to, row, col + coloff); } else if ( p_wiv #ifdef FEAT_GUI && !gui.in_use #endif && col + coloff > 0) { if (ScreenAttrs[off_to] == ScreenAttrs[off_to - 1]) { /* * Don't output stop-highlight when moving the cursor, it will * stop the highlighting when it should continue. */ screen_attr = 0; } else if (screen_attr != 0) screen_stop_highlight(); } off_to += CHAR_CELLS; off_from += CHAR_CELLS; col += CHAR_CELLS; } #ifdef FEAT_MBYTE if (clear_next) { /* Clear the second half of a double-wide character of which the left * half was overwritten with a single-wide character. */ ScreenLines[off_to] = ' '; if (enc_utf8) ScreenLinesUC[off_to] = 0; screen_char(off_to, row, col + coloff); } #endif if (clear_width > 0 #ifdef FEAT_RIGHTLEFT && !rlflag #endif ) { #ifdef FEAT_GUI int startCol = col; #endif /* blank out the rest of the line */ while (col < clear_width && ScreenLines[off_to] == ' ' && ScreenAttrs[off_to] == 0 #ifdef FEAT_MBYTE && (!enc_utf8 || ScreenLinesUC[off_to] == 0) #endif ) { ++off_to; ++col; } if (col < clear_width) { #ifdef FEAT_GUI /* * In the GUI, clearing the rest of the line may leave pixels * behind if the first character cleared was bold. Some bold * fonts spill over the left. In this case we redraw the previous * character too. If we didn't skip any blanks above, then we * only redraw if the character wasn't already redrawn anyway. */ if (gui.in_use && (col > startCol || !redraw_this)) { hl = ScreenAttrs[off_to]; # ifndef FEAT_GUI_MACVIM /* see comment on subpixel antialiasing */ if (hl > HL_ALL || (hl & HL_BOLD)) # endif { int prev_cells = 1; # ifdef FEAT_MBYTE if (enc_utf8) /* for utf-8, ScreenLines[char_offset + 1] == 0 means * that its width is 2. */ prev_cells = ScreenLines[off_to - 1] == 0 ? 2 : 1; else if (enc_dbcs != 0) { /* find previous character by counting from first * column and get its width. */ unsigned off = LineOffset[row]; unsigned max_off = LineOffset[row] + screen_Columns; while (off < off_to) { prev_cells = (*mb_off2cells)(off, max_off); off += prev_cells; } } if (enc_dbcs != 0 && prev_cells > 1) screen_char_2(off_to - prev_cells, row, col + coloff - prev_cells); else # endif screen_char(off_to - prev_cells, row, col + coloff - prev_cells); } } #endif screen_fill(row, row + 1, col + coloff, clear_width + coloff, ' ', ' ', 0); #ifdef FEAT_VERTSPLIT off_to += clear_width - col; col = clear_width; #endif } } if (clear_width > 0) { #ifdef FEAT_VERTSPLIT /* For a window that's left of another, draw the separator char. */ if (col + coloff < Columns) { int c; c = fillchar_vsep(&hl); if (ScreenLines[off_to] != (schar_T)c # ifdef FEAT_MBYTE || (enc_utf8 && (int)ScreenLinesUC[off_to] != (c >= 0x80 ? c : 0)) # endif || ScreenAttrs[off_to] != hl) { ScreenLines[off_to] = c; ScreenAttrs[off_to] = hl; # ifdef FEAT_MBYTE if (enc_utf8) { if (c >= 0x80) { ScreenLinesUC[off_to] = c; ScreenLinesC[0][off_to] = 0; } else ScreenLinesUC[off_to] = 0; } # endif screen_char(off_to, row, col + coloff); } } else #endif LineWraps[row] = FALSE; } } #if defined(FEAT_RIGHTLEFT) || defined(PROTO) /* * Mirror text "str" for right-left displaying. * Only works for single-byte characters (e.g., numbers). */ void rl_mirror(str) char_u *str; { char_u *p1, *p2; int t; for (p1 = str, p2 = str + STRLEN(str) - 1; p1 < p2; ++p1, --p2) { t = *p1; *p1 = *p2; *p2 = t; } } #endif #if defined(FEAT_WINDOWS) || defined(PROTO) /* * mark all status lines for redraw; used after first :cd */ void status_redraw_all() { win_T *wp; for (wp = firstwin; wp; wp = wp->w_next) if (wp->w_status_height) { wp->w_redr_status = TRUE; redraw_later(VALID); } } /* * mark all status lines of the current buffer for redraw */ void status_redraw_curbuf() { win_T *wp; for (wp = firstwin; wp; wp = wp->w_next) if (wp->w_status_height != 0 && wp->w_buffer == curbuf) { wp->w_redr_status = TRUE; redraw_later(VALID); } } /* * Redraw all status lines that need to be redrawn. */ void redraw_statuslines() { win_T *wp; for (wp = firstwin; wp; wp = wp->w_next) if (wp->w_redr_status) win_redr_status(wp); if (redraw_tabline) draw_tabline(); } #endif #if (defined(FEAT_WILDMENU) && defined(FEAT_VERTSPLIT)) || defined(PROTO) /* * Redraw all status lines at the bottom of frame "frp". */ void win_redraw_last_status(frp) frame_T *frp; { if (frp->fr_layout == FR_LEAF) frp->fr_win->w_redr_status = TRUE; else if (frp->fr_layout == FR_ROW) { for (frp = frp->fr_child; frp != NULL; frp = frp->fr_next) win_redraw_last_status(frp); } else /* frp->fr_layout == FR_COL */ { frp = frp->fr_child; while (frp->fr_next != NULL) frp = frp->fr_next; win_redraw_last_status(frp); } } #endif #ifdef FEAT_VERTSPLIT /* * Draw the verticap separator right of window "wp" starting with line "row". */ static void draw_vsep_win(wp, row) win_T *wp; int row; { int hl; int c; if (wp->w_vsep_width) { /* draw the vertical separator right of this window */ c = fillchar_vsep(&hl); screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + wp->w_height, W_ENDCOL(wp), W_ENDCOL(wp) + 1, c, ' ', hl); } } #endif #ifdef FEAT_WILDMENU static int status_match_len __ARGS((expand_T *xp, char_u *s)); static int skip_status_match_char __ARGS((expand_T *xp, char_u *s)); /* * Get the length of an item as it will be shown in the status line. */ static int status_match_len(xp, s) expand_T *xp; char_u *s; { int len = 0; #ifdef FEAT_MENU int emenu = (xp->xp_context == EXPAND_MENUS || xp->xp_context == EXPAND_MENUNAMES); /* Check for menu separators - replace with '|'. */ if (emenu && menu_is_separator(s)) return 1; #endif while (*s != NUL) { s += skip_status_match_char(xp, s); len += ptr2cells(s); mb_ptr_adv(s); } return len; } /* * Return the number of characters that should be skipped in a status match. * These are backslashes used for escaping. Do show backslashes in help tags. */ static int skip_status_match_char(xp, s) expand_T *xp; char_u *s; { if ((rem_backslash(s) && xp->xp_context != EXPAND_HELP) #ifdef FEAT_MENU || ((xp->xp_context == EXPAND_MENUS || xp->xp_context == EXPAND_MENUNAMES) && (s[0] == '\t' || (s[0] == '\\' && s[1] != NUL))) #endif ) { #ifndef BACKSLASH_IN_FILENAME if (xp->xp_shell && csh_like_shell() && s[1] == '\\' && s[2] == '!') return 2; #endif return 1; } return 0; } /* * Show wildchar matches in the status line. * Show at least the "match" item. * We start at item 'first_match' in the list and show all matches that fit. * * If inversion is possible we use it. Else '=' characters are used. */ void win_redr_status_matches(xp, num_matches, matches, match, showtail) expand_T *xp; int num_matches; char_u **matches; /* list of matches */ int match; int showtail; { #define L_MATCH(m) (showtail ? sm_gettail(matches[m]) : matches[m]) int row; char_u *buf; int len; int clen; /* length in screen cells */ int fillchar; int attr; int i; int highlight = TRUE; char_u *selstart = NULL; int selstart_col = 0; char_u *selend = NULL; static int first_match = 0; int add_left = FALSE; char_u *s; #ifdef FEAT_MENU int emenu; #endif #if defined(FEAT_MBYTE) || defined(FEAT_MENU) int l; #endif if (matches == NULL) /* interrupted completion? */ return; #ifdef FEAT_MBYTE if (has_mbyte) buf = alloc((unsigned)Columns * MB_MAXBYTES + 1); else #endif buf = alloc((unsigned)Columns + 1); if (buf == NULL) return; if (match == -1) /* don't show match but original text */ { match = 0; highlight = FALSE; } /* count 1 for the ending ">" */ clen = status_match_len(xp, L_MATCH(match)) + 3; if (match == 0) first_match = 0; else if (match < first_match) { /* jumping left, as far as we can go */ first_match = match; add_left = TRUE; } else { /* check if match fits on the screen */ for (i = first_match; i < match; ++i) clen += status_match_len(xp, L_MATCH(i)) + 2; if (first_match > 0) clen += 2; /* jumping right, put match at the left */ if ((long)clen > Columns) { first_match = match; /* if showing the last match, we can add some on the left */ clen = 2; for (i = match; i < num_matches; ++i) { clen += status_match_len(xp, L_MATCH(i)) + 2; if ((long)clen >= Columns) break; } if (i == num_matches) add_left = TRUE; } } if (add_left) while (first_match > 0) { clen += status_match_len(xp, L_MATCH(first_match - 1)) + 2; if ((long)clen >= Columns) break; --first_match; } fillchar = fillchar_status(&attr, TRUE); if (first_match == 0) { *buf = NUL; len = 0; } else { STRCPY(buf, "< "); len = 2; } clen = len; i = first_match; while ((long)(clen + status_match_len(xp, L_MATCH(i)) + 2) < Columns) { if (i == match) { selstart = buf + len; selstart_col = clen; } s = L_MATCH(i); /* Check for menu separators - replace with '|' */ #ifdef FEAT_MENU emenu = (xp->xp_context == EXPAND_MENUS || xp->xp_context == EXPAND_MENUNAMES); if (emenu && menu_is_separator(s)) { STRCPY(buf + len, transchar('|')); l = (int)STRLEN(buf + len); len += l; clen += l; } else #endif for ( ; *s != NUL; ++s) { s += skip_status_match_char(xp, s); clen += ptr2cells(s); #ifdef FEAT_MBYTE if (has_mbyte && (l = (*mb_ptr2len)(s)) > 1) { STRNCPY(buf + len, s, l); s += l - 1; len += l; } else #endif { STRCPY(buf + len, transchar_byte(*s)); len += (int)STRLEN(buf + len); } } if (i == match) selend = buf + len; *(buf + len++) = ' '; *(buf + len++) = ' '; clen += 2; if (++i == num_matches) break; } if (i != num_matches) { *(buf + len++) = '>'; ++clen; } buf[len] = NUL; row = cmdline_row - 1; if (row >= 0) { if (wild_menu_showing == 0) { if (msg_scrolled > 0) { /* Put the wildmenu just above the command line. If there is * no room, scroll the screen one line up. */ if (cmdline_row == Rows - 1) { screen_del_lines(0, 0, 1, (int)Rows, TRUE, NULL); ++msg_scrolled; } else { ++cmdline_row; ++row; } wild_menu_showing = WM_SCROLLED; } else { /* Create status line if needed by setting 'laststatus' to 2. * Set 'winminheight' to zero to avoid that the window is * resized. */ if (lastwin->w_status_height == 0) { save_p_ls = p_ls; save_p_wmh = p_wmh; p_ls = 2; p_wmh = 0; last_status(FALSE); } wild_menu_showing = WM_SHOWN; } } screen_puts(buf, row, 0, attr); if (selstart != NULL && highlight) { *selend = NUL; screen_puts(selstart, row, selstart_col, hl_attr(HLF_WM)); } screen_fill(row, row + 1, clen, (int)Columns, fillchar, fillchar, attr); } #ifdef FEAT_VERTSPLIT win_redraw_last_status(topframe); #else lastwin->w_redr_status = TRUE; #endif vim_free(buf); } #endif #if defined(FEAT_WINDOWS) || defined(PROTO) /* * Redraw the status line of window wp. * * If inversion is possible we use it. Else '=' characters are used. */ void win_redr_status(wp) win_T *wp; { int row; char_u *p; int len; int fillchar; int attr; int this_ru_col; static int busy = FALSE; /* It's possible to get here recursively when 'statusline' (indirectly) * invokes ":redrawstatus". Simply ignore the call then. */ if (busy) return; busy = TRUE; wp->w_redr_status = FALSE; if (wp->w_status_height == 0) { /* no status line, can only be last window */ redraw_cmdline = TRUE; } else if (!redrawing() #ifdef FEAT_INS_EXPAND /* don't update status line when popup menu is visible and may be * drawn over it */ || pum_visible() #endif ) { /* Don't redraw right now, do it later. */ wp->w_redr_status = TRUE; } #ifdef FEAT_STL_OPT else if (*p_stl != NUL || *wp->w_p_stl != NUL) { /* redraw custom status line */ redraw_custom_statusline(wp); } #endif else { fillchar = fillchar_status(&attr, wp == curwin); get_trans_bufname(wp->w_buffer); p = NameBuff; len = (int)STRLEN(p); if (wp->w_buffer->b_help #ifdef FEAT_QUICKFIX || wp->w_p_pvw #endif || bufIsChanged(wp->w_buffer) || wp->w_buffer->b_p_ro) *(p + len++) = ' '; if (wp->w_buffer->b_help) { STRCPY(p + len, _("[Help]")); len += (int)STRLEN(p + len); } #ifdef FEAT_QUICKFIX if (wp->w_p_pvw) { STRCPY(p + len, _("[Preview]")); len += (int)STRLEN(p + len); } #endif if (bufIsChanged(wp->w_buffer)) { STRCPY(p + len, "[+]"); len += 3; } if (wp->w_buffer->b_p_ro) { STRCPY(p + len, _("[RO]")); len += 4; } #ifndef FEAT_VERTSPLIT this_ru_col = ru_col; if (this_ru_col < (Columns + 1) / 2) this_ru_col = (Columns + 1) / 2; #else this_ru_col = ru_col - (Columns - W_WIDTH(wp)); if (this_ru_col < (W_WIDTH(wp) + 1) / 2) this_ru_col = (W_WIDTH(wp) + 1) / 2; if (this_ru_col <= 1) { p = (char_u *)"<"; /* No room for file name! */ len = 1; } else #endif #ifdef FEAT_MBYTE if (has_mbyte) { int clen = 0, i; /* Count total number of display cells. */ clen = mb_string2cells(p, -1); /* Find first character that will fit. * Going from start to end is much faster for DBCS. */ for (i = 0; p[i] != NUL && clen >= this_ru_col - 1; i += (*mb_ptr2len)(p + i)) clen -= (*mb_ptr2cells)(p + i); len = clen; if (i > 0) { p = p + i - 1; *p = '<'; ++len; } } else #endif if (len > this_ru_col - 1) { p += len - (this_ru_col - 1); *p = '<'; len = this_ru_col - 1; } row = W_WINROW(wp) + wp->w_height; screen_puts(p, row, W_WINCOL(wp), attr); screen_fill(row, row + 1, len + W_WINCOL(wp), this_ru_col + W_WINCOL(wp), fillchar, fillchar, attr); if (get_keymap_str(wp, NameBuff, MAXPATHL) && (int)(this_ru_col - len) > (int)(STRLEN(NameBuff) + 1)) screen_puts(NameBuff, row, (int)(this_ru_col - STRLEN(NameBuff) - 1 + W_WINCOL(wp)), attr); #ifdef FEAT_CMDL_INFO win_redr_ruler(wp, TRUE); #endif } #ifdef FEAT_VERTSPLIT /* * May need to draw the character below the vertical separator. */ if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing()) { if (stl_connected(wp)) fillchar = fillchar_status(&attr, wp == curwin); else fillchar = fillchar_vsep(&attr); screen_putchar(fillchar, W_WINROW(wp) + wp->w_height, W_ENDCOL(wp), attr); } #endif busy = FALSE; } #ifdef FEAT_STL_OPT /* * Redraw the status line according to 'statusline' and take care of any * errors encountered. */ static void redraw_custom_statusline(wp) win_T *wp; { static int entered = FALSE; int save_called_emsg = called_emsg; /* When called recursively return. This can happen when the statusline * contains an expression that triggers a redraw. */ if (entered) return; entered = TRUE; called_emsg = FALSE; win_redr_custom(wp, FALSE); if (called_emsg) { /* When there is an error disable the statusline, otherwise the * display is messed up with errors and a redraw triggers the problem * again and again. */ set_string_option_direct((char_u *)"statusline", -1, (char_u *)"", OPT_FREE | (*wp->w_p_stl != NUL ? OPT_LOCAL : OPT_GLOBAL), SID_ERROR); } called_emsg |= save_called_emsg; entered = FALSE; } #endif # ifdef FEAT_VERTSPLIT /* * Return TRUE if the status line of window "wp" is connected to the status * line of the window right of it. If not, then it's a vertical separator. * Only call if (wp->w_vsep_width != 0). */ int stl_connected(wp) win_T *wp; { frame_T *fr; fr = wp->w_frame; while (fr->fr_parent != NULL) { if (fr->fr_parent->fr_layout == FR_COL) { if (fr->fr_next != NULL) break; } else { if (fr->fr_next != NULL) return TRUE; } fr = fr->fr_parent; } return FALSE; } # endif #endif /* FEAT_WINDOWS */ #if defined(FEAT_WINDOWS) || defined(FEAT_STL_OPT) || defined(PROTO) /* * Get the value to show for the language mappings, active 'keymap'. */ int get_keymap_str(wp, buf, len) win_T *wp; char_u *buf; /* buffer for the result */ int len; /* length of buffer */ { char_u *p; if (wp->w_buffer->b_p_iminsert != B_IMODE_LMAP) return FALSE; { #ifdef FEAT_EVAL buf_T *old_curbuf = curbuf; win_T *old_curwin = curwin; char_u *s; curbuf = wp->w_buffer; curwin = wp; STRCPY(buf, "b:keymap_name"); /* must be writable */ ++emsg_skip; s = p = eval_to_string(buf, NULL, FALSE); --emsg_skip; curbuf = old_curbuf; curwin = old_curwin; if (p == NULL || *p == NUL) #endif { #ifdef FEAT_KEYMAP if (wp->w_buffer->b_kmap_state & KEYMAP_LOADED) p = wp->w_buffer->b_p_keymap; else #endif p = (char_u *)"lang"; } if ((int)(STRLEN(p) + 3) < len) sprintf((char *)buf, "<%s>", p); else buf[0] = NUL; #ifdef FEAT_EVAL vim_free(s); #endif } return buf[0] != NUL; } #endif #if defined(FEAT_STL_OPT) || defined(PROTO) /* * Redraw the status line or ruler of window "wp". * When "wp" is NULL redraw the tab pages line from 'tabline'. */ static void win_redr_custom(wp, draw_ruler) win_T *wp; int draw_ruler; /* TRUE or FALSE */ { static int entered = FALSE; int attr; int curattr; int row; int col = 0; int maxwidth; int width; int n; int len; int fillchar; char_u buf[MAXPATHL]; char_u *stl; char_u *p; struct stl_hlrec hltab[STL_MAX_ITEM]; struct stl_hlrec tabtab[STL_MAX_ITEM]; int use_sandbox = FALSE; win_T *ewp; int p_crb_save; /* There is a tiny chance that this gets called recursively: When * redrawing a status line triggers redrawing the ruler or tabline. * Avoid trouble by not allowing recursion. */ if (entered) return; entered = TRUE; /* setup environment for the task at hand */ if (wp == NULL) { /* Use 'tabline'. Always at the first line of the screen. */ stl = p_tal; row = 0; fillchar = ' '; attr = hl_attr(HLF_TPF); maxwidth = Columns; # ifdef FEAT_EVAL use_sandbox = was_set_insecurely((char_u *)"tabline", 0); # endif } else { row = W_WINROW(wp) + wp->w_height; fillchar = fillchar_status(&attr, wp == curwin); maxwidth = W_WIDTH(wp); if (draw_ruler) { stl = p_ruf; /* advance past any leading group spec - implicit in ru_col */ if (*stl == '%') { if (*++stl == '-') stl++; if (atoi((char *)stl)) while (VIM_ISDIGIT(*stl)) stl++; if (*stl++ != '(') stl = p_ruf; } #ifdef FEAT_VERTSPLIT col = ru_col - (Columns - W_WIDTH(wp)); if (col < (W_WIDTH(wp) + 1) / 2) col = (W_WIDTH(wp) + 1) / 2; #else col = ru_col; if (col > (Columns + 1) / 2) col = (Columns + 1) / 2; #endif maxwidth = W_WIDTH(wp) - col; #ifdef FEAT_WINDOWS if (!wp->w_status_height) #endif { row = Rows - 1; --maxwidth; /* writing in last column may cause scrolling */ fillchar = ' '; attr = 0; } # ifdef FEAT_EVAL use_sandbox = was_set_insecurely((char_u *)"rulerformat", 0); # endif } else { if (*wp->w_p_stl != NUL) stl = wp->w_p_stl; else stl = p_stl; # ifdef FEAT_EVAL use_sandbox = was_set_insecurely((char_u *)"statusline", *wp->w_p_stl == NUL ? 0 : OPT_LOCAL); # endif } #ifdef FEAT_VERTSPLIT col += W_WINCOL(wp); #endif } if (maxwidth <= 0) goto theend; /* Temporarily reset 'cursorbind', we don't want a side effect from moving * the cursor away and back. */ ewp = wp == NULL ? curwin : wp; p_crb_save = ewp->w_p_crb; ewp->w_p_crb = FALSE; /* Make a copy, because the statusline may include a function call that * might change the option value and free the memory. */ stl = vim_strsave(stl); width = build_stl_str_hl(ewp, buf, sizeof(buf), stl, use_sandbox, fillchar, maxwidth, hltab, tabtab); vim_free(stl); ewp->w_p_crb = p_crb_save; /* Make all characters printable. */ p = transstr(buf); if (p != NULL) { vim_strncpy(buf, p, sizeof(buf) - 1); vim_free(p); } /* fill up with "fillchar" */ len = (int)STRLEN(buf); while (width < maxwidth && len < (int)sizeof(buf) - 1) { #ifdef FEAT_MBYTE len += (*mb_char2bytes)(fillchar, buf + len); #else buf[len++] = fillchar; #endif ++width; } buf[len] = NUL; /* * Draw each snippet with the specified highlighting. */ curattr = attr; p = buf; for (n = 0; hltab[n].start != NULL; n++) { len = (int)(hltab[n].start - p); screen_puts_len(p, len, row, col, curattr); col += vim_strnsize(p, len); p = hltab[n].start; if (hltab[n].userhl == 0) curattr = attr; else if (hltab[n].userhl < 0) curattr = syn_id2attr(-hltab[n].userhl); #ifdef FEAT_WINDOWS else if (wp != NULL && wp != curwin && wp->w_status_height != 0) curattr = highlight_stlnc[hltab[n].userhl - 1]; #endif else curattr = highlight_user[hltab[n].userhl - 1]; } screen_puts(p, row, col, curattr); if (wp == NULL) { /* Fill the TabPageIdxs[] array for clicking in the tab pagesline. */ col = 0; len = 0; p = buf; fillchar = 0; for (n = 0; tabtab[n].start != NULL; n++) { len += vim_strnsize(p, (int)(tabtab[n].start - p)); while (col < len) TabPageIdxs[col++] = fillchar; p = tabtab[n].start; fillchar = tabtab[n].userhl; } while (col < Columns) TabPageIdxs[col++] = fillchar; } theend: entered = FALSE; } #endif /* FEAT_STL_OPT */ /* * Output a single character directly to the screen and update ScreenLines. */ void screen_putchar(c, row, col, attr) int c; int row, col; int attr; { char_u buf[MB_MAXBYTES + 1]; #ifdef FEAT_MBYTE if (has_mbyte) buf[(*mb_char2bytes)(c, buf)] = NUL; else #endif { buf[0] = c; buf[1] = NUL; } screen_puts(buf, row, col, attr); } /* * Get a single character directly from ScreenLines into "bytes[]". * Also return its attribute in *attrp; */ void screen_getbytes(row, col, bytes, attrp) int row, col; char_u *bytes; int *attrp; { unsigned off; /* safety check */ if (ScreenLines != NULL && row < screen_Rows && col < screen_Columns) { off = LineOffset[row] + col; *attrp = ScreenAttrs[off]; bytes[0] = ScreenLines[off]; bytes[1] = NUL; #ifdef FEAT_MBYTE if (enc_utf8 && ScreenLinesUC[off] != 0) bytes[utfc_char2bytes(off, bytes)] = NUL; else if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e) { bytes[0] = ScreenLines[off]; bytes[1] = ScreenLines2[off]; bytes[2] = NUL; } else if (enc_dbcs && MB_BYTE2LEN(bytes[0]) > 1) { bytes[1] = ScreenLines[off + 1]; bytes[2] = NUL; } #endif } } #ifdef FEAT_MBYTE static int screen_comp_differs __ARGS((int, int*)); /* * Return TRUE if composing characters for screen posn "off" differs from * composing characters in "u8cc". * Only to be used when ScreenLinesUC[off] != 0. */ static int screen_comp_differs(off, u8cc) int off; int *u8cc; { int i; for (i = 0; i < Screen_mco; ++i) { if (ScreenLinesC[i][off] != (u8char_T)u8cc[i]) return TRUE; if (u8cc[i] == 0) break; } return FALSE; } #endif /* * Put string '*text' on the screen at position 'row' and 'col', with * attributes 'attr', and update ScreenLines[] and ScreenAttrs[]. * Note: only outputs within one row, message is truncated at screen boundary! * Note: if ScreenLines[], row and/or col is invalid, nothing is done. */ void screen_puts(text, row, col, attr) char_u *text; int row; int col; int attr; { screen_puts_len(text, -1, row, col, attr); } /* * Like screen_puts(), but output "text[len]". When "len" is -1 output up to * a NUL. */ void screen_puts_len(text, textlen, row, col, attr) char_u *text; int textlen; int row; int col; int attr; { unsigned off; char_u *ptr = text; int len = textlen; int c; #ifdef FEAT_MBYTE unsigned max_off; int mbyte_blen = 1; int mbyte_cells = 1; int u8c = 0; int u8cc[MAX_MCO]; int clear_next_cell = FALSE; # ifdef FEAT_ARABIC int prev_c = 0; /* previous Arabic character */ int pc, nc, nc1; int pcc[MAX_MCO]; # endif #endif #if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX) int force_redraw_this; int force_redraw_next = FALSE; #endif int need_redraw; if (ScreenLines == NULL || row >= screen_Rows) /* safety check */ return; off = LineOffset[row] + col; #ifdef FEAT_MBYTE /* When drawing over the right halve of a double-wide char clear out the * left halve. Only needed in a terminal. */ if (has_mbyte && col > 0 && col < screen_Columns # ifdef FEAT_GUI && !gui.in_use # endif && mb_fix_col(col, row) != col) { ScreenLines[off - 1] = ' '; ScreenAttrs[off - 1] = 0; if (enc_utf8) { ScreenLinesUC[off - 1] = 0; ScreenLinesC[0][off - 1] = 0; } /* redraw the previous cell, make it empty */ screen_char(off - 1, row, col - 1); /* force the cell at "col" to be redrawn */ force_redraw_next = TRUE; } #endif #ifdef FEAT_MBYTE max_off = LineOffset[row] + screen_Columns; #endif while (col < screen_Columns && (len < 0 || (int)(ptr - text) < len) && *ptr != NUL) { c = *ptr; #ifdef FEAT_MBYTE /* check if this is the first byte of a multibyte */ if (has_mbyte) { if (enc_utf8 && len > 0) mbyte_blen = utfc_ptr2len_len(ptr, (int)((text + len) - ptr)); else mbyte_blen = (*mb_ptr2len)(ptr); if (enc_dbcs == DBCS_JPNU && c == 0x8e) mbyte_cells = 1; else if (enc_dbcs != 0) mbyte_cells = mbyte_blen; else /* enc_utf8 */ { if (len >= 0) u8c = utfc_ptr2char_len(ptr, u8cc, (int)((text + len) - ptr)); else u8c = utfc_ptr2char(ptr, u8cc); mbyte_cells = utf_char2cells(u8c); # ifdef UNICODE16 /* Non-BMP character: display as ? or fullwidth ?. */ if (u8c >= 0x10000) { u8c = (mbyte_cells == 2) ? 0xff1f : (int)'?'; if (attr == 0) attr = hl_attr(HLF_8); } # endif # ifdef FEAT_ARABIC if (p_arshape && !p_tbidi && ARABIC_CHAR(u8c)) { /* Do Arabic shaping. */ if (len >= 0 && (int)(ptr - text) + mbyte_blen >= len) { /* Past end of string to be displayed. */ nc = NUL; nc1 = NUL; } else { nc = utfc_ptr2char_len(ptr + mbyte_blen, pcc, (int)((text + len) - ptr - mbyte_blen)); nc1 = pcc[0]; } pc = prev_c; prev_c = u8c; u8c = arabic_shape(u8c, &c, &u8cc[0], nc, nc1, pc); } else prev_c = u8c; # endif if (col + mbyte_cells > screen_Columns) { /* Only 1 cell left, but character requires 2 cells: * display a '>' in the last column to avoid wrapping. */ c = '>'; mbyte_cells = 1; } } } #endif #if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX) force_redraw_this = force_redraw_next; force_redraw_next = FALSE; #endif need_redraw = ScreenLines[off] != c #ifdef FEAT_MBYTE || (mbyte_cells == 2 && ScreenLines[off + 1] != (enc_dbcs ? ptr[1] : 0)) || (enc_dbcs == DBCS_JPNU && c == 0x8e && ScreenLines2[off] != ptr[1]) || (enc_utf8 && (ScreenLinesUC[off] != (u8char_T)(c < 0x80 && u8cc[0] == 0 ? 0 : u8c) || (ScreenLinesUC[off] != 0 && screen_comp_differs(off, u8cc)))) #endif || ScreenAttrs[off] != attr || exmode_active; if (need_redraw #if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX) || force_redraw_this #endif ) { #if defined(FEAT_GUI) || defined(UNIX) /* The bold trick makes a single row of pixels appear in the next * character. When a bold character is removed, the next * character should be redrawn too. This happens for our own GUI * and for some xterms. */ if (need_redraw && ScreenLines[off] != ' ' && ( # ifdef FEAT_GUI gui.in_use # endif # if defined(FEAT_GUI) && defined(UNIX) || # endif # ifdef UNIX term_is_xterm # endif )) { int n = ScreenAttrs[off]; if (n > HL_ALL) n = syn_attr2attr(n); # ifndef FEAT_GUI_MACVIM /* see comment on subpixel antialiasing */ if (n & HL_BOLD) # endif force_redraw_next = TRUE; } #endif #ifdef FEAT_MBYTE /* When at the end of the text and overwriting a two-cell * character with a one-cell character, need to clear the next * cell. Also when overwriting the left halve of a two-cell char * with the right halve of a two-cell char. Do this only once * (mb_off2cells() may return 2 on the right halve). */ if (clear_next_cell) clear_next_cell = FALSE; else if (has_mbyte && (len < 0 ? ptr[mbyte_blen] == NUL : ptr + mbyte_blen >= text + len) && ((mbyte_cells == 1 && (*mb_off2cells)(off, max_off) > 1) || (mbyte_cells == 2 && (*mb_off2cells)(off, max_off) == 1 && (*mb_off2cells)(off + 1, max_off) > 1))) clear_next_cell = TRUE; /* Make sure we never leave a second byte of a double-byte behind, * it confuses mb_off2cells(). */ if (enc_dbcs && ((mbyte_cells == 1 && (*mb_off2cells)(off, max_off) > 1) || (mbyte_cells == 2 && (*mb_off2cells)(off, max_off) == 1 && (*mb_off2cells)(off + 1, max_off) > 1))) ScreenLines[off + mbyte_blen] = 0; #endif ScreenLines[off] = c; ScreenAttrs[off] = attr; #ifdef FEAT_MBYTE if (enc_utf8) { if (c < 0x80 && u8cc[0] == 0) ScreenLinesUC[off] = 0; else { int i; ScreenLinesUC[off] = u8c; for (i = 0; i < Screen_mco; ++i) { ScreenLinesC[i][off] = u8cc[i]; if (u8cc[i] == 0) break; } } if (mbyte_cells == 2) { ScreenLines[off + 1] = 0; ScreenAttrs[off + 1] = attr; } screen_char(off, row, col); } else if (mbyte_cells == 2) { ScreenLines[off + 1] = ptr[1]; ScreenAttrs[off + 1] = attr; screen_char_2(off, row, col); } else if (enc_dbcs == DBCS_JPNU && c == 0x8e) { ScreenLines2[off] = ptr[1]; screen_char(off, row, col); } else #endif screen_char(off, row, col); } #ifdef FEAT_MBYTE if (has_mbyte) { off += mbyte_cells; col += mbyte_cells; ptr += mbyte_blen; if (clear_next_cell) { /* This only happens at the end, display one space next. */ ptr = (char_u *)" "; len = -1; } } else #endif { ++off; ++col; ++ptr; } } #if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX) /* If we detected the next character needs to be redrawn, but the text * doesn't extend up to there, update the character here. */ if (force_redraw_next && col < screen_Columns) { # ifdef FEAT_MBYTE if (enc_dbcs != 0 && dbcs_off2cells(off, max_off) > 1) screen_char_2(off, row, col); else # endif screen_char(off, row, col); } #endif } #ifdef FEAT_SEARCH_EXTRA /* * Prepare for 'hlsearch' highlighting. */ static void start_search_hl() { if (p_hls && !no_hlsearch) { last_pat_prog(&search_hl.rm); search_hl.attr = hl_attr(HLF_L); # ifdef FEAT_RELTIME /* Set the time limit to 'redrawtime'. */ profile_setlimit(p_rdt, &search_hl.tm); # endif } } /* * Clean up for 'hlsearch' highlighting. */ static void end_search_hl() { if (search_hl.rm.regprog != NULL) { vim_regfree(search_hl.rm.regprog); search_hl.rm.regprog = NULL; } } /* * Init for calling prepare_search_hl(). */ static void init_search_hl(wp) win_T *wp; { matchitem_T *cur; /* Setup for match and 'hlsearch' highlighting. Disable any previous * match */ cur = wp->w_match_head; while (cur != NULL) { cur->hl.rm = cur->match; if (cur->hlg_id == 0) cur->hl.attr = 0; else cur->hl.attr = syn_id2attr(cur->hlg_id); cur->hl.buf = wp->w_buffer; cur->hl.lnum = 0; cur->hl.first_lnum = 0; # ifdef FEAT_RELTIME /* Set the time limit to 'redrawtime'. */ profile_setlimit(p_rdt, &(cur->hl.tm)); # endif cur = cur->next; } search_hl.buf = wp->w_buffer; search_hl.lnum = 0; search_hl.first_lnum = 0; /* time limit is set at the toplevel, for all windows */ } /* * Advance to the match in window "wp" line "lnum" or past it. */ static void prepare_search_hl(wp, lnum) win_T *wp; linenr_T lnum; { matchitem_T *cur; /* points to the match list */ match_T *shl; /* points to search_hl or a match */ int shl_flag; /* flag to indicate whether search_hl has been processed or not */ int pos_inprogress; /* marks that position match search is in progress */ int n; /* * When using a multi-line pattern, start searching at the top * of the window or just after a closed fold. * Do this both for search_hl and the match list. */ cur = wp->w_match_head; shl_flag = FALSE; while (cur != NULL || shl_flag == FALSE) { if (shl_flag == FALSE) { shl = &search_hl; shl_flag = TRUE; } else shl = &cur->hl; if (shl->rm.regprog != NULL && shl->lnum == 0 && re_multiline(shl->rm.regprog)) { if (shl->first_lnum == 0) { # ifdef FEAT_FOLDING for (shl->first_lnum = lnum; shl->first_lnum > wp->w_topline; --shl->first_lnum) if (hasFoldingWin(wp, shl->first_lnum - 1, NULL, NULL, TRUE, NULL)) break; # else shl->first_lnum = wp->w_topline; # endif } if (cur != NULL) cur->pos.cur = 0; pos_inprogress = TRUE; n = 0; while (shl->first_lnum < lnum && (shl->rm.regprog != NULL || (cur != NULL && pos_inprogress))) { next_search_hl(wp, shl, shl->first_lnum, (colnr_T)n, cur); pos_inprogress = cur == NULL || cur->pos.cur == 0 ? FALSE : TRUE; if (shl->lnum != 0) { shl->first_lnum = shl->lnum + shl->rm.endpos[0].lnum - shl->rm.startpos[0].lnum; n = shl->rm.endpos[0].col; } else { ++shl->first_lnum; n = 0; } } } if (shl != &search_hl && cur != NULL) cur = cur->next; } } /* * Search for a next 'hlsearch' or match. * Uses shl->buf. * Sets shl->lnum and shl->rm contents. * Note: Assumes a previous match is always before "lnum", unless * shl->lnum is zero. * Careful: Any pointers for buffer lines will become invalid. */ static void next_search_hl(win, shl, lnum, mincol, cur) win_T *win; match_T *shl; /* points to search_hl or a match */ linenr_T lnum; colnr_T mincol; /* minimal column for a match */ matchitem_T *cur; /* to retrieve match positions if any */ { linenr_T l; colnr_T matchcol; long nmatched; if (shl->lnum != 0) { /* Check for three situations: * 1. If the "lnum" is below a previous match, start a new search. * 2. If the previous match includes "mincol", use it. * 3. Continue after the previous match. */ l = shl->lnum + shl->rm.endpos[0].lnum - shl->rm.startpos[0].lnum; if (lnum > l) shl->lnum = 0; else if (lnum < l || shl->rm.endpos[0].col > mincol) return; } /* * Repeat searching for a match until one is found that includes "mincol" * or none is found in this line. */ called_emsg = FALSE; for (;;) { #ifdef FEAT_RELTIME /* Stop searching after passing the time limit. */ if (profile_passed_limit(&(shl->tm))) { shl->lnum = 0; /* no match found in time */ break; } #endif /* Three situations: * 1. No useful previous match: search from start of line. * 2. Not Vi compatible or empty match: continue at next character. * Break the loop if this is beyond the end of the line. * 3. Vi compatible searching: continue at end of previous match. */ if (shl->lnum == 0) matchcol = 0; else if (vim_strchr(p_cpo, CPO_SEARCH) == NULL || (shl->rm.endpos[0].lnum == 0 && shl->rm.endpos[0].col <= shl->rm.startpos[0].col)) { char_u *ml; matchcol = shl->rm.startpos[0].col; ml = ml_get_buf(shl->buf, lnum, FALSE) + matchcol; if (*ml == NUL) { ++matchcol; shl->lnum = 0; break; } #ifdef FEAT_MBYTE if (has_mbyte) matchcol += mb_ptr2len(ml); else #endif ++matchcol; } else matchcol = shl->rm.endpos[0].col; shl->lnum = lnum; if (shl->rm.regprog != NULL) { /* Remember whether shl->rm is using a copy of the regprog in * cur->match. */ int regprog_is_copy = (shl != &search_hl && cur != NULL && shl == &cur->hl && cur->match.regprog == cur->hl.rm.regprog); nmatched = vim_regexec_multi(&shl->rm, win, shl->buf, lnum, matchcol, #ifdef FEAT_RELTIME &(shl->tm) #else NULL #endif ); /* Copy the regprog, in case it got freed and recompiled. */ if (regprog_is_copy) cur->match.regprog = cur->hl.rm.regprog; if (called_emsg || got_int) { /* Error while handling regexp: stop using this regexp. */ if (shl == &search_hl) { /* don't free regprog in the match list, it's a copy */ vim_regfree(shl->rm.regprog); SET_NO_HLSEARCH(TRUE); } shl->rm.regprog = NULL; shl->lnum = 0; got_int = FALSE; /* avoid the "Type :quit to exit Vim" message */ break; } } else if (cur != NULL) nmatched = next_search_hl_pos(shl, lnum, &(cur->pos), matchcol); else nmatched = 0; if (nmatched == 0) { shl->lnum = 0; /* no match found */ break; } if (shl->rm.startpos[0].lnum > 0 || shl->rm.startpos[0].col >= mincol || nmatched > 1 || shl->rm.endpos[0].col > mincol) { shl->lnum += shl->rm.startpos[0].lnum; break; /* useful match found */ } } } static int next_search_hl_pos(shl, lnum, posmatch, mincol) match_T *shl; /* points to a match */ linenr_T lnum; posmatch_T *posmatch; /* match positions */ colnr_T mincol; /* minimal column for a match */ { int i; int bot = -1; shl->lnum = 0; for (i = posmatch->cur; i < MAXPOSMATCH; i++) { if (posmatch->pos[i].lnum == 0) break; if (posmatch->pos[i].col < mincol) continue; if (posmatch->pos[i].lnum == lnum) { if (shl->lnum == lnum) { /* partially sort positions by column numbers * on the same line */ if (posmatch->pos[i].col < posmatch->pos[bot].col) { llpos_T tmp = posmatch->pos[i]; posmatch->pos[i] = posmatch->pos[bot]; posmatch->pos[bot] = tmp; } } else { bot = i; shl->lnum = lnum; } } } posmatch->cur = 0; if (shl->lnum == lnum && bot >= 0) { colnr_T start = posmatch->pos[bot].col == 0 ? 0 : posmatch->pos[bot].col - 1; colnr_T end = posmatch->pos[bot].col == 0 ? MAXCOL : start + posmatch->pos[bot].len; shl->rm.startpos[0].lnum = 0; shl->rm.startpos[0].col = start; shl->rm.endpos[0].lnum = 0; shl->rm.endpos[0].col = end; posmatch->cur = bot + 1; return TRUE; } return FALSE; } #endif static void screen_start_highlight(attr) int attr; { attrentry_T *aep = NULL; screen_attr = attr; if (full_screen #ifdef WIN3264 && termcap_active #endif ) { #ifdef FEAT_GUI if (gui.in_use) { char buf[20]; /* The GUI handles this internally. */ sprintf(buf, IF_EB("\033|%dh", ESC_STR "|%dh"), attr); OUT_STR(buf); } else #endif { if (attr > HL_ALL) /* special HL attr. */ { if (t_colors > 1) aep = syn_cterm_attr2entry(attr); else aep = syn_term_attr2entry(attr); if (aep == NULL) /* did ":syntax clear" */ attr = 0; else attr = aep->ae_attr; } if ((attr & HL_BOLD) && T_MD != NULL) /* bold */ out_str(T_MD); else if (aep != NULL && t_colors > 1 && aep->ae_u.cterm.fg_color && cterm_normal_fg_bold) /* If the Normal FG color has BOLD attribute and the new HL * has a FG color defined, clear BOLD. */ out_str(T_ME); if ((attr & HL_STANDOUT) && T_SO != NULL) /* standout */ out_str(T_SO); if ((attr & (HL_UNDERLINE | HL_UNDERCURL)) && T_US != NULL) /* underline or undercurl */ out_str(T_US); if ((attr & HL_ITALIC) && T_CZH != NULL) /* italic */ out_str(T_CZH); if ((attr & HL_INVERSE) && T_MR != NULL) /* inverse (reverse) */ out_str(T_MR); /* * Output the color or start string after bold etc., in case the * bold etc. override the color setting. */ if (aep != NULL) { if (t_colors > 1) { if (aep->ae_u.cterm.fg_color) term_fg_color(aep->ae_u.cterm.fg_color - 1); if (aep->ae_u.cterm.bg_color) term_bg_color(aep->ae_u.cterm.bg_color - 1); } else { if (aep->ae_u.term.start != NULL) out_str(aep->ae_u.term.start); } } } } } void screen_stop_highlight() { int do_ME = FALSE; /* output T_ME code */ if (screen_attr != 0 #ifdef WIN3264 && termcap_active #endif ) { #ifdef FEAT_GUI if (gui.in_use) { char buf[20]; /* use internal GUI code */ sprintf(buf, IF_EB("\033|%dH", ESC_STR "|%dH"), screen_attr); OUT_STR(buf); } else #endif { if (screen_attr > HL_ALL) /* special HL attr. */ { attrentry_T *aep; if (t_colors > 1) { /* * Assume that t_me restores the original colors! */ aep = syn_cterm_attr2entry(screen_attr); if (aep != NULL && (aep->ae_u.cterm.fg_color || aep->ae_u.cterm.bg_color)) do_ME = TRUE; } else { aep = syn_term_attr2entry(screen_attr); if (aep != NULL && aep->ae_u.term.stop != NULL) { if (STRCMP(aep->ae_u.term.stop, T_ME) == 0) do_ME = TRUE; else out_str(aep->ae_u.term.stop); } } if (aep == NULL) /* did ":syntax clear" */ screen_attr = 0; else screen_attr = aep->ae_attr; } /* * Often all ending-codes are equal to T_ME. Avoid outputting the * same sequence several times. */ if (screen_attr & HL_STANDOUT) { if (STRCMP(T_SE, T_ME) == 0) do_ME = TRUE; else out_str(T_SE); } if (screen_attr & (HL_UNDERLINE | HL_UNDERCURL)) { if (STRCMP(T_UE, T_ME) == 0) do_ME = TRUE; else out_str(T_UE); } if (screen_attr & HL_ITALIC) { if (STRCMP(T_CZR, T_ME) == 0) do_ME = TRUE; else out_str(T_CZR); } if (do_ME || (screen_attr & (HL_BOLD | HL_INVERSE))) out_str(T_ME); if (t_colors > 1) { /* set Normal cterm colors */ if (cterm_normal_fg_color != 0) term_fg_color(cterm_normal_fg_color - 1); if (cterm_normal_bg_color != 0) term_bg_color(cterm_normal_bg_color - 1); if (cterm_normal_fg_bold) out_str(T_MD); } } } screen_attr = 0; } /* * Reset the colors for a cterm. Used when leaving Vim. * The machine specific code may override this again. */ void reset_cterm_colors() { if (t_colors > 1) { /* set Normal cterm colors */ if (cterm_normal_fg_color > 0 || cterm_normal_bg_color > 0) { out_str(T_OP); screen_attr = -1; } if (cterm_normal_fg_bold) { out_str(T_ME); screen_attr = -1; } } } /* * Put character ScreenLines["off"] on the screen at position "row" and "col", * using the attributes from ScreenAttrs["off"]. */ static void screen_char(off, row, col) unsigned off; int row; int col; { int attr; /* Check for illegal values, just in case (could happen just after * resizing). */ if (row >= screen_Rows || col >= screen_Columns) return; /* Outputting a character in the last cell on the screen may scroll the * screen up. Only do it when the "xn" termcap property is set, otherwise * mark the character invalid (update it when scrolled up). */ if (*T_XN == NUL && row == screen_Rows - 1 && col == screen_Columns - 1 #ifdef FEAT_RIGHTLEFT /* account for first command-line character in rightleft mode */ && !cmdmsg_rl #endif ) { ScreenAttrs[off] = (sattr_T)-1; return; } /* * Stop highlighting first, so it's easier to move the cursor. */ #if defined(FEAT_CLIPBOARD) || defined(FEAT_VERTSPLIT) if (screen_char_attr != 0) attr = screen_char_attr; else #endif attr = ScreenAttrs[off]; if (screen_attr != attr) screen_stop_highlight(); windgoto(row, col); if (screen_attr != attr) screen_start_highlight(attr); #ifdef FEAT_MBYTE if (enc_utf8 && ScreenLinesUC[off] != 0) { char_u buf[MB_MAXBYTES + 1]; /* Convert UTF-8 character to bytes and write it. */ buf[utfc_char2bytes(off, buf)] = NUL; out_str(buf); if (utf_char2cells(ScreenLinesUC[off]) > 1) ++screen_cur_col; } else #endif { #ifdef FEAT_MBYTE out_flush_check(); #endif out_char(ScreenLines[off]); #ifdef FEAT_MBYTE /* double-byte character in single-width cell */ if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e) out_char(ScreenLines2[off]); #endif } screen_cur_col++; } #ifdef FEAT_MBYTE /* * Used for enc_dbcs only: Put one double-wide character at ScreenLines["off"] * on the screen at position 'row' and 'col'. * The attributes of the first byte is used for all. This is required to * output the two bytes of a double-byte character with nothing in between. */ static void screen_char_2(off, row, col) unsigned off; int row; int col; { /* Check for illegal values (could be wrong when screen was resized). */ if (off + 1 >= (unsigned)(screen_Rows * screen_Columns)) return; /* Outputting the last character on the screen may scrollup the screen. * Don't to it! Mark the character invalid (update it when scrolled up) */ if (row == screen_Rows - 1 && col >= screen_Columns - 2) { ScreenAttrs[off] = (sattr_T)-1; return; } /* Output the first byte normally (positions the cursor), then write the * second byte directly. */ screen_char(off, row, col); out_char(ScreenLines[off + 1]); ++screen_cur_col; } #endif #if defined(FEAT_CLIPBOARD) || defined(FEAT_VERTSPLIT) || defined(PROTO) /* * Draw a rectangle of the screen, inverted when "invert" is TRUE. * This uses the contents of ScreenLines[] and doesn't change it. */ void screen_draw_rectangle(row, col, height, width, invert) int row; int col; int height; int width; int invert; { int r, c; int off; #ifdef FEAT_MBYTE int max_off; #endif /* Can't use ScreenLines unless initialized */ if (ScreenLines == NULL) return; if (invert) screen_char_attr = HL_INVERSE; for (r = row; r < row + height; ++r) { off = LineOffset[r]; #ifdef FEAT_MBYTE max_off = off + screen_Columns; #endif for (c = col; c < col + width; ++c) { #ifdef FEAT_MBYTE if (enc_dbcs != 0 && dbcs_off2cells(off + c, max_off) > 1) { screen_char_2(off + c, r, c); ++c; } else #endif { screen_char(off + c, r, c); #ifdef FEAT_MBYTE if (utf_off2cells(off + c, max_off) > 1) ++c; #endif } } } screen_char_attr = 0; } #endif #ifdef FEAT_VERTSPLIT /* * Redraw the characters for a vertically split window. */ static void redraw_block(row, end, wp) int row; int end; win_T *wp; { int col; int width; # ifdef FEAT_CLIPBOARD clip_may_clear_selection(row, end - 1); # endif if (wp == NULL) { col = 0; width = Columns; } else { col = wp->w_wincol; width = wp->w_width; } screen_draw_rectangle(row, col, end - row, width, FALSE); } #endif /* * Fill the screen from 'start_row' to 'end_row', from 'start_col' to 'end_col' * with character 'c1' in first column followed by 'c2' in the other columns. * Use attributes 'attr'. */ void screen_fill(start_row, end_row, start_col, end_col, c1, c2, attr) int start_row, end_row; int start_col, end_col; int c1, c2; int attr; { int row; int col; int off; int end_off; int did_delete; int c; int norm_term; #if defined(FEAT_GUI) || defined(UNIX) int force_next = FALSE; #endif if (end_row > screen_Rows) /* safety check */ end_row = screen_Rows; if (end_col > screen_Columns) /* safety check */ end_col = screen_Columns; if (ScreenLines == NULL || start_row >= end_row || start_col >= end_col) /* nothing to do */ return; /* it's a "normal" terminal when not in a GUI or cterm */ norm_term = ( #ifdef FEAT_GUI !gui.in_use && #endif t_colors <= 1); for (row = start_row; row < end_row; ++row) { #ifdef FEAT_MBYTE if (has_mbyte # ifdef FEAT_GUI && !gui.in_use # endif ) { /* When drawing over the right halve of a double-wide char clear * out the left halve. When drawing over the left halve of a * double wide-char clear out the right halve. Only needed in a * terminal. */ if (start_col > 0 && mb_fix_col(start_col, row) != start_col) screen_puts_len((char_u *)" ", 1, row, start_col - 1, 0); if (end_col < screen_Columns && mb_fix_col(end_col, row) != end_col) screen_puts_len((char_u *)" ", 1, row, end_col, 0); } #endif /* * Try to use delete-line termcap code, when no attributes or in a * "normal" terminal, where a bold/italic space is just a * space. */ did_delete = FALSE; if (c2 == ' ' && end_col == Columns && can_clear(T_CE) && (attr == 0 || (norm_term && attr <= HL_ALL && ((attr & ~(HL_BOLD | HL_ITALIC)) == 0)))) { /* * check if we really need to clear something */ col = start_col; if (c1 != ' ') /* don't clear first char */ ++col; off = LineOffset[row] + col; end_off = LineOffset[row] + end_col; /* skip blanks (used often, keep it fast!) */ #ifdef FEAT_MBYTE if (enc_utf8) while (off < end_off && ScreenLines[off] == ' ' && ScreenAttrs[off] == 0 && ScreenLinesUC[off] == 0) ++off; else #endif while (off < end_off && ScreenLines[off] == ' ' && ScreenAttrs[off] == 0) ++off; if (off < end_off) /* something to be cleared */ { col = off - LineOffset[row]; screen_stop_highlight(); term_windgoto(row, col);/* clear rest of this screen line */ out_str(T_CE); screen_start(); /* don't know where cursor is now */ col = end_col - col; while (col--) /* clear chars in ScreenLines */ { ScreenLines[off] = ' '; #ifdef FEAT_MBYTE if (enc_utf8) ScreenLinesUC[off] = 0; #endif ScreenAttrs[off] = 0; ++off; } } did_delete = TRUE; /* the chars are cleared now */ } off = LineOffset[row] + start_col; c = c1; for (col = start_col; col < end_col; ++col) { if (ScreenLines[off] != c #ifdef FEAT_MBYTE || (enc_utf8 && (int)ScreenLinesUC[off] != (c >= 0x80 ? c : 0)) #endif || ScreenAttrs[off] != attr #if defined(FEAT_GUI) || defined(UNIX) || force_next #endif #ifdef FEAT_GUI_MACVIM /* force a clear if the next char will be cleared (see * comment on subpixel antialiasing) */ || (gui.in_use && col+1 < end_col && ScreenLines[off+1] != c) #endif ) { #if defined(FEAT_GUI) || defined(UNIX) /* The bold trick may make a single row of pixels appear in * the next character. When a bold character is removed, the * next character should be redrawn too. This happens for our * own GUI and for some xterms. */ if ( # ifdef FEAT_GUI gui.in_use # endif # if defined(FEAT_GUI) && defined(UNIX) || # endif # ifdef UNIX term_is_xterm # endif ) { # ifndef FEAT_GUI_MACVIM if (ScreenLines[off] != ' ' && (ScreenAttrs[off] > HL_ALL || ScreenAttrs[off] & HL_BOLD)) force_next = TRUE; else force_next = FALSE; # else /* Mac OS X does subpixel antialiasing which often causes a * glyph to spill over into neighboring cells. For this * reason we always clear the neighboring glyphs whenever a * glyph is cleared, just like other GUIs cope with the * bold trick. */ force_next = (ScreenLines[off] != ' '); # endif } #endif ScreenLines[off] = c; #ifdef FEAT_MBYTE if (enc_utf8) { if (c >= 0x80) { ScreenLinesUC[off] = c; ScreenLinesC[0][off] = 0; } else ScreenLinesUC[off] = 0; } #endif ScreenAttrs[off] = attr; if (!did_delete || c != ' ') screen_char(off, row, col); } ++off; if (col == start_col) { if (did_delete) break; c = c2; } } if (end_col == Columns) LineWraps[row] = FALSE; if (row == Rows - 1) /* overwritten the command line */ { redraw_cmdline = TRUE; if (c1 == ' ' && c2 == ' ') clear_cmdline = FALSE; /* command line has been cleared */ if (start_col == 0) mode_displayed = FALSE; /* mode cleared or overwritten */ } } } /* * Check if there should be a delay. Used before clearing or redrawing the * screen or the command line. */ void check_for_delay(check_msg_scroll) int check_msg_scroll; { if ((emsg_on_display || (check_msg_scroll && msg_scroll)) && !did_wait_return && emsg_silent == 0) { out_flush(); ui_delay(1000L, TRUE); emsg_on_display = FALSE; if (check_msg_scroll) msg_scroll = FALSE; } } /* * screen_valid - allocate screen buffers if size changed * If "doclear" is TRUE: clear screen if it has been resized. * Returns TRUE if there is a valid screen to write to. * Returns FALSE when starting up and screen not initialized yet. */ int screen_valid(doclear) int doclear; { screenalloc(doclear); /* allocate screen buffers if size changed */ return (ScreenLines != NULL); } /* * Resize the shell to Rows and Columns. * Allocate ScreenLines[] and associated items. * * There may be some time between setting Rows and Columns and (re)allocating * ScreenLines[]. This happens when starting up and when (manually) changing * the shell size. Always use screen_Rows and screen_Columns to access items * in ScreenLines[]. Use Rows and Columns for positioning text etc. where the * final size of the shell is needed. */ void screenalloc(doclear) int doclear; { int new_row, old_row; #ifdef FEAT_GUI int old_Rows; #endif win_T *wp; int outofmem = FALSE; int len; schar_T *new_ScreenLines; #ifdef FEAT_MBYTE u8char_T *new_ScreenLinesUC = NULL; u8char_T *new_ScreenLinesC[MAX_MCO]; schar_T *new_ScreenLines2 = NULL; int i; #endif sattr_T *new_ScreenAttrs; unsigned *new_LineOffset; char_u *new_LineWraps; #ifdef FEAT_WINDOWS short *new_TabPageIdxs; tabpage_T *tp; #endif static int entered = FALSE; /* avoid recursiveness */ static int done_outofmem_msg = FALSE; /* did outofmem message */ #ifdef FEAT_AUTOCMD int retry_count = 0; retry: #endif /* * Allocation of the screen buffers is done only when the size changes and * when Rows and Columns have been set and we have started doing full * screen stuff. */ if ((ScreenLines != NULL && Rows == screen_Rows && Columns == screen_Columns #ifdef FEAT_MBYTE && enc_utf8 == (ScreenLinesUC != NULL) && (enc_dbcs == DBCS_JPNU) == (ScreenLines2 != NULL) && p_mco == Screen_mco #endif ) || Rows == 0 || Columns == 0 || (!full_screen && ScreenLines == NULL)) return; /* * It's possible that we produce an out-of-memory message below, which * will cause this function to be called again. To break the loop, just * return here. */ if (entered) return; entered = TRUE; /* * Note that the window sizes are updated before reallocating the arrays, * thus we must not redraw here! */ ++RedrawingDisabled; win_new_shellsize(); /* fit the windows in the new sized shell */ comp_col(); /* recompute columns for shown command and ruler */ /* * We're changing the size of the screen. * - Allocate new arrays for ScreenLines and ScreenAttrs. * - Move lines from the old arrays into the new arrays, clear extra * lines (unless the screen is going to be cleared). * - Free the old arrays. * * If anything fails, make ScreenLines NULL, so we don't do anything! * Continuing with the old ScreenLines may result in a crash, because the * size is wrong. */ FOR_ALL_TAB_WINDOWS(tp, wp) win_free_lsize(wp); #ifdef FEAT_AUTOCMD if (aucmd_win != NULL) win_free_lsize(aucmd_win); #endif new_ScreenLines = (schar_T *)lalloc((long_u)( (Rows + 1) * Columns * sizeof(schar_T)), FALSE); #ifdef FEAT_MBYTE vim_memset(new_ScreenLinesC, 0, sizeof(u8char_T *) * MAX_MCO); if (enc_utf8) { new_ScreenLinesUC = (u8char_T *)lalloc((long_u)( (Rows + 1) * Columns * sizeof(u8char_T)), FALSE); for (i = 0; i < p_mco; ++i) new_ScreenLinesC[i] = (u8char_T *)lalloc_clear((long_u)( (Rows + 1) * Columns * sizeof(u8char_T)), FALSE); } if (enc_dbcs == DBCS_JPNU) new_ScreenLines2 = (schar_T *)lalloc((long_u)( (Rows + 1) * Columns * sizeof(schar_T)), FALSE); #endif new_ScreenAttrs = (sattr_T *)lalloc((long_u)( (Rows + 1) * Columns * sizeof(sattr_T)), FALSE); new_LineOffset = (unsigned *)lalloc((long_u)( Rows * sizeof(unsigned)), FALSE); new_LineWraps = (char_u *)lalloc((long_u)(Rows * sizeof(char_u)), FALSE); #ifdef FEAT_WINDOWS new_TabPageIdxs = (short *)lalloc((long_u)(Columns * sizeof(short)), FALSE); #endif FOR_ALL_TAB_WINDOWS(tp, wp) { if (win_alloc_lines(wp) == FAIL) { outofmem = TRUE; #ifdef FEAT_WINDOWS goto give_up; #endif } } #ifdef FEAT_AUTOCMD if (aucmd_win != NULL && aucmd_win->w_lines == NULL && win_alloc_lines(aucmd_win) == FAIL) outofmem = TRUE; #endif #ifdef FEAT_WINDOWS give_up: #endif #ifdef FEAT_MBYTE for (i = 0; i < p_mco; ++i) if (new_ScreenLinesC[i] == NULL) break; #endif if (new_ScreenLines == NULL #ifdef FEAT_MBYTE || (enc_utf8 && (new_ScreenLinesUC == NULL || i != p_mco)) || (enc_dbcs == DBCS_JPNU && new_ScreenLines2 == NULL) #endif || new_ScreenAttrs == NULL || new_LineOffset == NULL || new_LineWraps == NULL #ifdef FEAT_WINDOWS || new_TabPageIdxs == NULL #endif || outofmem) { if (ScreenLines != NULL || !done_outofmem_msg) { /* guess the size */ do_outofmem_msg((long_u)((Rows + 1) * Columns)); /* Remember we did this to avoid getting outofmem messages over * and over again. */ done_outofmem_msg = TRUE; } vim_free(new_ScreenLines); new_ScreenLines = NULL; #ifdef FEAT_MBYTE vim_free(new_ScreenLinesUC); new_ScreenLinesUC = NULL; for (i = 0; i < p_mco; ++i) { vim_free(new_ScreenLinesC[i]); new_ScreenLinesC[i] = NULL; } vim_free(new_ScreenLines2); new_ScreenLines2 = NULL; #endif vim_free(new_ScreenAttrs); new_ScreenAttrs = NULL; vim_free(new_LineOffset); new_LineOffset = NULL; vim_free(new_LineWraps); new_LineWraps = NULL; #ifdef FEAT_WINDOWS vim_free(new_TabPageIdxs); new_TabPageIdxs = NULL; #endif } else { done_outofmem_msg = FALSE; for (new_row = 0; new_row < Rows; ++new_row) { new_LineOffset[new_row] = new_row * Columns; new_LineWraps[new_row] = FALSE; /* * If the screen is not going to be cleared, copy as much as * possible from the old screen to the new one and clear the rest * (used when resizing the window at the "--more--" prompt or when * executing an external command, for the GUI). */ if (!doclear) { (void)vim_memset(new_ScreenLines + new_row * Columns, ' ', (size_t)Columns * sizeof(schar_T)); #ifdef FEAT_MBYTE if (enc_utf8) { (void)vim_memset(new_ScreenLinesUC + new_row * Columns, 0, (size_t)Columns * sizeof(u8char_T)); for (i = 0; i < p_mco; ++i) (void)vim_memset(new_ScreenLinesC[i] + new_row * Columns, 0, (size_t)Columns * sizeof(u8char_T)); } if (enc_dbcs == DBCS_JPNU) (void)vim_memset(new_ScreenLines2 + new_row * Columns, 0, (size_t)Columns * sizeof(schar_T)); #endif (void)vim_memset(new_ScreenAttrs + new_row * Columns, 0, (size_t)Columns * sizeof(sattr_T)); old_row = new_row + (screen_Rows - Rows); if (old_row >= 0 && ScreenLines != NULL) { if (screen_Columns < Columns) len = screen_Columns; else len = Columns; #ifdef FEAT_MBYTE /* When switching to utf-8 don't copy characters, they * may be invalid now. Also when p_mco changes. */ if (!(enc_utf8 && ScreenLinesUC == NULL) && p_mco == Screen_mco) #endif mch_memmove(new_ScreenLines + new_LineOffset[new_row], ScreenLines + LineOffset[old_row], (size_t)len * sizeof(schar_T)); #ifdef FEAT_MBYTE if (enc_utf8 && ScreenLinesUC != NULL && p_mco == Screen_mco) { mch_memmove(new_ScreenLinesUC + new_LineOffset[new_row], ScreenLinesUC + LineOffset[old_row], (size_t)len * sizeof(u8char_T)); for (i = 0; i < p_mco; ++i) mch_memmove(new_ScreenLinesC[i] + new_LineOffset[new_row], ScreenLinesC[i] + LineOffset[old_row], (size_t)len * sizeof(u8char_T)); } if (enc_dbcs == DBCS_JPNU && ScreenLines2 != NULL) mch_memmove(new_ScreenLines2 + new_LineOffset[new_row], ScreenLines2 + LineOffset[old_row], (size_t)len * sizeof(schar_T)); #endif mch_memmove(new_ScreenAttrs + new_LineOffset[new_row], ScreenAttrs + LineOffset[old_row], (size_t)len * sizeof(sattr_T)); } } } /* Use the last line of the screen for the current line. */ current_ScreenLine = new_ScreenLines + Rows * Columns; } free_screenlines(); ScreenLines = new_ScreenLines; #ifdef FEAT_MBYTE ScreenLinesUC = new_ScreenLinesUC; for (i = 0; i < p_mco; ++i) ScreenLinesC[i] = new_ScreenLinesC[i]; Screen_mco = p_mco; ScreenLines2 = new_ScreenLines2; #endif ScreenAttrs = new_ScreenAttrs; LineOffset = new_LineOffset; LineWraps = new_LineWraps; #ifdef FEAT_WINDOWS TabPageIdxs = new_TabPageIdxs; #endif /* It's important that screen_Rows and screen_Columns reflect the actual * size of ScreenLines[]. Set them before calling anything. */ #ifdef FEAT_GUI old_Rows = screen_Rows; #endif screen_Rows = Rows; screen_Columns = Columns; must_redraw = CLEAR; /* need to clear the screen later */ if (doclear) screenclear2(); #ifdef FEAT_GUI else if (gui.in_use && !gui.starting && ScreenLines != NULL && old_Rows != Rows) { (void)gui_redraw_block(0, 0, (int)Rows - 1, (int)Columns - 1, 0); /* * Adjust the position of the cursor, for when executing an external * command. */ if (msg_row >= Rows) /* Rows got smaller */ msg_row = Rows - 1; /* put cursor at last row */ else if (Rows > old_Rows) /* Rows got bigger */ msg_row += Rows - old_Rows; /* put cursor in same place */ if (msg_col >= Columns) /* Columns got smaller */ msg_col = Columns - 1; /* put cursor at last column */ } #endif entered = FALSE; --RedrawingDisabled; #ifdef FEAT_AUTOCMD /* * Do not apply autocommands more than 3 times to avoid an endless loop * in case applying autocommands always changes Rows or Columns. */ if (starting == 0 && ++retry_count <= 3) { apply_autocmds(EVENT_VIMRESIZED, NULL, NULL, FALSE, curbuf); /* In rare cases, autocommands may have altered Rows or Columns, * jump back to check if we need to allocate the screen again. */ goto retry; } #endif } void free_screenlines() { #ifdef FEAT_MBYTE int i; vim_free(ScreenLinesUC); for (i = 0; i < Screen_mco; ++i) vim_free(ScreenLinesC[i]); vim_free(ScreenLines2); #endif vim_free(ScreenLines); vim_free(ScreenAttrs); vim_free(LineOffset); vim_free(LineWraps); #ifdef FEAT_WINDOWS vim_free(TabPageIdxs); #endif } void screenclear() { check_for_delay(FALSE); screenalloc(FALSE); /* allocate screen buffers if size changed */ screenclear2(); /* clear the screen */ } static void screenclear2() { int i; if (starting == NO_SCREEN || ScreenLines == NULL #ifdef FEAT_GUI || (gui.in_use && gui.starting) #endif ) return; #ifdef FEAT_GUI if (!gui.in_use) #endif screen_attr = -1; /* force setting the Normal colors */ screen_stop_highlight(); /* don't want highlighting here */ #ifdef FEAT_CLIPBOARD /* disable selection without redrawing it */ clip_scroll_selection(9999); #endif /* blank out ScreenLines */ for (i = 0; i < Rows; ++i) { lineclear(LineOffset[i], (int)Columns); LineWraps[i] = FALSE; } if (can_clear(T_CL)) { out_str(T_CL); /* clear the display */ clear_cmdline = FALSE; mode_displayed = FALSE; } else { /* can't clear the screen, mark all chars with invalid attributes */ for (i = 0; i < Rows; ++i) lineinvalid(LineOffset[i], (int)Columns); clear_cmdline = TRUE; } screen_cleared = TRUE; /* can use contents of ScreenLines now */ win_rest_invalid(firstwin); redraw_cmdline = TRUE; #ifdef FEAT_WINDOWS redraw_tabline = TRUE; #endif if (must_redraw == CLEAR) /* no need to clear again */ must_redraw = NOT_VALID; compute_cmdrow(); msg_row = cmdline_row; /* put cursor on last line for messages */ msg_col = 0; screen_start(); /* don't know where cursor is now */ msg_scrolled = 0; /* can't scroll back */ msg_didany = FALSE; msg_didout = FALSE; } /* * Clear one line in ScreenLines. */ static void lineclear(off, width) unsigned off; int width; { (void)vim_memset(ScreenLines + off, ' ', (size_t)width * sizeof(schar_T)); #ifdef FEAT_MBYTE if (enc_utf8) (void)vim_memset(ScreenLinesUC + off, 0, (size_t)width * sizeof(u8char_T)); #endif (void)vim_memset(ScreenAttrs + off, 0, (size_t)width * sizeof(sattr_T)); } /* * Mark one line in ScreenLines invalid by setting the attributes to an * invalid value. */ static void lineinvalid(off, width) unsigned off; int width; { (void)vim_memset(ScreenAttrs + off, -1, (size_t)width * sizeof(sattr_T)); } #ifdef FEAT_VERTSPLIT /* * Copy part of a Screenline for vertically split window "wp". */ static void linecopy(to, from, wp) int to; int from; win_T *wp; { unsigned off_to = LineOffset[to] + wp->w_wincol; unsigned off_from = LineOffset[from] + wp->w_wincol; mch_memmove(ScreenLines + off_to, ScreenLines + off_from, wp->w_width * sizeof(schar_T)); # ifdef FEAT_MBYTE if (enc_utf8) { int i; mch_memmove(ScreenLinesUC + off_to, ScreenLinesUC + off_from, wp->w_width * sizeof(u8char_T)); for (i = 0; i < p_mco; ++i) mch_memmove(ScreenLinesC[i] + off_to, ScreenLinesC[i] + off_from, wp->w_width * sizeof(u8char_T)); } if (enc_dbcs == DBCS_JPNU) mch_memmove(ScreenLines2 + off_to, ScreenLines2 + off_from, wp->w_width * sizeof(schar_T)); # endif mch_memmove(ScreenAttrs + off_to, ScreenAttrs + off_from, wp->w_width * sizeof(sattr_T)); } #endif /* * Return TRUE if clearing with term string "p" would work. * It can't work when the string is empty or it won't set the right background. */ int can_clear(p) char_u *p; { return (*p != NUL && (t_colors <= 1 #ifdef FEAT_GUI || gui.in_use #endif || cterm_normal_bg_color == 0 || *T_UT != NUL)); } /* * Reset cursor position. Use whenever cursor was moved because of outputting * something directly to the screen (shell commands) or a terminal control * code. */ void screen_start() { screen_cur_row = screen_cur_col = 9999; } /* * Move the cursor to position "row","col" in the screen. * This tries to find the most efficient way to move, minimizing the number of * characters sent to the terminal. */ void windgoto(row, col) int row; int col; { sattr_T *p; int i; int plan; int cost; int wouldbe_col; int noinvcurs; char_u *bs; int goto_cost; int attr; #define GOTO_COST 7 /* assume a term_windgoto() takes about 7 chars */ #define HIGHL_COST 5 /* assume unhighlight takes 5 chars */ #define PLAN_LE 1 #define PLAN_CR 2 #define PLAN_NL 3 #define PLAN_WRITE 4 /* Can't use ScreenLines unless initialized */ if (ScreenLines == NULL) return; if (col != screen_cur_col || row != screen_cur_row) { /* Check for valid position. */ if (row < 0) /* window without text lines? */ row = 0; if (row >= screen_Rows) row = screen_Rows - 1; if (col >= screen_Columns) col = screen_Columns - 1; /* check if no cursor movement is allowed in highlight mode */ if (screen_attr && *T_MS == NUL) noinvcurs = HIGHL_COST; else noinvcurs = 0; goto_cost = GOTO_COST + noinvcurs; /* * Plan how to do the positioning: * 1. Use CR to move it to column 0, same row. * 2. Use T_LE to move it a few columns to the left. * 3. Use NL to move a few lines down, column 0. * 4. Move a few columns to the right with T_ND or by writing chars. * * Don't do this if the cursor went beyond the last column, the cursor * position is unknown then (some terminals wrap, some don't ) * * First check if the highlighting attributes allow us to write * characters to move the cursor to the right. */ if (row >= screen_cur_row && screen_cur_col < Columns) { /* * If the cursor is in the same row, bigger col, we can use CR * or T_LE. */ bs = NULL; /* init for GCC */ attr = screen_attr; if (row == screen_cur_row && col < screen_cur_col) { /* "le" is preferred over "bc", because "bc" is obsolete */ if (*T_LE) bs = T_LE; /* "cursor left" */ else bs = T_BC; /* "backspace character (old) */ if (*bs) cost = (screen_cur_col - col) * (int)STRLEN(bs); else cost = 999; if (col + 1 < cost) /* using CR is less characters */ { plan = PLAN_CR; wouldbe_col = 0; cost = 1; /* CR is just one character */ } else { plan = PLAN_LE; wouldbe_col = col; } if (noinvcurs) /* will stop highlighting */ { cost += noinvcurs; attr = 0; } } /* * If the cursor is above where we want to be, we can use CR LF. */ else if (row > screen_cur_row) { plan = PLAN_NL; wouldbe_col = 0; cost = (row - screen_cur_row) * 2; /* CR LF */ if (noinvcurs) /* will stop highlighting */ { cost += noinvcurs; attr = 0; } } /* * If the cursor is in the same row, smaller col, just use write. */ else { plan = PLAN_WRITE; wouldbe_col = screen_cur_col; cost = 0; } /* * Check if any characters that need to be written have the * correct attributes. Also avoid UTF-8 characters. */ i = col - wouldbe_col; if (i > 0) cost += i; if (cost < goto_cost && i > 0) { /* * Check if the attributes are correct without additionally * stopping highlighting. */ p = ScreenAttrs + LineOffset[row] + wouldbe_col; while (i && *p++ == attr) --i; if (i != 0) { /* * Try if it works when highlighting is stopped here. */ if (*--p == 0) { cost += noinvcurs; while (i && *p++ == 0) --i; } if (i != 0) cost = 999; /* different attributes, don't do it */ } #ifdef FEAT_MBYTE if (enc_utf8) { /* Don't use an UTF-8 char for positioning, it's slow. */ for (i = wouldbe_col; i < col; ++i) if (ScreenLinesUC[LineOffset[row] + i] != 0) { cost = 999; break; } } #endif } /* * We can do it without term_windgoto()! */ if (cost < goto_cost) { if (plan == PLAN_LE) { if (noinvcurs) screen_stop_highlight(); while (screen_cur_col > col) { out_str(bs); --screen_cur_col; } } else if (plan == PLAN_CR) { if (noinvcurs) screen_stop_highlight(); out_char('\r'); screen_cur_col = 0; } else if (plan == PLAN_NL) { if (noinvcurs) screen_stop_highlight(); while (screen_cur_row < row) { out_char('\n'); ++screen_cur_row; } screen_cur_col = 0; } i = col - screen_cur_col; if (i > 0) { /* * Use cursor-right if it's one character only. Avoids * removing a line of pixels from the last bold char, when * using the bold trick in the GUI. */ if (T_ND[0] != NUL && T_ND[1] == NUL) { while (i-- > 0) out_char(*T_ND); } else { int off; off = LineOffset[row] + screen_cur_col; while (i-- > 0) { if (ScreenAttrs[off] != screen_attr) screen_stop_highlight(); #ifdef FEAT_MBYTE out_flush_check(); #endif out_char(ScreenLines[off]); #ifdef FEAT_MBYTE if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e) out_char(ScreenLines2[off]); #endif ++off; } } } } } else cost = 999; if (cost >= goto_cost) { if (noinvcurs) screen_stop_highlight(); if (row == screen_cur_row && (col > screen_cur_col) && *T_CRI != NUL) term_cursor_right(col - screen_cur_col); else term_windgoto(row, col); } screen_cur_row = row; screen_cur_col = col; } } /* * Set cursor to its position in the current window. */ void setcursor() { if (redrawing()) { validate_cursor(); windgoto(W_WINROW(curwin) + curwin->w_wrow, W_WINCOL(curwin) + ( #ifdef FEAT_RIGHTLEFT /* With 'rightleft' set and the cursor on a double-wide * character, position it on the leftmost column. */ curwin->w_p_rl ? ((int)W_WIDTH(curwin) - curwin->w_wcol - ( # ifdef FEAT_MBYTE (has_mbyte && (*mb_ptr2cells)(ml_get_cursor()) == 2 && vim_isprintc(gchar_cursor())) ? 2 : # endif 1)) : #endif curwin->w_wcol)); } } /* * insert 'line_count' lines at 'row' in window 'wp' * if 'invalid' is TRUE the wp->w_lines[].wl_lnum is invalidated. * if 'mayclear' is TRUE the screen will be cleared if it is faster than * scrolling. * Returns FAIL if the lines are not inserted, OK for success. */ int win_ins_lines(wp, row, line_count, invalid, mayclear) win_T *wp; int row; int line_count; int invalid; int mayclear; { int did_delete; int nextrow; int lastrow; int retval; if (invalid) wp->w_lines_valid = 0; if (wp->w_height < 5) return FAIL; if (line_count > wp->w_height - row) line_count = wp->w_height - row; retval = win_do_lines(wp, row, line_count, mayclear, FALSE); if (retval != MAYBE) return retval; /* * If there is a next window or a status line, we first try to delete the * lines at the bottom to avoid messing what is after the window. * If this fails and there are following windows, don't do anything to avoid * messing up those windows, better just redraw. */ did_delete = FALSE; #ifdef FEAT_WINDOWS if (wp->w_next != NULL || wp->w_status_height) { if (screen_del_lines(0, W_WINROW(wp) + wp->w_height - line_count, line_count, (int)Rows, FALSE, NULL) == OK) did_delete = TRUE; else if (wp->w_next) return FAIL; } #endif /* * if no lines deleted, blank the lines that will end up below the window */ if (!did_delete) { #ifdef FEAT_WINDOWS wp->w_redr_status = TRUE; #endif redraw_cmdline = TRUE; nextrow = W_WINROW(wp) + wp->w_height + W_STATUS_HEIGHT(wp); lastrow = nextrow + line_count; if (lastrow > Rows) lastrow = Rows; screen_fill(nextrow - line_count, lastrow - line_count, W_WINCOL(wp), (int)W_ENDCOL(wp), ' ', ' ', 0); } if (screen_ins_lines(0, W_WINROW(wp) + row, line_count, (int)Rows, NULL) == FAIL) { /* deletion will have messed up other windows */ if (did_delete) { #ifdef FEAT_WINDOWS wp->w_redr_status = TRUE; #endif win_rest_invalid(W_NEXT(wp)); } return FAIL; } return OK; } /* * delete "line_count" window lines at "row" in window "wp" * If "invalid" is TRUE curwin->w_lines[] is invalidated. * If "mayclear" is TRUE the screen will be cleared if it is faster than * scrolling * Return OK for success, FAIL if the lines are not deleted. */ int win_del_lines(wp, row, line_count, invalid, mayclear) win_T *wp; int row; int line_count; int invalid; int mayclear; { int retval; if (invalid) wp->w_lines_valid = 0; if (line_count > wp->w_height - row) line_count = wp->w_height - row; retval = win_do_lines(wp, row, line_count, mayclear, TRUE); if (retval != MAYBE) return retval; if (screen_del_lines(0, W_WINROW(wp) + row, line_count, (int)Rows, FALSE, NULL) == FAIL) return FAIL; #ifdef FEAT_WINDOWS /* * If there are windows or status lines below, try to put them at the * correct place. If we can't do that, they have to be redrawn. */ if (wp->w_next || wp->w_status_height || cmdline_row < Rows - 1) { if (screen_ins_lines(0, W_WINROW(wp) + wp->w_height - line_count, line_count, (int)Rows, NULL) == FAIL) { wp->w_redr_status = TRUE; win_rest_invalid(wp->w_next); } } /* * If this is the last window and there is no status line, redraw the * command line later. */ else #endif redraw_cmdline = TRUE; return OK; } /* * Common code for win_ins_lines() and win_del_lines(). * Returns OK or FAIL when the work has been done. * Returns MAYBE when not finished yet. */ static int win_do_lines(wp, row, line_count, mayclear, del) win_T *wp; int row; int line_count; int mayclear; int del; { int retval; if (!redrawing() || line_count <= 0) return FAIL; /* only a few lines left: redraw is faster */ if (mayclear && Rows - line_count < 5 #ifdef FEAT_VERTSPLIT && wp->w_width == Columns #endif ) { screenclear(); /* will set wp->w_lines_valid to 0 */ return FAIL; } /* * Delete all remaining lines */ if (row + line_count >= wp->w_height) { screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + wp->w_height, W_WINCOL(wp), (int)W_ENDCOL(wp), ' ', ' ', 0); return OK; } /* * when scrolling, the message on the command line should be cleared, * otherwise it will stay there forever. */ clear_cmdline = TRUE; /* * If the terminal can set a scroll region, use that. * Always do this in a vertically split window. This will redraw from * ScreenLines[] when t_CV isn't defined. That's faster than using * win_line(). * Don't use a scroll region when we are going to redraw the text, writing * a character in the lower right corner of the scroll region causes a * scroll-up in the DJGPP version. */ if (scroll_region #ifdef FEAT_VERTSPLIT || W_WIDTH(wp) != Columns #endif ) { #ifdef FEAT_VERTSPLIT if (scroll_region && (wp->w_width == Columns || *T_CSV != NUL)) #endif scroll_region_set(wp, row); if (del) retval = screen_del_lines(W_WINROW(wp) + row, 0, line_count, wp->w_height - row, FALSE, wp); else retval = screen_ins_lines(W_WINROW(wp) + row, 0, line_count, wp->w_height - row, wp); #ifdef FEAT_VERTSPLIT if (scroll_region && (wp->w_width == Columns || *T_CSV != NUL)) #endif scroll_region_reset(); return retval; } #ifdef FEAT_WINDOWS if (wp->w_next != NULL && p_tf) /* don't delete/insert on fast terminal */ return FAIL; #endif return MAYBE; } /* * window 'wp' and everything after it is messed up, mark it for redraw */ static void win_rest_invalid(wp) win_T *wp; { #ifdef FEAT_WINDOWS while (wp != NULL) #else if (wp != NULL) #endif { redraw_win_later(wp, NOT_VALID); #ifdef FEAT_WINDOWS wp->w_redr_status = TRUE; wp = wp->w_next; #endif } redraw_cmdline = TRUE; } /* * The rest of the routines in this file perform screen manipulations. The * given operation is performed physically on the screen. The corresponding * change is also made to the internal screen image. In this way, the editor * anticipates the effect of editing changes on the appearance of the screen. * That way, when we call screenupdate a complete redraw isn't usually * necessary. Another advantage is that we can keep adding code to anticipate * screen changes, and in the meantime, everything still works. */ /* * types for inserting or deleting lines */ #define USE_T_CAL 1 #define USE_T_CDL 2 #define USE_T_AL 3 #define USE_T_CE 4 #define USE_T_DL 5 #define USE_T_SR 6 #define USE_NL 7 #define USE_T_CD 8 #define USE_REDRAW 9 /* * insert lines on the screen and update ScreenLines[] * 'end' is the line after the scrolled part. Normally it is Rows. * When scrolling region used 'off' is the offset from the top for the region. * 'row' and 'end' are relative to the start of the region. * * return FAIL for failure, OK for success. */ int screen_ins_lines(off, row, line_count, end, wp) int off; int row; int line_count; int end; win_T *wp; /* NULL or window to use width from */ { int i; int j; unsigned temp; int cursor_row; int type; int result_empty; int can_ce = can_clear(T_CE); /* * FAIL if * - there is no valid screen * - the screen has to be redrawn completely * - the line count is less than one * - the line count is more than 'ttyscroll' */ if (!screen_valid(TRUE) || line_count <= 0 || line_count > p_ttyscroll) return FAIL; /* * There are seven ways to insert lines: * 0. When in a vertically split window and t_CV isn't set, redraw the * characters from ScreenLines[]. * 1. Use T_CD (clear to end of display) if it exists and the result of * the insert is just empty lines * 2. Use T_CAL (insert multiple lines) if it exists and T_AL is not * present or line_count > 1. It looks better if we do all the inserts * at once. * 3. Use T_CDL (delete multiple lines) if it exists and the result of the * insert is just empty lines and T_CE is not present or line_count > * 1. * 4. Use T_AL (insert line) if it exists. * 5. Use T_CE (erase line) if it exists and the result of the insert is * just empty lines. * 6. Use T_DL (delete line) if it exists and the result of the insert is * just empty lines. * 7. Use T_SR (scroll reverse) if it exists and inserting at row 0 and * the 'da' flag is not set or we have clear line capability. * 8. redraw the characters from ScreenLines[]. * * Careful: In a hpterm scroll reverse doesn't work as expected, it moves * the scrollbar for the window. It does have insert line, use that if it * exists. */ result_empty = (row + line_count >= end); #ifdef FEAT_VERTSPLIT if (wp != NULL && wp->w_width != Columns && *T_CSV == NUL) type = USE_REDRAW; else #endif if (can_clear(T_CD) && result_empty) type = USE_T_CD; else if (*T_CAL != NUL && (line_count > 1 || *T_AL == NUL)) type = USE_T_CAL; else if (*T_CDL != NUL && result_empty && (line_count > 1 || !can_ce)) type = USE_T_CDL; else if (*T_AL != NUL) type = USE_T_AL; else if (can_ce && result_empty) type = USE_T_CE; else if (*T_DL != NUL && result_empty) type = USE_T_DL; else if (*T_SR != NUL && row == 0 && (*T_DA == NUL || can_ce)) type = USE_T_SR; else return FAIL; /* * For clearing the lines screen_del_lines() is used. This will also take * care of t_db if necessary. */ if (type == USE_T_CD || type == USE_T_CDL || type == USE_T_CE || type == USE_T_DL) return screen_del_lines(off, row, line_count, end, FALSE, wp); /* * If text is retained below the screen, first clear or delete as many * lines at the bottom of the window as are about to be inserted so that * the deleted lines won't later surface during a screen_del_lines. */ if (*T_DB) screen_del_lines(off, end - line_count, line_count, end, FALSE, wp); #ifdef FEAT_CLIPBOARD /* Remove a modeless selection when inserting lines halfway the screen * or not the full width of the screen. */ if (off + row > 0 # ifdef FEAT_VERTSPLIT || (wp != NULL && wp->w_width != Columns) # endif ) clip_clear_selection(&clip_star); else clip_scroll_selection(-line_count); #endif #ifdef FEAT_GUI /* Don't update the GUI cursor here, ScreenLines[] is invalid until the * scrolling is actually carried out. */ gui_dont_update_cursor(); #endif if (*T_CCS != NUL) /* cursor relative to region */ cursor_row = row; else cursor_row = row + off; /* * Shift LineOffset[] line_count down to reflect the inserted lines. * Clear the inserted lines in ScreenLines[]. */ row += off; end += off; for (i = 0; i < line_count; ++i) { #ifdef FEAT_VERTSPLIT if (wp != NULL && wp->w_width != Columns) { /* need to copy part of a line */ j = end - 1 - i; while ((j -= line_count) >= row) linecopy(j + line_count, j, wp); j += line_count; if (can_clear((char_u *)" ")) lineclear(LineOffset[j] + wp->w_wincol, wp->w_width); else lineinvalid(LineOffset[j] + wp->w_wincol, wp->w_width); LineWraps[j] = FALSE; } else #endif { j = end - 1 - i; temp = LineOffset[j]; while ((j -= line_count) >= row) { LineOffset[j + line_count] = LineOffset[j]; LineWraps[j + line_count] = LineWraps[j]; } LineOffset[j + line_count] = temp; LineWraps[j + line_count] = FALSE; if (can_clear((char_u *)" ")) lineclear(temp, (int)Columns); else lineinvalid(temp, (int)Columns); } } screen_stop_highlight(); windgoto(cursor_row, 0); #ifdef FEAT_VERTSPLIT /* redraw the characters */ if (type == USE_REDRAW) redraw_block(row, end, wp); else #endif if (type == USE_T_CAL) { term_append_lines(line_count); screen_start(); /* don't know where cursor is now */ } else { for (i = 0; i < line_count; i++) { if (type == USE_T_AL) { if (i && cursor_row != 0) windgoto(cursor_row, 0); out_str(T_AL); } else /* type == USE_T_SR */ out_str(T_SR); screen_start(); /* don't know where cursor is now */ } } /* * With scroll-reverse and 'da' flag set we need to clear the lines that * have been scrolled down into the region. */ if (type == USE_T_SR && *T_DA) { for (i = 0; i < line_count; ++i) { windgoto(off + i, 0); out_str(T_CE); screen_start(); /* don't know where cursor is now */ } } #ifdef FEAT_GUI gui_can_update_cursor(); if (gui.in_use) out_flush(); /* always flush after a scroll */ #endif return OK; } /* * delete lines on the screen and update ScreenLines[] * 'end' is the line after the scrolled part. Normally it is Rows. * When scrolling region used 'off' is the offset from the top for the region. * 'row' and 'end' are relative to the start of the region. * * Return OK for success, FAIL if the lines are not deleted. */ int screen_del_lines(off, row, line_count, end, force, wp) int off; int row; int line_count; int end; int force; /* even when line_count > p_ttyscroll */ win_T *wp UNUSED; /* NULL or window to use width from */ { int j; int i; unsigned temp; int cursor_row; int cursor_end; int result_empty; /* result is empty until end of region */ int can_delete; /* deleting line codes can be used */ int type; /* * FAIL if * - there is no valid screen * - the screen has to be redrawn completely * - the line count is less than one * - the line count is more than 'ttyscroll' */ if (!screen_valid(TRUE) || line_count <= 0 || (!force && line_count > p_ttyscroll)) return FAIL; /* * Check if the rest of the current region will become empty. */ result_empty = row + line_count >= end; /* * We can delete lines only when 'db' flag not set or when 'ce' option * available. */ can_delete = (*T_DB == NUL || can_clear(T_CE)); /* * There are six ways to delete lines: * 0. When in a vertically split window and t_CV isn't set, redraw the * characters from ScreenLines[]. * 1. Use T_CD if it exists and the result is empty. * 2. Use newlines if row == 0 and count == 1 or T_CDL does not exist. * 3. Use T_CDL (delete multiple lines) if it exists and line_count > 1 or * none of the other ways work. * 4. Use T_CE (erase line) if the result is empty. * 5. Use T_DL (delete line) if it exists. * 6. redraw the characters from ScreenLines[]. */ #ifdef FEAT_VERTSPLIT if (wp != NULL && wp->w_width != Columns && *T_CSV == NUL) type = USE_REDRAW; else #endif if (can_clear(T_CD) && result_empty) type = USE_T_CD; #if defined(__BEOS__) && defined(BEOS_DR8) /* * USE_NL does not seem to work in Terminal of DR8 so we set T_DB="" in * its internal termcap... this works okay for tests which test *T_DB != * NUL. It has the disadvantage that the user cannot use any :set t_* * command to get T_DB (back) to empty_option, only :set term=... will do * the trick... * Anyway, this hack will hopefully go away with the next OS release. * (Olaf Seibert) */ else if (row == 0 && T_DB == empty_option && (line_count == 1 || *T_CDL == NUL)) #else else if (row == 0 && ( #ifndef AMIGA /* On the Amiga, somehow '\n' on the last line doesn't always scroll * up, so use delete-line command */ line_count == 1 || #endif *T_CDL == NUL)) #endif type = USE_NL; else if (*T_CDL != NUL && line_count > 1 && can_delete) type = USE_T_CDL; else if (can_clear(T_CE) && result_empty #ifdef FEAT_VERTSPLIT && (wp == NULL || wp->w_width == Columns) #endif ) type = USE_T_CE; else if (*T_DL != NUL && can_delete) type = USE_T_DL; else if (*T_CDL != NUL && can_delete) type = USE_T_CDL; else return FAIL; #ifdef FEAT_CLIPBOARD /* Remove a modeless selection when deleting lines halfway the screen or * not the full width of the screen. */ if (off + row > 0 # ifdef FEAT_VERTSPLIT || (wp != NULL && wp->w_width != Columns) # endif ) clip_clear_selection(&clip_star); else clip_scroll_selection(line_count); #endif #ifdef FEAT_GUI /* Don't update the GUI cursor here, ScreenLines[] is invalid until the * scrolling is actually carried out. */ gui_dont_update_cursor(); #endif if (*T_CCS != NUL) /* cursor relative to region */ { cursor_row = row; cursor_end = end; } else { cursor_row = row + off; cursor_end = end + off; } /* * Now shift LineOffset[] line_count up to reflect the deleted lines. * Clear the inserted lines in ScreenLines[]. */ row += off; end += off; for (i = 0; i < line_count; ++i) { #ifdef FEAT_VERTSPLIT if (wp != NULL && wp->w_width != Columns) { /* need to copy part of a line */ j = row + i; while ((j += line_count) <= end - 1) linecopy(j - line_count, j, wp); j -= line_count; if (can_clear((char_u *)" ")) lineclear(LineOffset[j] + wp->w_wincol, wp->w_width); else lineinvalid(LineOffset[j] + wp->w_wincol, wp->w_width); LineWraps[j] = FALSE; } else #endif { /* whole width, moving the line pointers is faster */ j = row + i; temp = LineOffset[j]; while ((j += line_count) <= end - 1) { LineOffset[j - line_count] = LineOffset[j]; LineWraps[j - line_count] = LineWraps[j]; } LineOffset[j - line_count] = temp; LineWraps[j - line_count] = FALSE; if (can_clear((char_u *)" ")) lineclear(temp, (int)Columns); else lineinvalid(temp, (int)Columns); } } screen_stop_highlight(); #ifdef FEAT_VERTSPLIT /* redraw the characters */ if (type == USE_REDRAW) redraw_block(row, end, wp); else #endif if (type == USE_T_CD) /* delete the lines */ { windgoto(cursor_row, 0); out_str(T_CD); screen_start(); /* don't know where cursor is now */ } else if (type == USE_T_CDL) { windgoto(cursor_row, 0); term_delete_lines(line_count); screen_start(); /* don't know where cursor is now */ } /* * Deleting lines at top of the screen or scroll region: Just scroll * the whole screen (scroll region) up by outputting newlines on the * last line. */ else if (type == USE_NL) { windgoto(cursor_end - 1, 0); for (i = line_count; --i >= 0; ) out_char('\n'); /* cursor will remain on same line */ } else { for (i = line_count; --i >= 0; ) { if (type == USE_T_DL) { windgoto(cursor_row, 0); out_str(T_DL); /* delete a line */ } else /* type == USE_T_CE */ { windgoto(cursor_row + i, 0); out_str(T_CE); /* erase a line */ } screen_start(); /* don't know where cursor is now */ } } /* * If the 'db' flag is set, we need to clear the lines that have been * scrolled up at the bottom of the region. */ if (*T_DB && (type == USE_T_DL || type == USE_T_CDL)) { for (i = line_count; i > 0; --i) { windgoto(cursor_end - i, 0); out_str(T_CE); /* erase a line */ screen_start(); /* don't know where cursor is now */ } } #ifdef FEAT_GUI gui_can_update_cursor(); if (gui.in_use) out_flush(); /* always flush after a scroll */ #endif return OK; } /* * show the current mode and ruler * * If clear_cmdline is TRUE, clear the rest of the cmdline. * If clear_cmdline is FALSE there may be a message there that needs to be * cleared only if a mode is shown. * Return the length of the message (0 if no message). */ int showmode() { int need_clear; int length = 0; int do_mode; int attr; int nwr_save; #ifdef FEAT_INS_EXPAND int sub_attr; #endif do_mode = ((p_smd && msg_silent == 0) && ((State & INSERT) || restart_edit || VIsual_active)); if (do_mode || Recording) { /* * Don't show mode right now, when not redrawing or inside a mapping. * Call char_avail() only when we are going to show something, because * it takes a bit of time. */ if (!redrawing() || (char_avail() && !KeyTyped) || msg_silent != 0) { redraw_cmdline = TRUE; /* show mode later */ return 0; } nwr_save = need_wait_return; /* wait a bit before overwriting an important message */ check_for_delay(FALSE); /* if the cmdline is more than one line high, erase top lines */ need_clear = clear_cmdline; if (clear_cmdline && cmdline_row < Rows - 1) msg_clr_cmdline(); /* will reset clear_cmdline */ /* Position on the last line in the window, column 0 */ msg_pos_mode(); cursor_off(); attr = hl_attr(HLF_CM); /* Highlight mode */ if (do_mode) { MSG_PUTS_ATTR("--", attr); #if defined(FEAT_XIM) if ( # if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MACVIM) preedit_get_status() # else im_get_status() # endif ) # if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MACVIM) /* most of the time, it's not XIM being used */ MSG_PUTS_ATTR(" IM", attr); # else MSG_PUTS_ATTR(" XIM", attr); # endif #endif #if defined(FEAT_HANGULIN) && defined(FEAT_GUI) if (gui.in_use) { if (hangul_input_state_get()) MSG_PUTS_ATTR(" \307\321\261\333", attr); /* HANGUL */ } #endif #ifdef FEAT_INS_EXPAND /* CTRL-X in Insert mode */ if (edit_submode != NULL && !shortmess(SHM_COMPLETIONMENU)) { /* These messages can get long, avoid a wrap in a narrow * window. Prefer showing edit_submode_extra. */ length = (Rows - msg_row) * Columns - 3; if (edit_submode_extra != NULL) length -= vim_strsize(edit_submode_extra); if (length > 0) { if (edit_submode_pre != NULL) length -= vim_strsize(edit_submode_pre); if (length - vim_strsize(edit_submode) > 0) { if (edit_submode_pre != NULL) msg_puts_attr(edit_submode_pre, attr); msg_puts_attr(edit_submode, attr); } if (edit_submode_extra != NULL) { MSG_PUTS_ATTR(" ", attr); /* add a space in between */ if ((int)edit_submode_highl < (int)HLF_COUNT) sub_attr = hl_attr(edit_submode_highl); else sub_attr = attr; msg_puts_attr(edit_submode_extra, sub_attr); } } length = 0; } else #endif { #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) MSG_PUTS_ATTR(_(" VREPLACE"), attr); else #endif if (State & REPLACE_FLAG) MSG_PUTS_ATTR(_(" REPLACE"), attr); else if (State & INSERT) { #ifdef FEAT_RIGHTLEFT if (p_ri) MSG_PUTS_ATTR(_(" REVERSE"), attr); #endif MSG_PUTS_ATTR(_(" INSERT"), attr); } else if (restart_edit == 'I') MSG_PUTS_ATTR(_(" (insert)"), attr); else if (restart_edit == 'R') MSG_PUTS_ATTR(_(" (replace)"), attr); else if (restart_edit == 'V') MSG_PUTS_ATTR(_(" (vreplace)"), attr); #ifdef FEAT_RIGHTLEFT if (p_hkmap) MSG_PUTS_ATTR(_(" Hebrew"), attr); # ifdef FEAT_FKMAP if (p_fkmap) MSG_PUTS_ATTR(farsi_text_5, attr); # endif #endif #ifdef FEAT_KEYMAP if (State & LANGMAP) { # ifdef FEAT_ARABIC if (curwin->w_p_arab) MSG_PUTS_ATTR(_(" Arabic"), attr); else # endif MSG_PUTS_ATTR(_(" (lang)"), attr); } #endif if ((State & INSERT) && p_paste) MSG_PUTS_ATTR(_(" (paste)"), attr); if (VIsual_active) { char *p; /* Don't concatenate separate words to avoid translation * problems. */ switch ((VIsual_select ? 4 : 0) + (VIsual_mode == Ctrl_V) * 2 + (VIsual_mode == 'V')) { case 0: p = N_(" VISUAL"); break; case 1: p = N_(" VISUAL LINE"); break; case 2: p = N_(" VISUAL BLOCK"); break; case 4: p = N_(" SELECT"); break; case 5: p = N_(" SELECT LINE"); break; default: p = N_(" SELECT BLOCK"); break; } MSG_PUTS_ATTR(_(p), attr); } MSG_PUTS_ATTR(" --", attr); } need_clear = TRUE; } if (Recording #ifdef FEAT_INS_EXPAND && edit_submode == NULL /* otherwise it gets too long */ #endif ) { MSG_PUTS_ATTR(_("recording"), attr); need_clear = TRUE; } mode_displayed = TRUE; if (need_clear || clear_cmdline) msg_clr_eos(); msg_didout = FALSE; /* overwrite this message */ length = msg_col; msg_col = 0; need_wait_return = nwr_save; /* never ask for hit-return for this */ } else if (clear_cmdline && msg_silent == 0) /* Clear the whole command line. Will reset "clear_cmdline". */ msg_clr_cmdline(); #ifdef FEAT_CMDL_INFO /* In Visual mode the size of the selected area must be redrawn. */ if (VIsual_active) clear_showcmd(); /* If the last window has no status line, the ruler is after the mode * message and must be redrawn */ if (redrawing() # ifdef FEAT_WINDOWS && lastwin->w_status_height == 0 # endif ) win_redr_ruler(lastwin, TRUE); #endif redraw_cmdline = FALSE; clear_cmdline = FALSE; return length; } /* * Position for a mode message. */ static void msg_pos_mode() { msg_col = 0; msg_row = Rows - 1; } /* * Delete mode message. Used when ESC is typed which is expected to end * Insert mode (but Insert mode didn't end yet!). * Caller should check "mode_displayed". */ void unshowmode(force) int force; { /* * Don't delete it right now, when not redrawing or inside a mapping. */ if (!redrawing() || (!force && char_avail() && !KeyTyped)) redraw_cmdline = TRUE; /* delete mode later */ else { msg_pos_mode(); if (Recording) MSG_PUTS_ATTR(_("recording"), hl_attr(HLF_CM)); msg_clr_eos(); } } #if defined(FEAT_WINDOWS) /* * Draw the tab pages line at the top of the Vim window. */ static void draw_tabline() { int tabcount = 0; tabpage_T *tp; int tabwidth; int col = 0; int scol = 0; int attr; win_T *wp; win_T *cwp; int wincount; int modified; int c; int len; int attr_sel = hl_attr(HLF_TPS); int attr_nosel = hl_attr(HLF_TP); int attr_fill = hl_attr(HLF_TPF); char_u *p; int room; int use_sep_chars = (t_colors < 8 #ifdef FEAT_GUI && !gui.in_use #endif ); redraw_tabline = FALSE; #ifdef FEAT_GUI_TABLINE /* Take care of a GUI tabline. */ if (gui_use_tabline()) { gui_update_tabline(); return; } #endif if (tabline_height() < 1) return; #if defined(FEAT_STL_OPT) /* Init TabPageIdxs[] to zero: Clicking outside of tabs has no effect. */ for (scol = 0; scol < Columns; ++scol) TabPageIdxs[scol] = 0; /* Use the 'tabline' option if it's set. */ if (*p_tal != NUL) { int save_called_emsg = called_emsg; /* Check for an error. If there is one we would loop in redrawing the * screen. Avoid that by making 'tabline' empty. */ called_emsg = FALSE; win_redr_custom(NULL, FALSE); if (called_emsg) set_string_option_direct((char_u *)"tabline", -1, (char_u *)"", OPT_FREE, SID_ERROR); called_emsg |= save_called_emsg; } else #endif { for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) ++tabcount; tabwidth = (Columns - 1 + tabcount / 2) / tabcount; if (tabwidth < 6) tabwidth = 6; attr = attr_nosel; tabcount = 0; scol = 0; for (tp = first_tabpage; tp != NULL && col < Columns - 4; tp = tp->tp_next) { scol = col; if (tp->tp_topframe == topframe) attr = attr_sel; if (use_sep_chars && col > 0) screen_putchar('|', 0, col++, attr); if (tp->tp_topframe != topframe) attr = attr_nosel; screen_putchar(' ', 0, col++, attr); if (tp == curtab) { cwp = curwin; wp = firstwin; } else { cwp = tp->tp_curwin; wp = tp->tp_firstwin; } modified = FALSE; for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount) if (bufIsChanged(wp->w_buffer)) modified = TRUE; if (modified || wincount > 1) { if (wincount > 1) { vim_snprintf((char *)NameBuff, MAXPATHL, "%d", wincount); len = (int)STRLEN(NameBuff); if (col + len >= Columns - 3) break; screen_puts_len(NameBuff, len, 0, col, #if defined(FEAT_SYN_HL) hl_combine_attr(attr, hl_attr(HLF_T)) #else attr #endif ); col += len; } if (modified) screen_puts_len((char_u *)"+", 1, 0, col++, attr); screen_putchar(' ', 0, col++, attr); } room = scol - col + tabwidth - 1; if (room > 0) { /* Get buffer name in NameBuff[] */ get_trans_bufname(cwp->w_buffer); shorten_dir(NameBuff); len = vim_strsize(NameBuff); p = NameBuff; #ifdef FEAT_MBYTE if (has_mbyte) while (len > room) { len -= ptr2cells(p); mb_ptr_adv(p); } else #endif if (len > room) { p += len - room; len = room; } if (len > Columns - col - 1) len = Columns - col - 1; screen_puts_len(p, (int)STRLEN(p), 0, col, attr); col += len; } screen_putchar(' ', 0, col++, attr); /* Store the tab page number in TabPageIdxs[], so that * jump_to_mouse() knows where each one is. */ ++tabcount; while (scol < col) TabPageIdxs[scol++] = tabcount; } if (use_sep_chars) c = '_'; else c = ' '; screen_fill(0, 1, col, (int)Columns, c, c, attr_fill); /* Put an "X" for closing the current tab if there are several. */ if (first_tabpage->tp_next != NULL) { screen_putchar('X', 0, (int)Columns - 1, attr_nosel); TabPageIdxs[Columns - 1] = -999; } } /* Reset the flag here again, in case evaluating 'tabline' causes it to be * set. */ redraw_tabline = FALSE; } /* * Get buffer name for "buf" into NameBuff[]. * Takes care of special buffer names and translates special characters. */ void get_trans_bufname(buf) buf_T *buf; { if (buf_spname(buf) != NULL) vim_strncpy(NameBuff, buf_spname(buf), MAXPATHL - 1); else home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, TRUE); trans_characters(NameBuff, MAXPATHL); } #endif #if defined(FEAT_WINDOWS) || defined(FEAT_WILDMENU) || defined(FEAT_STL_OPT) /* * Get the character to use in a status line. Get its attributes in "*attr". */ static int fillchar_status(attr, is_curwin) int *attr; int is_curwin; { int fill; if (is_curwin) { *attr = hl_attr(HLF_S); fill = fill_stl; } else { *attr = hl_attr(HLF_SNC); fill = fill_stlnc; } /* Use fill when there is highlighting, and highlighting of current * window differs, or the fillchars differ, or this is not the * current window */ if (*attr != 0 && ((hl_attr(HLF_S) != hl_attr(HLF_SNC) || !is_curwin || firstwin == lastwin) || (fill_stl != fill_stlnc))) return fill; if (is_curwin) return '^'; return '='; } #endif #ifdef FEAT_VERTSPLIT /* * Get the character to use in a separator between vertically split windows. * Get its attributes in "*attr". */ static int fillchar_vsep(attr) int *attr; { *attr = hl_attr(HLF_C); if (*attr == 0 && fill_vert == ' ') return '|'; else return fill_vert; } #endif /* * Return TRUE if redrawing should currently be done. */ int redrawing() { return (!RedrawingDisabled && !(p_lz && char_avail() && !KeyTyped && !do_redraw)); } /* * Return TRUE if printing messages should currently be done. */ int messaging() { return (!(p_lz && char_avail() && !KeyTyped)); } /* * Show current status info in ruler and various other places * If always is FALSE, only show ruler if position has changed. */ void showruler(always) int always; { if (!always && !redrawing()) return; #ifdef FEAT_INS_EXPAND if (pum_visible()) { # ifdef FEAT_WINDOWS /* Don't redraw right now, do it later. */ curwin->w_redr_status = TRUE; # endif return; } #endif #if defined(FEAT_STL_OPT) && defined(FEAT_WINDOWS) if ((*p_stl != NUL || *curwin->w_p_stl != NUL) && curwin->w_status_height) { redraw_custom_statusline(curwin); } else #endif #ifdef FEAT_CMDL_INFO win_redr_ruler(curwin, always); #endif #ifdef FEAT_TITLE if (need_maketitle # ifdef FEAT_STL_OPT || (p_icon && (stl_syntax & STL_IN_ICON)) || (p_title && (stl_syntax & STL_IN_TITLE)) # endif ) maketitle(); #endif #ifdef FEAT_WINDOWS /* Redraw the tab pages line if needed. */ if (redraw_tabline) draw_tabline(); #endif } #ifdef FEAT_CMDL_INFO static void win_redr_ruler(wp, always) win_T *wp; int always; { #define RULER_BUF_LEN 70 char_u buffer[RULER_BUF_LEN]; int row; int fillchar; int attr; int empty_line = FALSE; colnr_T virtcol; int i; size_t len; int o; #ifdef FEAT_VERTSPLIT int this_ru_col; int off = 0; int width = Columns; # define WITH_OFF(x) x # define WITH_WIDTH(x) x #else # define WITH_OFF(x) 0 # define WITH_WIDTH(x) Columns # define this_ru_col ru_col #endif /* If 'ruler' off or redrawing disabled, don't do anything */ if (!p_ru) return; /* * Check if cursor.lnum is valid, since win_redr_ruler() may be called * after deleting lines, before cursor.lnum is corrected. */ if (wp->w_cursor.lnum > wp->w_buffer->b_ml.ml_line_count) return; #ifdef FEAT_INS_EXPAND /* Don't draw the ruler while doing insert-completion, it might overwrite * the (long) mode message. */ # ifdef FEAT_WINDOWS if (wp == lastwin && lastwin->w_status_height == 0) # endif if (edit_submode != NULL) return; /* Don't draw the ruler when the popup menu is visible, it may overlap. */ if (pum_visible()) return; #endif #ifdef FEAT_STL_OPT if (*p_ruf) { int save_called_emsg = called_emsg; called_emsg = FALSE; win_redr_custom(wp, TRUE); if (called_emsg) set_string_option_direct((char_u *)"rulerformat", -1, (char_u *)"", OPT_FREE, SID_ERROR); called_emsg |= save_called_emsg; return; } #endif /* * Check if not in Insert mode and the line is empty (will show "0-1"). */ if (!(State & INSERT) && *ml_get_buf(wp->w_buffer, wp->w_cursor.lnum, FALSE) == NUL) empty_line = TRUE; /* * Only draw the ruler when something changed. */ validate_virtcol_win(wp); if ( redraw_cmdline || always || wp->w_cursor.lnum != wp->w_ru_cursor.lnum || wp->w_cursor.col != wp->w_ru_cursor.col || wp->w_virtcol != wp->w_ru_virtcol #ifdef FEAT_VIRTUALEDIT || wp->w_cursor.coladd != wp->w_ru_cursor.coladd #endif || wp->w_topline != wp->w_ru_topline || wp->w_buffer->b_ml.ml_line_count != wp->w_ru_line_count #ifdef FEAT_DIFF || wp->w_topfill != wp->w_ru_topfill #endif || empty_line != wp->w_ru_empty) { cursor_off(); #ifdef FEAT_WINDOWS if (wp->w_status_height) { row = W_WINROW(wp) + wp->w_height; fillchar = fillchar_status(&attr, wp == curwin); # ifdef FEAT_VERTSPLIT off = W_WINCOL(wp); width = W_WIDTH(wp); # endif } else #endif { row = Rows - 1; fillchar = ' '; attr = 0; #ifdef FEAT_VERTSPLIT width = Columns; off = 0; #endif } /* In list mode virtcol needs to be recomputed */ virtcol = wp->w_virtcol; if (wp->w_p_list && lcs_tab1 == NUL) { wp->w_p_list = FALSE; getvvcol(wp, &wp->w_cursor, NULL, &virtcol, NULL); wp->w_p_list = TRUE; } /* * Some sprintfs return the length, some return a pointer. * To avoid portability problems we use strlen() here. */ vim_snprintf((char *)buffer, RULER_BUF_LEN, "%ld,", (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) ? 0L : (long)(wp->w_cursor.lnum)); len = STRLEN(buffer); col_print(buffer + len, RULER_BUF_LEN - len, empty_line ? 0 : (int)wp->w_cursor.col + 1, (int)virtcol + 1); /* * Add a "50%" if there is room for it. * On the last line, don't print in the last column (scrolls the * screen up on some terminals). */ i = (int)STRLEN(buffer); get_rel_pos(wp, buffer + i + 1, RULER_BUF_LEN - i - 1); o = i + vim_strsize(buffer + i + 1); #ifdef FEAT_WINDOWS if (wp->w_status_height == 0) /* can't use last char of screen */ #endif ++o; #ifdef FEAT_VERTSPLIT this_ru_col = ru_col - (Columns - width); if (this_ru_col < 0) this_ru_col = 0; #endif /* Never use more than half the window/screen width, leave the other * half for the filename. */ if (this_ru_col < (WITH_WIDTH(width) + 1) / 2) this_ru_col = (WITH_WIDTH(width) + 1) / 2; if (this_ru_col + o < WITH_WIDTH(width)) { /* need at least 3 chars left for get_rel_pos() + NUL */ while (this_ru_col + o < WITH_WIDTH(width) && RULER_BUF_LEN > i + 4) { #ifdef FEAT_MBYTE if (has_mbyte) i += (*mb_char2bytes)(fillchar, buffer + i); else #endif buffer[i++] = fillchar; ++o; } get_rel_pos(wp, buffer + i, RULER_BUF_LEN - i); } /* Truncate at window boundary. */ #ifdef FEAT_MBYTE if (has_mbyte) { o = 0; for (i = 0; buffer[i] != NUL; i += (*mb_ptr2len)(buffer + i)) { o += (*mb_ptr2cells)(buffer + i); if (this_ru_col + o > WITH_WIDTH(width)) { buffer[i] = NUL; break; } } } else #endif if (this_ru_col + (int)STRLEN(buffer) > WITH_WIDTH(width)) buffer[WITH_WIDTH(width) - this_ru_col] = NUL; screen_puts(buffer, row, this_ru_col + WITH_OFF(off), attr); i = redraw_cmdline; screen_fill(row, row + 1, this_ru_col + WITH_OFF(off) + (int)STRLEN(buffer), (int)(WITH_OFF(off) + WITH_WIDTH(width)), fillchar, fillchar, attr); /* don't redraw the cmdline because of showing the ruler */ redraw_cmdline = i; wp->w_ru_cursor = wp->w_cursor; wp->w_ru_virtcol = wp->w_virtcol; wp->w_ru_empty = empty_line; wp->w_ru_topline = wp->w_topline; wp->w_ru_line_count = wp->w_buffer->b_ml.ml_line_count; #ifdef FEAT_DIFF wp->w_ru_topfill = wp->w_topfill; #endif } } #endif #if defined(FEAT_LINEBREAK) || defined(PROTO) /* * Return the width of the 'number' and 'relativenumber' column. * Caller may need to check if 'number' or 'relativenumber' is set. * Otherwise it depends on 'numberwidth' and the line count. */ int number_width(wp) win_T *wp; { int n; linenr_T lnum; if (wp->w_p_rnu && !wp->w_p_nu) /* cursor line shows "0" */ lnum = wp->w_height; else /* cursor line shows absolute line number */ lnum = wp->w_buffer->b_ml.ml_line_count; if (lnum == wp->w_nrwidth_line_count && wp->w_nuw_cached == wp->w_p_nuw) return wp->w_nrwidth_width; wp->w_nrwidth_line_count = lnum; n = 0; do { lnum /= 10; ++n; } while (lnum > 0); /* 'numberwidth' gives the minimal width plus one */ if (n < wp->w_p_nuw - 1) n = wp->w_p_nuw - 1; wp->w_nrwidth_width = n; wp->w_nuw_cached = wp->w_p_nuw; return n; } #endif /* * Return the current cursor column. This is the actual position on the * screen. First column is 0. */ int screen_screencol() { return screen_cur_col; } /* * Return the current cursor row. This is the actual position on the screen. * First row is 0. */ int screen_screenrow() { return screen_cur_row; }
""" Instalando e Utilizando Módulos Externos Utilizamos o gestor de pacotes Python Pip - Python Installer Package Podemos ver todos os pacotes externos oficiais em: https://pypi.org colorama -> É utilizado para permitir impressão de textos coloridos no terminal. Instalar um módulo: pip install nome_do_modulo #Instalando o pacote colorama pip install colorama # Utilizando o pacote instalado from colorama import init, Fore init() print(Fore.MAGENTA + 'Paulo Silva') print(Fore.RED + 'Paulo Silva') print(Fore.BLUE + 'Paulo Silva') """ from colorama import init, Fore import pydf pdf = pydf.generate_pdf('<h1>Programação em Python do básico ao avançado</h1>') with open('test_doc.pdf', 'wb') as f: f.write(pdf)
//index.js //获取应用实例 const app = getApp() Page({ data: { motto: 'Hello World', userInfo: {}, hasUserInfo: false, canIUse: wx.canIUse('button.open-type.getUserInfo'), }, //事件处理函数 bindViewTap: function () { wx.request({ url: 'https://www.xxxxx.com/test', }) wx.downloadFile({ url: 'https://www.xxxxx.com/sdtf', }) }, onError: function() { console.log(arguments,'arguments') }, onLoad: function () { console.log(getCurrentPages(),'getCurrentPages') console.error('xxxxxxx') const xxx = sdfs if (app.globalData.userInfo) { this.setData({ userInfo: app.globalData.userInfo, hasUserInfo: true, }) } else if (this.data.canIUse) { // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 app.userInfoReadyCallback = (res) => { this.setData({ userInfo: res.userInfo, hasUserInfo: true, }) } } else { // 在没有 open-type=getUserInfo 版本的兼容处理 wx.getUserInfo({ success: (res) => { app.globalData.userInfo = res.userInfo this.setData({ userInfo: res.userInfo, hasUserInfo: true, }) }, }) } }, getUserInfo: function (e) { console.log(e) app.globalData.userInfo = e.detail.userInfo this.setData({ userInfo: e.detail.userInfo, hasUserInfo: true, }) }, })
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # isort:skip_file import uuid from datetime import datetime import logging from math import nan from unittest.mock import Mock, patch import numpy as np import pandas as pd import tests.test_app import superset.viz as viz from superset import app from superset.constants import NULL_STRING from superset.exceptions import SpatialException from superset.utils.core import DTTM_ALIAS from .base_tests import SupersetTestCase from .utils import load_fixture logger = logging.getLogger(__name__) class BaseVizTestCase(SupersetTestCase): def test_constructor_exception_no_datasource(self): form_data = {} datasource = None with self.assertRaises(Exception): viz.BaseViz(datasource, form_data) def test_process_metrics(self): # test TableViz metrics in correct order form_data = { "url_params": {}, "row_limit": 500, "metric": "sum__SP_POP_TOTL", "entity": "country_code", "secondary_metric": "sum__SP_POP_TOTL", "granularity_sqla": "year", "page_length": 0, "all_columns": [], "viz_type": "table", "since": "2014-01-01", "until": "2014-01-02", "metrics": ["sum__SP_POP_TOTL", "SUM(SE_PRM_NENR_MA)", "SUM(SP_URB_TOTL)"], "country_fieldtype": "cca3", "percent_metrics": ["count"], "slice_id": 74, "time_grain_sqla": None, "order_by_cols": [], "groupby": ["country_name"], "compare_lag": "10", "limit": "25", "datasource": "2__table", "table_timestamp_format": "%Y-%m-%d %H:%M:%S", "markup_type": "markdown", "where": "", "compare_suffix": "o10Y", } datasource = Mock() datasource.type = "table" test_viz = viz.BaseViz(datasource, form_data) expect_metric_labels = [ u"sum__SP_POP_TOTL", u"SUM(SE_PRM_NENR_MA)", u"SUM(SP_URB_TOTL)", u"count", ] self.assertEqual(test_viz.metric_labels, expect_metric_labels) self.assertEqual(test_viz.all_metrics, expect_metric_labels) def test_get_df_returns_empty_df(self): form_data = {"dummy": 123} query_obj = {"granularity": "day"} datasource = self.get_datasource_mock() test_viz = viz.BaseViz(datasource, form_data) result = test_viz.get_df(query_obj) self.assertEqual(type(result), pd.DataFrame) self.assertTrue(result.empty) def test_get_df_handles_dttm_col(self): form_data = {"dummy": 123} query_obj = {"granularity": "day"} results = Mock() results.query = Mock() results.status = Mock() results.error_message = Mock() datasource = Mock() datasource.type = "table" datasource.query = Mock(return_value=results) mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col) test_viz = viz.BaseViz(datasource, form_data) test_viz.df_metrics_to_num = Mock() test_viz.get_fillna_for_columns = Mock(return_value=0) results.df = pd.DataFrame(data={DTTM_ALIAS: ["1960-01-01 05:00:00"]}) datasource.offset = 0 mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col) mock_dttm_col.python_date_format = "epoch_ms" result = test_viz.get_df(query_obj) import logging logger.info(result) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS) ) mock_dttm_col.python_date_format = None result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS) ) datasource.offset = 1 result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 6, 0)], name=DTTM_ALIAS) ) datasource.offset = 0 results.df = pd.DataFrame(data={DTTM_ALIAS: ["1960-01-01"]}) mock_dttm_col.python_date_format = "%Y-%m-%d" result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 0, 0)], name=DTTM_ALIAS) ) def test_cache_timeout(self): datasource = self.get_datasource_mock() datasource.cache_timeout = 0 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(0, test_viz.cache_timeout) datasource.cache_timeout = 156 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(156, test_viz.cache_timeout) datasource.cache_timeout = None datasource.database.cache_timeout = 0 self.assertEqual(0, test_viz.cache_timeout) datasource.database.cache_timeout = 1666 self.assertEqual(1666, test_viz.cache_timeout) datasource.database.cache_timeout = None test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(app.config["CACHE_DEFAULT_TIMEOUT"], test_viz.cache_timeout) class TableVizTestCase(SupersetTestCase): def test_get_data_applies_percentage(self): form_data = { "groupby": ["groupA", "groupB"], "metrics": [ { "expressionType": "SIMPLE", "aggregate": "SUM", "label": "SUM(value1)", "column": {"column_name": "value1", "type": "DOUBLE"}, }, "count", "avg__C", ], "percent_metrics": [ { "expressionType": "SIMPLE", "aggregate": "SUM", "label": "SUM(value1)", "column": {"column_name": "value1", "type": "DOUBLE"}, }, "avg__B", ], } datasource = self.get_datasource_mock() df = pd.DataFrame( { "SUM(value1)": [15, 20, 25, 40], "avg__B": [10, 20, 5, 15], "avg__C": [11, 22, 33, 44], "count": [6, 7, 8, 9], "groupA": ["A", "B", "C", "C"], "groupB": ["x", "x", "y", "z"], } ) test_viz = viz.TableViz(datasource, form_data) data = test_viz.get_data(df) # Check method correctly transforms data and computes percents self.assertEqual( [ "groupA", "groupB", "SUM(value1)", "count", "avg__C", "%SUM(value1)", "%avg__B", ], list(data["columns"]), ) expected = [ { "groupA": "A", "groupB": "x", "SUM(value1)": 15, "count": 6, "avg__C": 11, "%SUM(value1)": 0.15, "%avg__B": 0.2, }, { "groupA": "B", "groupB": "x", "SUM(value1)": 20, "count": 7, "avg__C": 22, "%SUM(value1)": 0.2, "%avg__B": 0.4, }, { "groupA": "C", "groupB": "y", "SUM(value1)": 25, "count": 8, "avg__C": 33, "%SUM(value1)": 0.25, "%avg__B": 0.1, }, { "groupA": "C", "groupB": "z", "SUM(value1)": 40, "count": 9, "avg__C": 44, "%SUM(value1)": 0.4, "%avg__B": 0.3, }, ] self.assertEqual(expected, data["records"]) def test_parse_adhoc_filters(self): form_data = { "metrics": [ { "expressionType": "SIMPLE", "aggregate": "SUM", "label": "SUM(value1)", "column": {"column_name": "value1", "type": "DOUBLE"}, } ], "adhoc_filters": [ { "expressionType": "SIMPLE", "clause": "WHERE", "subject": "value2", "operator": ">", "comparator": "100", }, { "expressionType": "SIMPLE", "clause": "HAVING", "subject": "SUM(value1)", "operator": "<", "comparator": "10", }, { "expressionType": "SQL", "clause": "HAVING", "sqlExpression": "SUM(value1) > 5", }, { "expressionType": "SQL", "clause": "WHERE", "sqlExpression": "value3 in ('North America')", }, ], } datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual( [{"col": "value2", "val": "100", "op": ">"}], query_obj["filter"] ) self.assertEqual( [{"op": "<", "val": "10", "col": "SUM(value1)"}], query_obj["extras"]["having_druid"], ) self.assertEqual("(value3 in ('North America'))", query_obj["extras"]["where"]) self.assertEqual("(SUM(value1) > 5)", query_obj["extras"]["having"]) def test_adhoc_filters_overwrite_legacy_filters(self): form_data = { "metrics": [ { "expressionType": "SIMPLE", "aggregate": "SUM", "label": "SUM(value1)", "column": {"column_name": "value1", "type": "DOUBLE"}, } ], "adhoc_filters": [ { "expressionType": "SIMPLE", "clause": "WHERE", "subject": "value2", "operator": ">", "comparator": "100", }, { "expressionType": "SQL", "clause": "WHERE", "sqlExpression": "value3 in ('North America')", }, ], "having": "SUM(value1) > 5", } datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual( [{"col": "value2", "val": "100", "op": ">"}], query_obj["filter"] ) self.assertEqual([], query_obj["extras"]["having_druid"]) self.assertEqual("(value3 in ('North America'))", query_obj["extras"]["where"]) self.assertEqual("", query_obj["extras"]["having"]) @patch("superset.viz.BaseViz.query_obj") def test_query_obj_merges_percent_metrics(self, super_query_obj): datasource = self.get_datasource_mock() form_data = { "percent_metrics": ["sum__A", "avg__B", "max__Y"], "metrics": ["sum__A", "count", "avg__C"], } test_viz = viz.TableViz(datasource, form_data) f_query_obj = {"metrics": form_data["metrics"]} super_query_obj.return_value = f_query_obj query_obj = test_viz.query_obj() self.assertEqual( ["sum__A", "count", "avg__C", "avg__B", "max__Y"], query_obj["metrics"] ) @patch("superset.viz.BaseViz.query_obj") def test_query_obj_throws_columns_and_metrics(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {"all_columns": ["A", "B"], "metrics": ["x", "y"]} super_query_obj.return_value = {} test_viz = viz.TableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() del form_data["metrics"] form_data["groupby"] = ["B", "C"] test_viz = viz.TableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() @patch("superset.viz.BaseViz.query_obj") def test_query_obj_merges_all_columns(self, super_query_obj): datasource = self.get_datasource_mock() form_data = { "all_columns": ["colA", "colB", "colC"], "order_by_cols": ['["colA", "colB"]', '["colC"]'], } super_query_obj.return_value = { "columns": ["colD", "colC"], "groupby": ["colA", "colB"], } test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual(form_data["all_columns"], query_obj["columns"]) self.assertEqual([], query_obj["groupby"]) self.assertEqual([["colA", "colB"], ["colC"]], query_obj["orderby"]) @patch("superset.viz.BaseViz.query_obj") def test_query_obj_uses_sortby(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {"timeseries_limit_metric": "__time__", "order_desc": False} super_query_obj.return_value = {"metrics": ["colA", "colB"]} test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual(["colA", "colB", "__time__"], query_obj["metrics"]) self.assertEqual([("__time__", True)], query_obj["orderby"]) def test_should_be_timeseries_raises_when_no_granularity(self): datasource = self.get_datasource_mock() form_data = {"include_time": True} test_viz = viz.TableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.should_be_timeseries() def test_adhoc_metric_with_sortby(self): metrics = [ { "expressionType": "SIMPLE", "aggregate": "SUM", "label": "sum_value", "column": {"column_name": "value1", "type": "DOUBLE"}, } ] form_data = { "metrics": metrics, "timeseries_limit_metric": { "expressionType": "SIMPLE", "aggregate": "SUM", "label": "SUM(value1)", "column": {"column_name": "value1", "type": "DOUBLE"}, }, "order_desc": False, } df = pd.DataFrame({"SUM(value1)": [15], "sum_value": [15]}) datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) data = test_viz.get_data(df) self.assertEqual(["sum_value"], data["columns"]) class DistBarVizTestCase(SupersetTestCase): def test_groupby_nulls(self): form_data = { "metrics": ["votes"], "adhoc_filters": [], "groupby": ["toppings"], "columns": [], } datasource = self.get_datasource_mock() df = pd.DataFrame( { "toppings": ["cheese", "pepperoni", "anchovies", None], "votes": [3, 5, 1, 2], } ) test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual("votes", data["key"]) expected_values = [ {"x": "pepperoni", "y": 5}, {"x": "cheese", "y": 3}, {"x": NULL_STRING, "y": 2}, {"x": "anchovies", "y": 1}, ] self.assertEqual(expected_values, data["values"]) def test_groupby_nans(self): form_data = { "metrics": ["count"], "adhoc_filters": [], "groupby": ["beds"], "columns": [], } datasource = self.get_datasource_mock() df = pd.DataFrame({"beds": [0, 1, nan, 2], "count": [30, 42, 3, 29]}) test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual("count", data["key"]) expected_values = [ {"x": "1.0", "y": 42}, {"x": "0.0", "y": 30}, {"x": "2.0", "y": 29}, {"x": NULL_STRING, "y": 3}, ] self.assertEqual(expected_values, data["values"]) def test_column_nulls(self): form_data = { "metrics": ["votes"], "adhoc_filters": [], "groupby": ["toppings"], "columns": ["role"], } datasource = self.get_datasource_mock() df = pd.DataFrame( { "toppings": ["cheese", "pepperoni", "cheese", "pepperoni"], "role": ["engineer", "engineer", None, None], "votes": [3, 5, 1, 2], } ) test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df) expected = [ { "key": NULL_STRING, "values": [{"x": "pepperoni", "y": 2}, {"x": "cheese", "y": 1}], }, { "key": "engineer", "values": [{"x": "pepperoni", "y": 5}, {"x": "cheese", "y": 3}], }, ] self.assertEqual(expected, data) class PairedTTestTestCase(SupersetTestCase): def test_get_data_transforms_dataframe(self): form_data = { "groupby": ["groupA", "groupB", "groupC"], "metrics": ["metric1", "metric2", "metric3"], } datasource = self.get_datasource_mock() # Test data raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100, 200, 300, 100, 200, 300] raw["groupA"] = ["a1", "a1", "a1", "b1", "b1", "b1", "c1", "c1", "c1"] raw["groupB"] = ["a2", "a2", "a2", "b2", "b2", "b2", "c2", "c2", "c2"] raw["groupC"] = ["a3", "a3", "a3", "b3", "b3", "b3", "c3", "c3", "c3"] raw["metric1"] = [1, 2, 3, 4, 5, 6, 7, 8, 9] raw["metric2"] = [10, 20, 30, 40, 50, 60, 70, 80, 90] raw["metric3"] = [100, 200, 300, 400, 500, 600, 700, 800, 900] df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types["paired_ttest"](datasource, form_data) data = pairedTTestViz.get_data(df) # Check method correctly transforms data expected = { "metric1": [ { "values": [ {"x": 100, "y": 1}, {"x": 200, "y": 2}, {"x": 300, "y": 3}, ], "group": ("a1", "a2", "a3"), }, { "values": [ {"x": 100, "y": 4}, {"x": 200, "y": 5}, {"x": 300, "y": 6}, ], "group": ("b1", "b2", "b3"), }, { "values": [ {"x": 100, "y": 7}, {"x": 200, "y": 8}, {"x": 300, "y": 9}, ], "group": ("c1", "c2", "c3"), }, ], "metric2": [ { "values": [ {"x": 100, "y": 10}, {"x": 200, "y": 20}, {"x": 300, "y": 30}, ], "group": ("a1", "a2", "a3"), }, { "values": [ {"x": 100, "y": 40}, {"x": 200, "y": 50}, {"x": 300, "y": 60}, ], "group": ("b1", "b2", "b3"), }, { "values": [ {"x": 100, "y": 70}, {"x": 200, "y": 80}, {"x": 300, "y": 90}, ], "group": ("c1", "c2", "c3"), }, ], "metric3": [ { "values": [ {"x": 100, "y": 100}, {"x": 200, "y": 200}, {"x": 300, "y": 300}, ], "group": ("a1", "a2", "a3"), }, { "values": [ {"x": 100, "y": 400}, {"x": 200, "y": 500}, {"x": 300, "y": 600}, ], "group": ("b1", "b2", "b3"), }, { "values": [ {"x": 100, "y": 700}, {"x": 200, "y": 800}, {"x": 300, "y": 900}, ], "group": ("c1", "c2", "c3"), }, ], } self.assertEqual(data, expected) def test_get_data_empty_null_keys(self): form_data = {"groupby": [], "metrics": ["", None]} datasource = self.get_datasource_mock() # Test data raw = {} raw[DTTM_ALIAS] = [100, 200, 300] raw[""] = [1, 2, 3] raw[None] = [10, 20, 30] df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types["paired_ttest"](datasource, form_data) data = pairedTTestViz.get_data(df) # Check method correctly transforms data expected = { "N/A": [ { "values": [ {"x": 100, "y": 1}, {"x": 200, "y": 2}, {"x": 300, "y": 3}, ], "group": "All", } ], "NULL": [ { "values": [ {"x": 100, "y": 10}, {"x": 200, "y": 20}, {"x": 300, "y": 30}, ], "group": "All", } ], } self.assertEqual(data, expected) class PartitionVizTestCase(SupersetTestCase): @patch("superset.viz.BaseViz.query_obj") def test_query_obj_time_series_option(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {} test_viz = viz.PartitionViz(datasource, form_data) super_query_obj.return_value = {} query_obj = test_viz.query_obj() self.assertFalse(query_obj["is_timeseries"]) test_viz.form_data["time_series_option"] = "agg_sum" query_obj = test_viz.query_obj() self.assertTrue(query_obj["is_timeseries"]) def test_levels_for_computes_levels(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100, 200, 300, 100, 200, 300] raw["groupA"] = ["a1", "a1", "a1", "b1", "b1", "b1", "c1", "c1", "c1"] raw["groupB"] = ["a2", "a2", "a2", "b2", "b2", "b2", "c2", "c2", "c2"] raw["groupC"] = ["a3", "a3", "a3", "b3", "b3", "b3", "c3", "c3", "c3"] raw["metric1"] = [1, 2, 3, 4, 5, 6, 7, 8, 9] raw["metric2"] = [10, 20, 30, 40, 50, 60, 70, 80, 90] raw["metric3"] = [100, 200, 300, 400, 500, 600, 700, 800, 900] df = pd.DataFrame(raw) groups = ["groupA", "groupB", "groupC"] time_op = "agg_sum" test_viz = viz.PartitionViz(Mock(), {}) levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected = {DTTM_ALIAS: 1800, "metric1": 45, "metric2": 450, "metric3": 4500} self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS: {"a1": 600, "b1": 600, "c1": 600}, "metric1": {"a1": 6, "b1": 15, "c1": 24}, "metric2": {"a1": 60, "b1": 150, "c1": 240}, "metric3": {"a1": 600, "b1": 1500, "c1": 2400}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(["groupA", "groupB"], levels[2].index.names) self.assertEqual(["groupA", "groupB", "groupC"], levels[3].index.names) time_op = "agg_mean" levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected = { DTTM_ALIAS: 200.0, "metric1": 5.0, "metric2": 50.0, "metric3": 500.0, } self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS: {"a1": 200, "c1": 200, "b1": 200}, "metric1": {"a1": 2, "b1": 5, "c1": 8}, "metric2": {"a1": 20, "b1": 50, "c1": 80}, "metric3": {"a1": 200, "b1": 500, "c1": 800}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(["groupA", "groupB"], levels[2].index.names) self.assertEqual(["groupA", "groupB", "groupC"], levels[3].index.names) def test_levels_for_diff_computes_difference(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100, 200, 300, 100, 200, 300] raw["groupA"] = ["a1", "a1", "a1", "b1", "b1", "b1", "c1", "c1", "c1"] raw["groupB"] = ["a2", "a2", "a2", "b2", "b2", "b2", "c2", "c2", "c2"] raw["groupC"] = ["a3", "a3", "a3", "b3", "b3", "b3", "c3", "c3", "c3"] raw["metric1"] = [1, 2, 3, 4, 5, 6, 7, 8, 9] raw["metric2"] = [10, 20, 30, 40, 50, 60, 70, 80, 90] raw["metric3"] = [100, 200, 300, 400, 500, 600, 700, 800, 900] df = pd.DataFrame(raw) groups = ["groupA", "groupB", "groupC"] test_viz = viz.PartitionViz(Mock(), {}) time_op = "point_diff" levels = test_viz.levels_for_diff(time_op, groups, df) expected = {"metric1": 6, "metric2": 60, "metric3": 600} self.assertEqual(expected, levels[0].to_dict()) expected = { "metric1": {"a1": 2, "b1": 2, "c1": 2}, "metric2": {"a1": 20, "b1": 20, "c1": 20}, "metric3": {"a1": 200, "b1": 200, "c1": 200}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(4, len(levels)) self.assertEqual(["groupA", "groupB", "groupC"], levels[3].index.names) def test_levels_for_time_calls_process_data_and_drops_cols(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100, 200, 300, 100, 200, 300] raw["groupA"] = ["a1", "a1", "a1", "b1", "b1", "b1", "c1", "c1", "c1"] raw["groupB"] = ["a2", "a2", "a2", "b2", "b2", "b2", "c2", "c2", "c2"] raw["groupC"] = ["a3", "a3", "a3", "b3", "b3", "b3", "c3", "c3", "c3"] raw["metric1"] = [1, 2, 3, 4, 5, 6, 7, 8, 9] raw["metric2"] = [10, 20, 30, 40, 50, 60, 70, 80, 90] raw["metric3"] = [100, 200, 300, 400, 500, 600, 700, 800, 900] df = pd.DataFrame(raw) groups = ["groupA", "groupB", "groupC"] test_viz = viz.PartitionViz(Mock(), {"groupby": groups}) def return_args(df_drop, aggregate): return df_drop test_viz.process_data = Mock(side_effect=return_args) levels = test_viz.levels_for_time(groups, df) self.assertEqual(4, len(levels)) cols = [DTTM_ALIAS, "metric1", "metric2", "metric3"] self.assertEqual(sorted(cols), sorted(levels[0].columns.tolist())) cols += ["groupA"] self.assertEqual(sorted(cols), sorted(levels[1].columns.tolist())) cols += ["groupB"] self.assertEqual(sorted(cols), sorted(levels[2].columns.tolist())) cols += ["groupC"] self.assertEqual(sorted(cols), sorted(levels[3].columns.tolist())) self.assertEqual(4, len(test_viz.process_data.mock_calls)) def test_nest_values_returns_hierarchy(self): raw = {} raw["groupA"] = ["a1", "a1", "a1", "b1", "b1", "b1", "c1", "c1", "c1"] raw["groupB"] = ["a2", "a2", "a2", "b2", "b2", "b2", "c2", "c2", "c2"] raw["groupC"] = ["a3", "a3", "a3", "b3", "b3", "b3", "c3", "c3", "c3"] raw["metric1"] = [1, 2, 3, 4, 5, 6, 7, 8, 9] raw["metric2"] = [10, 20, 30, 40, 50, 60, 70, 80, 90] raw["metric3"] = [100, 200, 300, 400, 500, 600, 700, 800, 900] df = pd.DataFrame(raw) test_viz = viz.PartitionViz(Mock(), {}) groups = ["groupA", "groupB", "groupC"] levels = test_viz.levels_for("agg_sum", groups, df) nest = test_viz.nest_values(levels) self.assertEqual(3, len(nest)) for i in range(0, 3): self.assertEqual("metric" + str(i + 1), nest[i]["name"]) self.assertEqual(3, len(nest[0]["children"])) self.assertEqual(1, len(nest[0]["children"][0]["children"])) self.assertEqual(1, len(nest[0]["children"][0]["children"][0]["children"])) def test_nest_procs_returns_hierarchy(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100, 200, 300, 100, 200, 300] raw["groupA"] = ["a1", "a1", "a1", "b1", "b1", "b1", "c1", "c1", "c1"] raw["groupB"] = ["a2", "a2", "a2", "b2", "b2", "b2", "c2", "c2", "c2"] raw["groupC"] = ["a3", "a3", "a3", "b3", "b3", "b3", "c3", "c3", "c3"] raw["metric1"] = [1, 2, 3, 4, 5, 6, 7, 8, 9] raw["metric2"] = [10, 20, 30, 40, 50, 60, 70, 80, 90] raw["metric3"] = [100, 200, 300, 400, 500, 600, 700, 800, 900] df = pd.DataFrame(raw) test_viz = viz.PartitionViz(Mock(), {}) groups = ["groupA", "groupB", "groupC"] metrics = ["metric1", "metric2", "metric3"] procs = {} for i in range(0, 4): df_drop = df.drop(groups[i:], 1) pivot = df_drop.pivot_table( index=DTTM_ALIAS, columns=groups[:i], values=metrics ) procs[i] = pivot nest = test_viz.nest_procs(procs) self.assertEqual(3, len(nest)) for i in range(0, 3): self.assertEqual("metric" + str(i + 1), nest[i]["name"]) self.assertEqual(None, nest[i].get("val")) self.assertEqual(3, len(nest[0]["children"])) self.assertEqual(3, len(nest[0]["children"][0]["children"])) self.assertEqual(1, len(nest[0]["children"][0]["children"][0]["children"])) self.assertEqual( 1, len(nest[0]["children"][0]["children"][0]["children"][0]["children"]) ) def test_get_data_calls_correct_method(self): test_viz = viz.PartitionViz(Mock(), {}) df = Mock() with self.assertRaises(ValueError): test_viz.get_data(df) test_viz.levels_for = Mock(return_value=1) test_viz.nest_values = Mock(return_value=1) test_viz.form_data["groupby"] = ["groups"] test_viz.form_data["time_series_option"] = "not_time" test_viz.get_data(df) self.assertEqual("agg_sum", test_viz.levels_for.mock_calls[0][1][0]) test_viz.form_data["time_series_option"] = "agg_sum" test_viz.get_data(df) self.assertEqual("agg_sum", test_viz.levels_for.mock_calls[1][1][0]) test_viz.form_data["time_series_option"] = "agg_mean" test_viz.get_data(df) self.assertEqual("agg_mean", test_viz.levels_for.mock_calls[2][1][0]) test_viz.form_data["time_series_option"] = "point_diff" test_viz.levels_for_diff = Mock(return_value=1) test_viz.get_data(df) self.assertEqual("point_diff", test_viz.levels_for_diff.mock_calls[0][1][0]) test_viz.form_data["time_series_option"] = "point_percent" test_viz.get_data(df) self.assertEqual("point_percent", test_viz.levels_for_diff.mock_calls[1][1][0]) test_viz.form_data["time_series_option"] = "point_factor" test_viz.get_data(df) self.assertEqual("point_factor", test_viz.levels_for_diff.mock_calls[2][1][0]) test_viz.levels_for_time = Mock(return_value=1) test_viz.nest_procs = Mock(return_value=1) test_viz.form_data["time_series_option"] = "adv_anal" test_viz.get_data(df) self.assertEqual(1, len(test_viz.levels_for_time.mock_calls)) self.assertEqual(1, len(test_viz.nest_procs.mock_calls)) test_viz.form_data["time_series_option"] = "time_series" test_viz.get_data(df) self.assertEqual("agg_sum", test_viz.levels_for.mock_calls[3][1][0]) self.assertEqual(7, len(test_viz.nest_values.mock_calls)) class RoseVisTestCase(SupersetTestCase): def test_rose_vis_get_data(self): raw = {} t1 = pd.Timestamp("2000") t2 = pd.Timestamp("2002") t3 = pd.Timestamp("2004") raw[DTTM_ALIAS] = [t1, t2, t3, t1, t2, t3, t1, t2, t3] raw["groupA"] = ["a1", "a1", "a1", "b1", "b1", "b1", "c1", "c1", "c1"] raw["groupB"] = ["a2", "a2", "a2", "b2", "b2", "b2", "c2", "c2", "c2"] raw["groupC"] = ["a3", "a3", "a3", "b3", "b3", "b3", "c3", "c3", "c3"] raw["metric1"] = [1, 2, 3, 4, 5, 6, 7, 8, 9] df = pd.DataFrame(raw) fd = {"metrics": ["metric1"], "groupby": ["groupA"]} test_viz = viz.RoseViz(Mock(), fd) test_viz.metrics = fd["metrics"] res = test_viz.get_data(df) expected = { 946684800000000000: [ {"time": t1, "value": 1, "key": ("a1",), "name": ("a1",)}, {"time": t1, "value": 4, "key": ("b1",), "name": ("b1",)}, {"time": t1, "value": 7, "key": ("c1",), "name": ("c1",)}, ], 1009843200000000000: [ {"time": t2, "value": 2, "key": ("a1",), "name": ("a1",)}, {"time": t2, "value": 5, "key": ("b1",), "name": ("b1",)}, {"time": t2, "value": 8, "key": ("c1",), "name": ("c1",)}, ], 1072915200000000000: [ {"time": t3, "value": 3, "key": ("a1",), "name": ("a1",)}, {"time": t3, "value": 6, "key": ("b1",), "name": ("b1",)}, {"time": t3, "value": 9, "key": ("c1",), "name": ("c1",)}, ], } self.assertEqual(expected, res) class TimeSeriesTableVizTestCase(SupersetTestCase): def test_get_data_metrics(self): form_data = {"metrics": ["sum__A", "count"], "groupby": []} datasource = self.get_datasource_mock() raw = {} t1 = pd.Timestamp("2000") t2 = pd.Timestamp("2002") raw[DTTM_ALIAS] = [t1, t2] raw["sum__A"] = [15, 20] raw["count"] = [6, 7] df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data) data = test_viz.get_data(df) # Check method correctly transforms data self.assertEqual(set(["count", "sum__A"]), set(data["columns"])) time_format = "%Y-%m-%d %H:%M:%S" expected = { t1.strftime(time_format): {"sum__A": 15, "count": 6}, t2.strftime(time_format): {"sum__A": 20, "count": 7}, } self.assertEqual(expected, data["records"]) def test_get_data_group_by(self): form_data = {"metrics": ["sum__A"], "groupby": ["groupby1"]} datasource = self.get_datasource_mock() raw = {} t1 = pd.Timestamp("2000") t2 = pd.Timestamp("2002") raw[DTTM_ALIAS] = [t1, t1, t1, t2, t2, t2] raw["sum__A"] = [15, 20, 25, 30, 35, 40] raw["groupby1"] = ["a1", "a2", "a3", "a1", "a2", "a3"] df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data) data = test_viz.get_data(df) # Check method correctly transforms data self.assertEqual(set(["a1", "a2", "a3"]), set(data["columns"])) time_format = "%Y-%m-%d %H:%M:%S" expected = { t1.strftime(time_format): {"a1": 15, "a2": 20, "a3": 25}, t2.strftime(time_format): {"a1": 30, "a2": 35, "a3": 40}, } self.assertEqual(expected, data["records"]) @patch("superset.viz.BaseViz.query_obj") def test_query_obj_throws_metrics_and_groupby(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {"groupby": ["a"]} super_query_obj.return_value = {} test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() form_data["metrics"] = ["x", "y"] test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() class BaseDeckGLVizTestCase(SupersetTestCase): def test_get_metrics(self): form_data = load_fixture("deck_path_form_data.json") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert result == [form_data.get("size")] form_data = {} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert result == [] def test_scatterviz_get_metrics(self): form_data = load_fixture("deck_path_form_data.json") datasource = self.get_datasource_mock() form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {"type": "metric", "value": "int"} result = test_viz_deckgl.get_metrics() assert result == ["int"] form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {} result = test_viz_deckgl.get_metrics() assert result == [] def test_get_js_columns(self): form_data = load_fixture("deck_path_form_data.json") datasource = self.get_datasource_mock() mock_d = {"a": "dummy1", "b": "dummy2", "c": "dummy3"} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_js_columns(mock_d) assert result == {"color": None} def test_get_properties(self): mock_d = {} form_data = load_fixture("deck_path_form_data.json") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(NotImplementedError) as context: test_viz_deckgl.get_properties(mock_d) self.assertTrue("" in str(context.exception)) def test_process_spatial_query_obj(self): form_data = load_fixture("deck_path_form_data.json") datasource = self.get_datasource_mock() mock_key = "spatial_key" mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(ValueError) as context: test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) self.assertTrue("Bad spatial key" in str(context.exception)) test_form_data = { "latlong_key": {"type": "latlong", "lonCol": "lon", "latCol": "lat"}, "delimited_key": {"type": "delimited", "lonlatCol": "lonlat"}, "geohash_key": {"type": "geohash", "geohashCol": "geo"}, } datasource = self.get_datasource_mock() expected_results = { "latlong_key": ["lon", "lat"], "delimited_key": ["lonlat"], "geohash_key": ["geo"], } for mock_key in ["latlong_key", "delimited_key", "geohash_key"]: mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data) test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) assert expected_results.get(mock_key) == mock_gb def test_geojson_query_obj(self): form_data = load_fixture("deck_geojson_form_data.json") datasource = self.get_datasource_mock() test_viz_deckgl = viz.DeckGeoJson(datasource, form_data) results = test_viz_deckgl.query_obj() assert results["metrics"] == [] assert results["groupby"] == [] assert results["columns"] == ["test_col"] def test_parse_coordinates(self): form_data = load_fixture("deck_path_form_data.json") datasource = self.get_datasource_mock() viz_instance = viz.BaseDeckGLViz(datasource, form_data) coord = viz_instance.parse_coordinates("1.23, 3.21") self.assertEqual(coord, (1.23, 3.21)) coord = viz_instance.parse_coordinates("1.23 3.21") self.assertEqual(coord, (1.23, 3.21)) self.assertEqual(viz_instance.parse_coordinates(None), None) self.assertEqual(viz_instance.parse_coordinates(""), None) def test_parse_coordinates_raises(self): form_data = load_fixture("deck_path_form_data.json") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates("NULL") with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates("fldkjsalkj,fdlaskjfjadlksj") @patch("superset.utils.core.uuid.uuid4") def test_filter_nulls(self, mock_uuid4): mock_uuid4.return_value = uuid.UUID("12345678123456781234567812345678") test_form_data = { "latlong_key": {"type": "latlong", "lonCol": "lon", "latCol": "lat"}, "delimited_key": {"type": "delimited", "lonlatCol": "lonlat"}, "geohash_key": {"type": "geohash", "geohashCol": "geo"}, } datasource = self.get_datasource_mock() expected_results = { "latlong_key": [ { "clause": "WHERE", "expressionType": "SIMPLE", "filterOptionName": "12345678-1234-5678-1234-567812345678", "comparator": "", "operator": "IS NOT NULL", "subject": "lat", "isExtra": False, }, { "clause": "WHERE", "expressionType": "SIMPLE", "filterOptionName": "12345678-1234-5678-1234-567812345678", "comparator": "", "operator": "IS NOT NULL", "subject": "lon", "isExtra": False, }, ], "delimited_key": [ { "clause": "WHERE", "expressionType": "SIMPLE", "filterOptionName": "12345678-1234-5678-1234-567812345678", "comparator": "", "operator": "IS NOT NULL", "subject": "lonlat", "isExtra": False, } ], "geohash_key": [ { "clause": "WHERE", "expressionType": "SIMPLE", "filterOptionName": "12345678-1234-5678-1234-567812345678", "comparator": "", "operator": "IS NOT NULL", "subject": "geo", "isExtra": False, } ], } for mock_key in ["latlong_key", "delimited_key", "geohash_key"]: test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data.copy()) test_viz_deckgl.spatial_control_keys = [mock_key] test_viz_deckgl.add_null_filters() adhoc_filters = test_viz_deckgl.form_data["adhoc_filters"] assert expected_results.get(mock_key) == adhoc_filters class TimeSeriesVizTestCase(SupersetTestCase): def test_timeseries_unicode_data(self): datasource = self.get_datasource_mock() form_data = {"groupby": ["name"], "metrics": ["sum__payout"]} raw = {} raw["name"] = [ "Real Madrid C.F.🇺🇸🇬🇧", "Real Madrid C.F.🇺🇸🇬🇧", "Real Madrid Basket", "Real Madrid Basket", ] raw["__timestamp"] = [ "2018-02-20T00:00:00", "2018-03-09T00:00:00", "2018-02-20T00:00:00", "2018-03-09T00:00:00", ] raw["sum__payout"] = [2, 2, 4, 4] df = pd.DataFrame(raw) test_viz = viz.NVD3TimeSeriesViz(datasource, form_data) viz_data = {} viz_data = test_viz.get_data(df) expected = [ { u"values": [ {u"y": 4, u"x": u"2018-02-20T00:00:00"}, {u"y": 4, u"x": u"2018-03-09T00:00:00"}, ], u"key": (u"Real Madrid Basket",), }, { u"values": [ {u"y": 2, u"x": u"2018-02-20T00:00:00"}, {u"y": 2, u"x": u"2018-03-09T00:00:00"}, ], u"key": (u"Real Madrid C.F.\U0001f1fa\U0001f1f8\U0001f1ec\U0001f1e7",), }, ] self.assertEqual(expected, viz_data) def test_process_data_resample(self): datasource = self.get_datasource_mock() df = pd.DataFrame( { "__timestamp": pd.to_datetime( ["2019-01-01", "2019-01-02", "2019-01-05", "2019-01-07"] ), "y": [1.0, 2.0, 5.0, 7.0], } ) self.assertEqual( viz.NVD3TimeSeriesViz( datasource, {"metrics": ["y"], "resample_method": "sum", "resample_rule": "1D"}, ) .process_data(df)["y"] .tolist(), [1.0, 2.0, 0.0, 0.0, 5.0, 0.0, 7.0], ) np.testing.assert_equal( viz.NVD3TimeSeriesViz( datasource, {"metrics": ["y"], "resample_method": "asfreq", "resample_rule": "1D"}, ) .process_data(df)["y"] .tolist(), [1.0, 2.0, np.nan, np.nan, 5.0, np.nan, 7.0], ) def test_apply_rolling(self): datasource = self.get_datasource_mock() df = pd.DataFrame( index=pd.to_datetime( ["2019-01-01", "2019-01-02", "2019-01-05", "2019-01-07"] ), data={"y": [1.0, 2.0, 3.0, 4.0]}, ) self.assertEqual( viz.BigNumberViz( datasource, { "metrics": ["y"], "rolling_type": "cumsum", "rolling_periods": 0, "min_periods": 0, }, ) .apply_rolling(df)["y"] .tolist(), [1.0, 3.0, 6.0, 10.0], ) self.assertEqual( viz.BigNumberViz( datasource, { "metrics": ["y"], "rolling_type": "sum", "rolling_periods": 2, "min_periods": 0, }, ) .apply_rolling(df)["y"] .tolist(), [1.0, 3.0, 5.0, 7.0], ) self.assertEqual( viz.BigNumberViz( datasource, { "metrics": ["y"], "rolling_type": "mean", "rolling_periods": 10, "min_periods": 0, }, ) .apply_rolling(df)["y"] .tolist(), [1.0, 1.5, 2.0, 2.5], ) class BigNumberVizTestCase(SupersetTestCase): def test_get_data(self): datasource = self.get_datasource_mock() df = pd.DataFrame( data={ DTTM_ALIAS: pd.to_datetime( ["2019-01-01", "2019-01-02", "2019-01-05", "2019-01-07"] ), "y": [1.0, 2.0, 3.0, 4.0], } ) data = viz.BigNumberViz(datasource, {"metrics": ["y"]}).get_data(df) self.assertEqual(data[2], {DTTM_ALIAS: pd.Timestamp("2019-01-05"), "y": 3}) def test_get_data_with_none(self): datasource = self.get_datasource_mock() df = pd.DataFrame( data={ DTTM_ALIAS: pd.to_datetime( ["2019-01-01", "2019-01-02", "2019-01-05", "2019-01-07"] ), "y": [1.0, 2.0, None, 4.0], } ) data = viz.BigNumberViz(datasource, {"metrics": ["y"]}).get_data(df) assert np.isnan(data[2]["y"])
from __future__ import print_function import os path = os.path.join(os.path.dirname(__file__), "UnicodeData.txt") f = open(path, "r") text = f.read() f.close() result = [] openValue = None for line in text.splitlines(): line = line.split(";") value, name, category = line[:3] if category in ("Ps", "Pi"): openValue = (value, name, category) elif category in ("Pe", "Pf") and openValue is not None: result.append("%s;%s;%s" % openValue) result.append("%s;%s;%s" % (value, name, category)) result.append("") openValue = None print("\n".join(result))
from data.indicator.GT1.preprocess import config
const getInvoiceLinesOfPaymentRequest = require('./get-invoice-lines-of-payment-request') module.exports = { getInvoiceLinesOfPaymentRequest }
#!/usr/bin/env python # # Run the test suite against all the Python versions we can find. # import sys import os from os.path import dirname, abspath, join import re TOP = dirname(dirname(abspath(__file__))) sys.path.insert(0, join(TOP, "tools")) import which def _python_ver_from_python(python): assert ' ' not in python o = os.popen('''%s -c "import sys; print(sys.version)"''' % python) ver_str = o.read().strip() ver_bits = re.split("\.|[^\d]", ver_str, 2)[:2] ver = tuple(map(int, ver_bits)) return ver def _gen_python_names(): yield "python" for ver in [(2,2), (2,3), (2,4), (2,5), (2,6), (2,7), (3,0), (3,1), (3,2), (3,3)]: yield "python%d.%d" % ver if sys.platform == "win32": yield "python%d%d" % ver def _gen_pythons(): python_from_ver = {} for name in _gen_python_names(): for python in which.whichall(name): ver = _python_ver_from_python(python) if ver not in python_from_ver: python_from_ver[ver] = python for ver, python in sorted(python_from_ver.items()): yield ver, python def testall(): for ver, python in _gen_pythons(): if ver < (2,3): # Don't support Python < 2.3. continue ver_str = "%s.%s" % ver print "-- test with Python %s (%s)" % (ver_str, python) assert ' ' not in python rv = os.system("MACOSX_DEPLOYMENT_TARGET= %s test.py -- -knownfailure" % python) if rv: sys.exit(os.WEXITSTATUS(rv)) testall()
#! /usr/bin/env python3 import string import random import os import os.path as path import sys MIN_NAME_LEN = 1 MAX_NAME_LEN = 8 MIN_CHILD_DIRS = 0 MAX_CHILD_DIRS = 3 MIN_CHILD_FILES = 0 MAX_CHILD_FILES = 5 MIN_DEPTH = 0 MAX_DEPTH = 3 FILE_SIZES = [0, 1, 2, 3, 1024, 512*1024, 2*1024*1024, 8*1024*1024] def random_file_name(): name_len = random.randint(MIN_NAME_LEN, MAX_NAME_LEN) return ''.join(random.choices(string.ascii_lowercase, k=name_len)) def fresh_dir_ent(dir_path): while True: p = path.join(dir_path, random_file_name()) if not path.exists(p): return p def random_dir(dir_path="./random_dir", depth=None): if depth is None: depth = random.randint(MIN_DEPTH, MAX_DEPTH) os.mkdir(dir_path) num_files = random.randint(MIN_CHILD_FILES, MAX_CHILD_FILES) num_dirs = random.randint(MIN_CHILD_DIRS, MAX_CHILD_DIRS) if depth != 0: for i in range(num_dirs): random_dir(dir_path=fresh_dir_ent(dir_path), depth=depth-1) for i in range(num_files): with open(fresh_dir_ent(dir_path), "wb") as f: fsize = random.choice(FILE_SIZES) f.write(os.urandom(fsize)) if __name__ == '__main__': random_dir(sys.argv[1])
# Generated by Django 3.1.4 on 2021-12-27 02:41 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reddit_api', '0002_auto_20211227_0241'), ] operations = [ migrations.AlterModelTable( name='redditposts', table='redditposts', ), ]
/** ****************************************************************************** * @file stm324xg_eval_sdio_sd.h * @author MCD Application Team * @version V1.0.0 * @date 30-September-2011 * @brief This file contains all the functions prototypes for the SD Card * stm324xg_eval_sdio_sd driver firmware library. ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2> ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __SDCARD_H #define __SDCARD_H #ifdef __cplusplus extern "C" { #endif #include "main.h" /** @defgroup STM324xG_EVAL_SDIO_SD_Exported_Types * @{ */ typedef enum { /** * @brief SDIO specific error defines */ SD_CMD_CRC_FAIL = (1), /*!< Command response received (but CRC check failed) */ SD_DATA_CRC_FAIL = (2), /*!< Data bock sent/received (CRC check Failed) */ SD_CMD_RSP_TIMEOUT = (3), /*!< Command response timeout */ SD_DATA_TIMEOUT = (4), /*!< Data time out */ SD_TX_UNDERRUN = (5), /*!< Transmit FIFO under-run */ SD_RX_OVERRUN = (6), /*!< Receive FIFO over-run */ SD_START_BIT_ERR = (7), /*!< Start bit not detected on all data signals in widE bus mode */ SD_CMD_OUT_OF_RANGE = (8), /*!< CMD's argument was out of range.*/ SD_ADDR_MISALIGNED = (9), /*!< Misaligned address */ SD_BLOCK_LEN_ERR = (10), /*!< Transferred block length is not allowed for the card or the number of transferred bytes does not match the block length */ SD_ERASE_SEQ_ERR = (11), /*!< An error in the sequence of erase command occurs.*/ SD_BAD_ERASE_PARAM = (12), /*!< An Invalid selection for erase groups */ SD_WRITE_PROT_VIOLATION = (13), /*!< Attempt to program a write protect block */ SD_LOCK_UNLOCK_FAILED = (14), /*!< Sequence or password error has been detected in unlock command or if there was an attempt to access a locked card */ SD_COM_CRC_FAILED = (15), /*!< CRC check of the previous command failed */ SD_ILLEGAL_CMD = (16), /*!< Command is not legal for the card state */ SD_CARD_ECC_FAILED = (17), /*!< Card internal ECC was applied but failed to correct the data */ SD_CC_ERROR = (18), /*!< Internal card controller error */ SD_GENERAL_UNKNOWN_ERROR = (19), /*!< General or Unknown error */ SD_STREAM_READ_UNDERRUN = (20), /*!< The card could not sustain data transfer in stream read operation. */ SD_STREAM_WRITE_OVERRUN = (21), /*!< The card could not sustain data programming in stream mode */ SD_CID_CSD_OVERWRITE = (22), /*!< CID/CSD overwrite error */ SD_WP_ERASE_SKIP = (23), /*!< only partial address space was erased */ SD_CARD_ECC_DISABLED = (24), /*!< Command has been executed without using internal ECC */ SD_ERASE_RESET = (25), /*!< Erase sequence was cleared before executing because an out of erase sequence command was received */ SD_AKE_SEQ_ERROR = (26), /*!< Error in sequence of authentication. */ SD_INVALID_VOLTRANGE = (27), SD_ADDR_OUT_OF_RANGE = (28), SD_SWITCH_ERROR = (29), SD_SDIO_DISABLED = (30), SD_SDIO_FUNCTION_BUSY = (31), SD_SDIO_FUNCTION_FAILED = (32), SD_SDIO_UNKNOWN_FUNCTION = (33), /** * @brief Standard error defines */ SD_INTERNAL_ERROR, SD_NOT_CONFIGURED, SD_REQUEST_PENDING, SD_REQUEST_NOT_APPLICABLE, SD_INVALID_PARAMETER, SD_UNSUPPORTED_FEATURE, SD_UNSUPPORTED_HW, SD_ERROR, SD_OK = 0 } SD_Error; /** * @brief SDIO Transfer state */ typedef enum { SD_TRANSFER_OK = 0, SD_TRANSFER_BUSY = 1, SD_TRANSFER_ERROR } SDTransferState; /** * @brief SD Card States */ typedef enum { SD_CARD_READY = ((uint32_t)0x00000001), SD_CARD_IDENTIFICATION = ((uint32_t)0x00000002), SD_CARD_STANDBY = ((uint32_t)0x00000003), SD_CARD_TRANSFER = ((uint32_t)0x00000004), SD_CARD_SENDING = ((uint32_t)0x00000005), SD_CARD_RECEIVING = ((uint32_t)0x00000006), SD_CARD_PROGRAMMING = ((uint32_t)0x00000007), SD_CARD_DISCONNECTED = ((uint32_t)0x00000008), SD_CARD_ERROR = ((uint32_t)0x000000FF) }SDCardState; /** * @brief Card Specific Data: CSD Register */ typedef struct { __IO uint8_t CSDStruct; /*!< CSD structure */ __IO uint8_t SysSpecVersion; /*!< System specification version */ __IO uint8_t Reserved1; /*!< Reserved */ __IO uint8_t TAAC; /*!< Data read access-time 1 */ __IO uint8_t NSAC; /*!< Data read access-time 2 in CLK cycles */ __IO uint8_t MaxBusClkFrec; /*!< Max. bus clock frequency */ __IO uint16_t CardComdClasses; /*!< Card command classes */ __IO uint8_t RdBlockLen; /*!< Max. read data block length */ __IO uint8_t PartBlockRead; /*!< Partial blocks for read allowed */ __IO uint8_t WrBlockMisalign; /*!< Write block misalignment */ __IO uint8_t RdBlockMisalign; /*!< Read block misalignment */ __IO uint8_t DSRImpl; /*!< DSR implemented */ __IO uint8_t Reserved2; /*!< Reserved */ __IO uint32_t DeviceSize; /*!< Device Size */ __IO uint8_t MaxRdCurrentVDDMin; /*!< Max. read current @ VDD min */ __IO uint8_t MaxRdCurrentVDDMax; /*!< Max. read current @ VDD max */ __IO uint8_t MaxWrCurrentVDDMin; /*!< Max. write current @ VDD min */ __IO uint8_t MaxWrCurrentVDDMax; /*!< Max. write current @ VDD max */ __IO uint8_t DeviceSizeMul; /*!< Device size multiplier */ __IO uint8_t EraseGrSize; /*!< Erase group size */ __IO uint8_t EraseGrMul; /*!< Erase group size multiplier */ __IO uint8_t WrProtectGrSize; /*!< Write protect group size */ __IO uint8_t WrProtectGrEnable; /*!< Write protect group enable */ __IO uint8_t ManDeflECC; /*!< Manufacturer default ECC */ __IO uint8_t WrSpeedFact; /*!< Write speed factor */ __IO uint8_t MaxWrBlockLen; /*!< Max. write data block length */ __IO uint8_t WriteBlockPaPartial; /*!< Partial blocks for write allowed */ __IO uint8_t Reserved3; /*!< Reserded */ __IO uint8_t ContentProtectAppli; /*!< Content protection application */ __IO uint8_t FileFormatGrouop; /*!< File format group */ __IO uint8_t CopyFlag; /*!< Copy flag (OTP) */ __IO uint8_t PermWrProtect; /*!< Permanent write protection */ __IO uint8_t TempWrProtect; /*!< Temporary write protection */ __IO uint8_t FileFormat; /*!< File Format */ __IO uint8_t ECC; /*!< ECC code */ __IO uint8_t CSD_CRC; /*!< CSD CRC */ __IO uint8_t Reserved4; /*!< always 1*/ } SD_CSD; /** * @brief Card Identification Data: CID Register */ typedef struct { __IO uint8_t ManufacturerID; /*!< ManufacturerID */ __IO uint16_t OEM_AppliID; /*!< OEM/Application ID */ __IO uint32_t ProdName1; /*!< Product Name part1 */ __IO uint8_t ProdName2; /*!< Product Name part2*/ __IO uint8_t ProdRev; /*!< Product Revision */ __IO uint32_t ProdSN; /*!< Product Serial Number */ __IO uint8_t Reserved1; /*!< Reserved1 */ __IO uint16_t ManufactDate; /*!< Manufacturing Date */ __IO uint8_t CID_CRC; /*!< CID CRC */ __IO uint8_t Reserved2; /*!< always 1 */ } SD_CID; /** * @brief SD Card Status */ typedef struct { __IO uint8_t DAT_BUS_WIDTH; __IO uint8_t SECURED_MODE; __IO uint16_t SD_CARD_TYPE; __IO uint32_t SIZE_OF_PROTECTED_AREA; __IO uint8_t SPEED_CLASS; __IO uint8_t PERFORMANCE_MOVE; __IO uint8_t AU_SIZE; __IO uint16_t ERASE_SIZE; __IO uint8_t ERASE_TIMEOUT; __IO uint8_t ERASE_OFFSET; } SD_CardStatus; /** * @brief SD Card information */ typedef struct { SD_CSD SD_csd; SD_CID SD_cid; uint32_t CardCapacity; /*!< Card Capacity */ uint32_t CardBlockSize; /*!< Card Block Size */ uint16_t RCA; uint8_t CardType; } SD_CardInfo; #define SDIO_FIFO_ADDRESS ((uint32_t)0x40012C80) /** * @brief SDIO Intialization Frequency (400KHz max) */ #define SDIO_INIT_CLK_DIV ((uint8_t)0x76) /** * @brief SDIO Data Transfer Frequency (25MHz max) */ #define SDIO_TRANSFER_CLK_DIV ((uint8_t)0x0) #define SD_SDIO_DMA DMA2 #define SD_SDIO_DMA_CLK RCC_AHB1Periph_DMA2 #define SD_SDIO_DMA_STREAM3 3 //#define SD_SDIO_DMA_STREAM6 6 #ifdef SD_SDIO_DMA_STREAM3 #define SD_SDIO_DMA_STREAM DMA2_Stream3 #define SD_SDIO_DMA_CHANNEL DMA_Channel_4 #define SD_SDIO_DMA_FLAG_FEIF DMA_FLAG_FEIF3 #define SD_SDIO_DMA_FLAG_DMEIF DMA_FLAG_DMEIF3 #define SD_SDIO_DMA_FLAG_TEIF DMA_FLAG_TEIF3 #define SD_SDIO_DMA_FLAG_HTIF DMA_FLAG_HTIF3 #define SD_SDIO_DMA_FLAG_TCIF DMA_FLAG_TCIF3 #define SD_SDIO_DMA_IRQn DMA2_Stream3_IRQn #define SD_SDIO_DMA_IRQHANDLER DMA2_Stream3_IRQHandler #elif defined SD_SDIO_DMA_STREAM6 #define SD_SDIO_DMA_STREAM DMA2_Stream6 #define SD_SDIO_DMA_CHANNEL DMA_Channel_4 #define SD_SDIO_DMA_FLAG_FEIF DMA_FLAG_FEIF6 #define SD_SDIO_DMA_FLAG_DMEIF DMA_FLAG_DMEIF6 #define SD_SDIO_DMA_FLAG_TEIF DMA_FLAG_TEIF6 #define SD_SDIO_DMA_FLAG_HTIF DMA_FLAG_HTIF6 #define SD_SDIO_DMA_FLAG_TCIF DMA_FLAG_TCIF6 #define SD_SDIO_DMA_IRQn DMA2_Stream6_IRQn #define SD_SDIO_DMA_IRQHANDLER DMA2_Stream6_IRQHandler #endif /* SD_SDIO_DMA_STREAM3 */ /** * @brief SDIO Commands Index */ #define SD_CMD_GO_IDLE_STATE ((uint8_t)0) #define SD_CMD_SEND_OP_COND ((uint8_t)1) #define SD_CMD_ALL_SEND_CID ((uint8_t)2) #define SD_CMD_SET_REL_ADDR ((uint8_t)3) /*!< SDIO_SEND_REL_ADDR for SD Card */ #define SD_CMD_SET_DSR ((uint8_t)4) #define SD_CMD_SDIO_SEN_OP_COND ((uint8_t)5) #define SD_CMD_HS_SWITCH ((uint8_t)6) #define SD_CMD_SEL_DESEL_CARD ((uint8_t)7) #define SD_CMD_HS_SEND_EXT_CSD ((uint8_t)8) #define SD_CMD_SEND_CSD ((uint8_t)9) #define SD_CMD_SEND_CID ((uint8_t)10) #define SD_CMD_READ_DAT_UNTIL_STOP ((uint8_t)11) /*!< SD Card doesn't support it */ #define SD_CMD_STOP_TRANSMISSION ((uint8_t)12) #define SD_CMD_SEND_STATUS ((uint8_t)13) #define SD_CMD_HS_BUSTEST_READ ((uint8_t)14) #define SD_CMD_GO_INACTIVE_STATE ((uint8_t)15) #define SD_CMD_SET_BLOCKLEN ((uint8_t)16) #define SD_CMD_READ_SINGLE_BLOCK ((uint8_t)17) #define SD_CMD_READ_MULT_BLOCK ((uint8_t)18) #define SD_CMD_HS_BUSTEST_WRITE ((uint8_t)19) #define SD_CMD_WRITE_DAT_UNTIL_STOP ((uint8_t)20) /*!< SD Card doesn't support it */ #define SD_CMD_SET_BLOCK_COUNT ((uint8_t)23) /*!< SD Card doesn't support it */ #define SD_CMD_WRITE_SINGLE_BLOCK ((uint8_t)24) #define SD_CMD_WRITE_MULT_BLOCK ((uint8_t)25) #define SD_CMD_PROG_CID ((uint8_t)26) /*!< reserved for manufacturers */ #define SD_CMD_PROG_CSD ((uint8_t)27) #define SD_CMD_SET_WRITE_PROT ((uint8_t)28) #define SD_CMD_CLR_WRITE_PROT ((uint8_t)29) #define SD_CMD_SEND_WRITE_PROT ((uint8_t)30) #define SD_CMD_SD_ERASE_GRP_START ((uint8_t)32) /*!< To set the address of the first write block to be erased. (For SD card only) */ #define SD_CMD_SD_ERASE_GRP_END ((uint8_t)33) /*!< To set the address of the last write block of the continuous range to be erased. (For SD card only) */ #define SD_CMD_ERASE_GRP_START ((uint8_t)35) /*!< To set the address of the first write block to be erased. (For MMC card only spec 3.31) */ #define SD_CMD_ERASE_GRP_END ((uint8_t)36) /*!< To set the address of the last write block of the continuous range to be erased. (For MMC card only spec 3.31) */ #define SD_CMD_ERASE ((uint8_t)38) #define SD_CMD_FAST_IO ((uint8_t)39) /*!< SD Card doesn't support it */ #define SD_CMD_GO_IRQ_STATE ((uint8_t)40) /*!< SD Card doesn't support it */ #define SD_CMD_LOCK_UNLOCK ((uint8_t)42) #define SD_CMD_APP_CMD ((uint8_t)55) #define SD_CMD_GEN_CMD ((uint8_t)56) #define SD_CMD_NO_CMD ((uint8_t)64) /** * @brief Following commands are SD Card Specific commands. * SDIO_APP_CMD should be sent before sending these commands. */ #define SD_CMD_APP_SD_SET_BUSWIDTH ((uint8_t)6) /*!< For SD Card only */ #define SD_CMD_SD_APP_STAUS ((uint8_t)13) /*!< For SD Card only */ #define SD_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS ((uint8_t)22) /*!< For SD Card only */ #define SD_CMD_SD_APP_OP_COND ((uint8_t)41) /*!< For SD Card only */ #define SD_CMD_SD_APP_SET_CLR_CARD_DETECT ((uint8_t)42) /*!< For SD Card only */ #define SD_CMD_SD_APP_SEND_SCR ((uint8_t)51) /*!< For SD Card only */ #define SD_CMD_SDIO_RW_DIRECT ((uint8_t)52) /*!< For SD I/O Card only */ #define SD_CMD_SDIO_RW_EXTENDED ((uint8_t)53) /*!< For SD I/O Card only */ /** * @brief Following commands are SD Card Specific security commands. * SDIO_APP_CMD should be sent before sending these commands. */ #define SD_CMD_SD_APP_GET_MKB ((uint8_t)43) /*!< For SD Card only */ #define SD_CMD_SD_APP_GET_MID ((uint8_t)44) /*!< For SD Card only */ #define SD_CMD_SD_APP_SET_CER_RN1 ((uint8_t)45) /*!< For SD Card only */ #define SD_CMD_SD_APP_GET_CER_RN2 ((uint8_t)46) /*!< For SD Card only */ #define SD_CMD_SD_APP_SET_CER_RES2 ((uint8_t)47) /*!< For SD Card only */ #define SD_CMD_SD_APP_GET_CER_RES1 ((uint8_t)48) /*!< For SD Card only */ #define SD_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK ((uint8_t)18) /*!< For SD Card only */ #define SD_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK ((uint8_t)25) /*!< For SD Card only */ #define SD_CMD_SD_APP_SECURE_ERASE ((uint8_t)38) /*!< For SD Card only */ #define SD_CMD_SD_APP_CHANGE_SECURE_AREA ((uint8_t)49) /*!< For SD Card only */ #define SD_CMD_SD_APP_SECURE_WRITE_MKB ((uint8_t)48) /*!< For SD Card only */ /* Uncomment the following line to select the SDIO Data transfer mode */ #if !defined (SD_DMA_MODE) && !defined (SD_POLLING_MODE) /*#define SD_DMA_MODE ((uint32_t)0x00000000)*/ #define SD_POLLING_MODE ((uint32_t)0x00000002) #endif /** * @brief SD detection on its memory slot */ #define SD_PRESENT ((uint8_t)0x01) #define SD_NOT_PRESENT ((uint8_t)0x00) /** * @brief Supported SD Memory Cards */ #define SDIO_STD_CAPACITY_SD_CARD_V1_1 ((uint32_t)0x00000000) #define SDIO_STD_CAPACITY_SD_CARD_V2_0 ((uint32_t)0x00000001) #define SDIO_HIGH_CAPACITY_SD_CARD ((uint32_t)0x00000002) #define SDIO_MULTIMEDIA_CARD ((uint32_t)0x00000003) #define SDIO_SECURE_DIGITAL_IO_CARD ((uint32_t)0x00000004) #define SDIO_HIGH_SPEED_MULTIMEDIA_CARD ((uint32_t)0x00000005) #define SDIO_SECURE_DIGITAL_IO_COMBO_CARD ((uint32_t)0x00000006) #define SDIO_HIGH_CAPACITY_MMC_CARD ((uint32_t)0x00000007) /** * @} */ /** @defgroup STM324xG_EVAL_SDIO_SD_Exported_Macros * @{ */ /** * @} */ extern SD_CardInfo SDCardInfo; /** @defgroup STM324xG_EVAL_SDIO_SD_Exported_Functions * @{ */ void SD_DeInit(void); SD_Error SD_Init(void); SDTransferState SD_GetStatus(void); SDCardState SD_GetState(void); uint8_t SD_Detect(void); SD_Error SD_PowerON(void); SD_Error SD_PowerOFF(void); SD_Error SD_InitializeCards(void); SD_Error SD_GetCardInfo(SD_CardInfo *cardinfo); SD_Error SD_GetCardStatus(SD_CardStatus *cardstatus); SD_Error SD_EnableWideBusOperation(uint32_t WideMode); SD_Error SD_SelectDeselect(uint32_t addr); SD_Error SD_ReadBlock(uint8_t *readbuff, uint32_t ReadAddr, uint16_t BlockSize); SD_Error SD_ReadMultiBlocks(uint8_t *readbuff, uint32_t ReadAddr, uint16_t BlockSize, uint32_t NumberOfBlocks); SD_Error SD_WriteBlock(uint8_t *writebuff, uint32_t WriteAddr, uint16_t BlockSize); SD_Error SD_WriteMultiBlocks(uint8_t *writebuff, uint32_t WriteAddr, uint16_t BlockSize, uint32_t NumberOfBlocks); SDTransferState SD_GetTransferState(void); SD_Error SD_StopTransfer(void); SD_Error SD_Erase(uint32_t startaddr, uint32_t endaddr); SD_Error SD_SendStatus(uint32_t *pcardstatus); SD_Error SD_SendSDStatus(uint32_t *psdstatus); SD_Error SD_ProcessIRQSrc(void); void SD_ProcessDMAIRQ(void); SD_Error SD_WaitReadOperation(void); SD_Error SD_WaitWriteOperation(void); uint32_t SD_GetCapacity(void); #ifdef __cplusplus } #endif #endif /* __STM324xG_EVAL_SDIO_SD_H */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/CorePDF.framework/CorePDF */ #import <CorePDF/CPGraphicRegion.h> #import <CorePDF/CorePDF-Structs.h> @interface CPShapeRegion : CPGraphicRegion { } - (BOOL)isShapeRegion; // 0xbac9 - (void)accept:(id)accept; // 0xbacd @end
import re import sys import math import collections def tokeniser(_str, stopwords=["and", "for", "if", "the", "then", "be", "is", "are", "will", "in", "it", "to", "that"]): """ Given an input string and list of stopwords, returns a dictionary of frequency occurrences for terms in the given input string. From https://gist.github.com/mrorii/961963 """ tokens = collections.defaultdict(lambda: 0.0) for m in re.finditer(r"(\w+)", _str, re.UNICODE): m = m.group(1).lower() if len(m) < 2: continue if m in stopwords: continue tokens[m] += 1 return tokens def kl_divergence( _s, _t, stopwords=["and", "for", "if", "the", "then", "be", "is", "are", "will", "in", "it", "to", "that"] ): """ An implementation of Kullback-Leibler divergence for comparing two strings (documents). From https://gist.github.com/mrorii/961963 """ _s = tokeniser(_s) _t = tokeniser(_t) if len(_s) == 0: return 1e33 if len(_t) == 0: return 1e33 ssum = 0.0 + sum(_s.values()) # slen = len(_s) tsum = 0.0 + sum(_t.values()) # tlen = len(_t) vocabdiff = set(_s.keys()).difference(set(_t.keys())) lenvocabdiff = len(vocabdiff) """ epsilon """ epsilon = min(min(_s.values()) / ssum, min(_t.values()) / tsum) * 0.001 """ gamma """ gamma = 1 - lenvocabdiff * epsilon # print "_s: %s" % _s # print "_t: %s" % _t """ Check if distribution probabilities sum to 1""" sc = sum([v / ssum for v in _s.itervalues()]) st = sum([v / tsum for v in _t.itervalues()]) if sc < 9e-6: print("Sum P: %e, Sum Q: %e" % (sc, st)) print("*** ERROR: sc does not sum up to 1. Bailing out ..") sys.exit(2) if st < 9e-6: print("Sum P: %e, Sum Q: %e" % (sc, st)) print("*** ERROR: st does not sum up to 1. Bailing out ..") sys.exit(2) div = 0.0 for t, v in _s.items(): pts = v / ssum ptt = epsilon if t in _t: ptt = gamma * (_t[t] / tsum) ckl = (pts - ptt) * math.log(pts / ptt) div += ckl return div
#include <TargetConditionals.h> #if TARGET_OS_SIMULATOR #if 0 #elif defined(__x86_64__) && __x86_64__ // Generated by Apple Swift version 5.0.1 (swiftlang-1001.0.82.4 clang-1001.0.46.5) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgcc-compat" #if !defined(__has_include) # define __has_include(x) 0 #endif #if !defined(__has_attribute) # define __has_attribute(x) 0 #endif #if !defined(__has_feature) # define __has_feature(x) 0 #endif #if !defined(__has_warning) # define __has_warning(x) 0 #endif #if __has_include(<swift/objc-prologue.h>) # include <swift/objc-prologue.h> #endif #pragma clang diagnostic ignored "-Wauto-import" #include <Foundation/Foundation.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #if !defined(SWIFT_TYPEDEFS) # define SWIFT_TYPEDEFS 1 # if __has_include(<uchar.h>) # include <uchar.h> # elif !defined(__cplusplus) typedef uint_least16_t char16_t; typedef uint_least32_t char32_t; # endif typedef float swift_float2 __attribute__((__ext_vector_type__(2))); typedef float swift_float3 __attribute__((__ext_vector_type__(3))); typedef float swift_float4 __attribute__((__ext_vector_type__(4))); typedef double swift_double2 __attribute__((__ext_vector_type__(2))); typedef double swift_double3 __attribute__((__ext_vector_type__(3))); typedef double swift_double4 __attribute__((__ext_vector_type__(4))); typedef int swift_int2 __attribute__((__ext_vector_type__(2))); typedef int swift_int3 __attribute__((__ext_vector_type__(3))); typedef int swift_int4 __attribute__((__ext_vector_type__(4))); typedef unsigned int swift_uint2 __attribute__((__ext_vector_type__(2))); typedef unsigned int swift_uint3 __attribute__((__ext_vector_type__(3))); typedef unsigned int swift_uint4 __attribute__((__ext_vector_type__(4))); #endif #if !defined(SWIFT_PASTE) # define SWIFT_PASTE_HELPER(x, y) x##y # define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) #endif #if !defined(SWIFT_METATYPE) # define SWIFT_METATYPE(X) Class #endif #if !defined(SWIFT_CLASS_PROPERTY) # if __has_feature(objc_class_property) # define SWIFT_CLASS_PROPERTY(...) __VA_ARGS__ # else # define SWIFT_CLASS_PROPERTY(...) # endif #endif #if __has_attribute(objc_runtime_name) # define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) #else # define SWIFT_RUNTIME_NAME(X) #endif #if __has_attribute(swift_name) # define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X))) #else # define SWIFT_COMPILE_NAME(X) #endif #if __has_attribute(objc_method_family) # define SWIFT_METHOD_FAMILY(X) __attribute__((objc_method_family(X))) #else # define SWIFT_METHOD_FAMILY(X) #endif #if __has_attribute(noescape) # define SWIFT_NOESCAPE __attribute__((noescape)) #else # define SWIFT_NOESCAPE #endif #if __has_attribute(warn_unused_result) # define SWIFT_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #else # define SWIFT_WARN_UNUSED_RESULT #endif #if __has_attribute(noreturn) # define SWIFT_NORETURN __attribute__((noreturn)) #else # define SWIFT_NORETURN #endif #if !defined(SWIFT_CLASS_EXTRA) # define SWIFT_CLASS_EXTRA #endif #if !defined(SWIFT_PROTOCOL_EXTRA) # define SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_ENUM_EXTRA) # define SWIFT_ENUM_EXTRA #endif #if !defined(SWIFT_CLASS) # if __has_attribute(objc_subclassing_restricted) # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # else # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # endif #endif #if !defined(SWIFT_PROTOCOL) # define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA # define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_EXTENSION) # define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) #endif #if !defined(OBJC_DESIGNATED_INITIALIZER) # if __has_attribute(objc_designated_initializer) # define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) # else # define OBJC_DESIGNATED_INITIALIZER # endif #endif #if !defined(SWIFT_ENUM_ATTR) # if defined(__has_attribute) && __has_attribute(enum_extensibility) # define SWIFT_ENUM_ATTR(_extensibility) __attribute__((enum_extensibility(_extensibility))) # else # define SWIFT_ENUM_ATTR(_extensibility) # endif #endif #if !defined(SWIFT_ENUM) # define SWIFT_ENUM(_type, _name, _extensibility) enum _name : _type _name; enum SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type # if __has_feature(generalized_swift_name) # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type # else # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) SWIFT_ENUM(_type, _name, _extensibility) # endif #endif #if !defined(SWIFT_UNAVAILABLE) # define SWIFT_UNAVAILABLE __attribute__((unavailable)) #endif #if !defined(SWIFT_UNAVAILABLE_MSG) # define SWIFT_UNAVAILABLE_MSG(msg) __attribute__((unavailable(msg))) #endif #if !defined(SWIFT_AVAILABILITY) # define SWIFT_AVAILABILITY(plat, ...) __attribute__((availability(plat, __VA_ARGS__))) #endif #if !defined(SWIFT_DEPRECATED) # define SWIFT_DEPRECATED __attribute__((deprecated)) #endif #if !defined(SWIFT_DEPRECATED_MSG) # define SWIFT_DEPRECATED_MSG(...) __attribute__((deprecated(__VA_ARGS__))) #endif #if __has_feature(attribute_diagnose_if_objc) # define SWIFT_DEPRECATED_OBJC(Msg) __attribute__((diagnose_if(1, Msg, "warning"))) #else # define SWIFT_DEPRECATED_OBJC(Msg) SWIFT_DEPRECATED_MSG(Msg) #endif #if __has_feature(modules) #if __has_warning("-Watimport-in-framework-header") #pragma clang diagnostic ignored "-Watimport-in-framework-header" #endif @import ObjectiveC; @import UIKit; #endif #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" #pragma clang diagnostic ignored "-Wduplicate-method-arg" #if __has_warning("-Wpragma-clang-attribute") # pragma clang diagnostic ignored "-Wpragma-clang-attribute" #endif #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Wnullability" #if __has_attribute(external_source_symbol) # pragma push_macro("any") # undef any # pragma clang attribute push(__attribute__((external_source_symbol(language="Swift", defined_in="Razorpay",generated_declaration))), apply_to=any(function,enum,objc_interface,objc_category,objc_protocol)) # pragma pop_macro("any") #endif SWIFT_PROTOCOL("_TtP8Razorpay31ExternalWalletSelectionProtocol_") @protocol ExternalWalletSelectionProtocol - (void)onExternalWalletSelected:(NSString * _Nonnull)walletName withPaymentData:(NSDictionary * _Nullable)paymentData; @end @class WKWebView; @class WKNavigation; SWIFT_CLASS("_TtC8Razorpay6Otpelf") @interface Otpelf : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); + (void)initWithWebView:(WKWebView * _Nonnull)webView andMerchantKey:(NSString * _Nullable)merchantKey SWIFT_METHOD_FAMILY(none); + (Otpelf * _Nullable)getSharedInstance SWIFT_WARN_UNUSED_RESULT; - (void)setPaymentData:(NSDictionary * _Nonnull)data; - (BOOL)webViewWithDidFinish:(WKNavigation * _Null_unspecified)navigation error:(NSError * _Nullable * _Nullable)error; - (void)close; @end @class PluginPaymentModel; SWIFT_PROTOCOL("_TtP8Razorpay21PluginPaymentDelegate_") @protocol PluginPaymentDelegate - (BOOL)canProcessPaymentWithModel:(PluginPaymentModel * _Nonnull)model SWIFT_WARN_UNUSED_RESULT; - (NSString * _Nonnull)identifier SWIFT_WARN_UNUSED_RESULT; - (void)payWithModel:(PluginPaymentModel * _Nonnull)model; @end SWIFT_CLASS("_TtC8Razorpay18PluginPaymentModel") @interface PluginPaymentModel : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); @end @protocol RazorpayPaymentCompletionProtocol; @class UIViewController; @protocol RazorpayProtocol; @protocol RazorpayPaymentCompletionProtocolWithData; SWIFT_CLASS("_TtC8Razorpay8Razorpay") @interface Razorpay : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); + (void)initWithKey:(NSString * _Nonnull)key andDelegate:(id <RazorpayPaymentCompletionProtocol> _Nonnull)delegate forViewController:(UIViewController * _Nonnull)vc SWIFT_METHOD_FAMILY(none) SWIFT_UNAVAILABLE_MSG("This method is unavailable. Use initWithKey:andDelegate: instead. See https://docs.razorpay.com/docs/ios for more information."); + (Razorpay * _Nonnull)initWithKey:(NSString * _Nonnull)key andDelegate:(id <RazorpayProtocol> _Nonnull)delegate SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT; + (Razorpay * _Nonnull)initWithKey:(NSString * _Nonnull)key andDelegateWithData:(id <RazorpayPaymentCompletionProtocolWithData> _Nonnull)delegate SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT; - (void)setExternalWalletSelectionDelegate:(id <ExternalWalletSelectionProtocol> _Nonnull)walletDelegate; - (void)open:(NSDictionary * _Nonnull)options displayController:(UIViewController * _Nonnull)displayController; - (void)open:(NSDictionary * _Nonnull)options; - (void)open:(NSDictionary * _Nonnull)options displayController:(UIViewController * _Nonnull)displayController arrExternalPaymentEntities:(NSArray<id <PluginPaymentDelegate>> * _Nonnull)arrExternalPaymentEntities; - (void)open:(NSDictionary * _Nonnull)options arrExternalPaymentEntities:(NSArray<id <PluginPaymentDelegate>> * _Nonnull)arrExternalPaymentEntities; - (void)close; @end SWIFT_PROTOCOL("_TtP8Razorpay16RazorpayProtocol_") @protocol RazorpayProtocol @end SWIFT_PROTOCOL("_TtP8Razorpay33RazorpayPaymentCompletionProtocol_") @protocol RazorpayPaymentCompletionProtocol <RazorpayProtocol> - (void)onPaymentError:(int32_t)code description:(NSString * _Nonnull)str SWIFT_DEPRECATED_MSG("this function will accept a code of Type Int and not Int32 in future releases"); - (void)onPaymentSuccess:(NSString * _Nonnull)payment_id; @end SWIFT_PROTOCOL("_TtP8Razorpay41RazorpayPaymentCompletionProtocolWithData_") @protocol RazorpayPaymentCompletionProtocolWithData <RazorpayProtocol> - (void)onPaymentError:(int32_t)code description:(NSString * _Nonnull)str andData:(NSDictionary * _Nullable)response SWIFT_DEPRECATED_MSG("this function will accept a code of Type Int and not Int32 in future releases"); - (void)onPaymentSuccess:(NSString * _Nonnull)payment_id andData:(NSDictionary * _Nullable)response; @end SWIFT_PROTOCOL("_TtP8Razorpay22RazorpayResultProtocol_") @protocol RazorpayResultProtocol <RazorpayProtocol> - (void)onCompleteWithResponse:(NSDictionary * _Nonnull)response; @end #if __has_attribute(external_source_symbol) # pragma clang attribute pop #endif #pragma clang diagnostic pop #elif defined(__i386__) && __i386__ // Generated by Apple Swift version 5.0.1 (swiftlang-1001.0.82.4 clang-1001.0.46.5) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgcc-compat" #if !defined(__has_include) # define __has_include(x) 0 #endif #if !defined(__has_attribute) # define __has_attribute(x) 0 #endif #if !defined(__has_feature) # define __has_feature(x) 0 #endif #if !defined(__has_warning) # define __has_warning(x) 0 #endif #if __has_include(<swift/objc-prologue.h>) # include <swift/objc-prologue.h> #endif #pragma clang diagnostic ignored "-Wauto-import" #include <Foundation/Foundation.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #if !defined(SWIFT_TYPEDEFS) # define SWIFT_TYPEDEFS 1 # if __has_include(<uchar.h>) # include <uchar.h> # elif !defined(__cplusplus) typedef uint_least16_t char16_t; typedef uint_least32_t char32_t; # endif typedef float swift_float2 __attribute__((__ext_vector_type__(2))); typedef float swift_float3 __attribute__((__ext_vector_type__(3))); typedef float swift_float4 __attribute__((__ext_vector_type__(4))); typedef double swift_double2 __attribute__((__ext_vector_type__(2))); typedef double swift_double3 __attribute__((__ext_vector_type__(3))); typedef double swift_double4 __attribute__((__ext_vector_type__(4))); typedef int swift_int2 __attribute__((__ext_vector_type__(2))); typedef int swift_int3 __attribute__((__ext_vector_type__(3))); typedef int swift_int4 __attribute__((__ext_vector_type__(4))); typedef unsigned int swift_uint2 __attribute__((__ext_vector_type__(2))); typedef unsigned int swift_uint3 __attribute__((__ext_vector_type__(3))); typedef unsigned int swift_uint4 __attribute__((__ext_vector_type__(4))); #endif #if !defined(SWIFT_PASTE) # define SWIFT_PASTE_HELPER(x, y) x##y # define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) #endif #if !defined(SWIFT_METATYPE) # define SWIFT_METATYPE(X) Class #endif #if !defined(SWIFT_CLASS_PROPERTY) # if __has_feature(objc_class_property) # define SWIFT_CLASS_PROPERTY(...) __VA_ARGS__ # else # define SWIFT_CLASS_PROPERTY(...) # endif #endif #if __has_attribute(objc_runtime_name) # define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) #else # define SWIFT_RUNTIME_NAME(X) #endif #if __has_attribute(swift_name) # define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X))) #else # define SWIFT_COMPILE_NAME(X) #endif #if __has_attribute(objc_method_family) # define SWIFT_METHOD_FAMILY(X) __attribute__((objc_method_family(X))) #else # define SWIFT_METHOD_FAMILY(X) #endif #if __has_attribute(noescape) # define SWIFT_NOESCAPE __attribute__((noescape)) #else # define SWIFT_NOESCAPE #endif #if __has_attribute(warn_unused_result) # define SWIFT_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #else # define SWIFT_WARN_UNUSED_RESULT #endif #if __has_attribute(noreturn) # define SWIFT_NORETURN __attribute__((noreturn)) #else # define SWIFT_NORETURN #endif #if !defined(SWIFT_CLASS_EXTRA) # define SWIFT_CLASS_EXTRA #endif #if !defined(SWIFT_PROTOCOL_EXTRA) # define SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_ENUM_EXTRA) # define SWIFT_ENUM_EXTRA #endif #if !defined(SWIFT_CLASS) # if __has_attribute(objc_subclassing_restricted) # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # else # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # endif #endif #if !defined(SWIFT_PROTOCOL) # define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA # define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_EXTENSION) # define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) #endif #if !defined(OBJC_DESIGNATED_INITIALIZER) # if __has_attribute(objc_designated_initializer) # define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) # else # define OBJC_DESIGNATED_INITIALIZER # endif #endif #if !defined(SWIFT_ENUM_ATTR) # if defined(__has_attribute) && __has_attribute(enum_extensibility) # define SWIFT_ENUM_ATTR(_extensibility) __attribute__((enum_extensibility(_extensibility))) # else # define SWIFT_ENUM_ATTR(_extensibility) # endif #endif #if !defined(SWIFT_ENUM) # define SWIFT_ENUM(_type, _name, _extensibility) enum _name : _type _name; enum SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type # if __has_feature(generalized_swift_name) # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type # else # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) SWIFT_ENUM(_type, _name, _extensibility) # endif #endif #if !defined(SWIFT_UNAVAILABLE) # define SWIFT_UNAVAILABLE __attribute__((unavailable)) #endif #if !defined(SWIFT_UNAVAILABLE_MSG) # define SWIFT_UNAVAILABLE_MSG(msg) __attribute__((unavailable(msg))) #endif #if !defined(SWIFT_AVAILABILITY) # define SWIFT_AVAILABILITY(plat, ...) __attribute__((availability(plat, __VA_ARGS__))) #endif #if !defined(SWIFT_DEPRECATED) # define SWIFT_DEPRECATED __attribute__((deprecated)) #endif #if !defined(SWIFT_DEPRECATED_MSG) # define SWIFT_DEPRECATED_MSG(...) __attribute__((deprecated(__VA_ARGS__))) #endif #if __has_feature(attribute_diagnose_if_objc) # define SWIFT_DEPRECATED_OBJC(Msg) __attribute__((diagnose_if(1, Msg, "warning"))) #else # define SWIFT_DEPRECATED_OBJC(Msg) SWIFT_DEPRECATED_MSG(Msg) #endif #if __has_feature(modules) #if __has_warning("-Watimport-in-framework-header") #pragma clang diagnostic ignored "-Watimport-in-framework-header" #endif @import ObjectiveC; @import UIKit; #endif #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" #pragma clang diagnostic ignored "-Wduplicate-method-arg" #if __has_warning("-Wpragma-clang-attribute") # pragma clang diagnostic ignored "-Wpragma-clang-attribute" #endif #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Wnullability" #if __has_attribute(external_source_symbol) # pragma push_macro("any") # undef any # pragma clang attribute push(__attribute__((external_source_symbol(language="Swift", defined_in="Razorpay",generated_declaration))), apply_to=any(function,enum,objc_interface,objc_category,objc_protocol)) # pragma pop_macro("any") #endif SWIFT_PROTOCOL("_TtP8Razorpay31ExternalWalletSelectionProtocol_") @protocol ExternalWalletSelectionProtocol - (void)onExternalWalletSelected:(NSString * _Nonnull)walletName withPaymentData:(NSDictionary * _Nullable)paymentData; @end @class WKWebView; @class WKNavigation; SWIFT_CLASS("_TtC8Razorpay6Otpelf") @interface Otpelf : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); + (void)initWithWebView:(WKWebView * _Nonnull)webView andMerchantKey:(NSString * _Nullable)merchantKey SWIFT_METHOD_FAMILY(none); + (Otpelf * _Nullable)getSharedInstance SWIFT_WARN_UNUSED_RESULT; - (void)setPaymentData:(NSDictionary * _Nonnull)data; - (BOOL)webViewWithDidFinish:(WKNavigation * _Null_unspecified)navigation error:(NSError * _Nullable * _Nullable)error; - (void)close; @end @class PluginPaymentModel; SWIFT_PROTOCOL("_TtP8Razorpay21PluginPaymentDelegate_") @protocol PluginPaymentDelegate - (BOOL)canProcessPaymentWithModel:(PluginPaymentModel * _Nonnull)model SWIFT_WARN_UNUSED_RESULT; - (NSString * _Nonnull)identifier SWIFT_WARN_UNUSED_RESULT; - (void)payWithModel:(PluginPaymentModel * _Nonnull)model; @end SWIFT_CLASS("_TtC8Razorpay18PluginPaymentModel") @interface PluginPaymentModel : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); @end @protocol RazorpayPaymentCompletionProtocol; @class UIViewController; @protocol RazorpayProtocol; @protocol RazorpayPaymentCompletionProtocolWithData; SWIFT_CLASS("_TtC8Razorpay8Razorpay") @interface Razorpay : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); + (void)initWithKey:(NSString * _Nonnull)key andDelegate:(id <RazorpayPaymentCompletionProtocol> _Nonnull)delegate forViewController:(UIViewController * _Nonnull)vc SWIFT_METHOD_FAMILY(none) SWIFT_UNAVAILABLE_MSG("This method is unavailable. Use initWithKey:andDelegate: instead. See https://docs.razorpay.com/docs/ios for more information."); + (Razorpay * _Nonnull)initWithKey:(NSString * _Nonnull)key andDelegate:(id <RazorpayProtocol> _Nonnull)delegate SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT; + (Razorpay * _Nonnull)initWithKey:(NSString * _Nonnull)key andDelegateWithData:(id <RazorpayPaymentCompletionProtocolWithData> _Nonnull)delegate SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT; - (void)setExternalWalletSelectionDelegate:(id <ExternalWalletSelectionProtocol> _Nonnull)walletDelegate; - (void)open:(NSDictionary * _Nonnull)options displayController:(UIViewController * _Nonnull)displayController; - (void)open:(NSDictionary * _Nonnull)options; - (void)open:(NSDictionary * _Nonnull)options displayController:(UIViewController * _Nonnull)displayController arrExternalPaymentEntities:(NSArray<id <PluginPaymentDelegate>> * _Nonnull)arrExternalPaymentEntities; - (void)open:(NSDictionary * _Nonnull)options arrExternalPaymentEntities:(NSArray<id <PluginPaymentDelegate>> * _Nonnull)arrExternalPaymentEntities; - (void)close; @end SWIFT_PROTOCOL("_TtP8Razorpay16RazorpayProtocol_") @protocol RazorpayProtocol @end SWIFT_PROTOCOL("_TtP8Razorpay33RazorpayPaymentCompletionProtocol_") @protocol RazorpayPaymentCompletionProtocol <RazorpayProtocol> - (void)onPaymentError:(int32_t)code description:(NSString * _Nonnull)str SWIFT_DEPRECATED_MSG("this function will accept a code of Type Int and not Int32 in future releases"); - (void)onPaymentSuccess:(NSString * _Nonnull)payment_id; @end SWIFT_PROTOCOL("_TtP8Razorpay41RazorpayPaymentCompletionProtocolWithData_") @protocol RazorpayPaymentCompletionProtocolWithData <RazorpayProtocol> - (void)onPaymentError:(int32_t)code description:(NSString * _Nonnull)str andData:(NSDictionary * _Nullable)response SWIFT_DEPRECATED_MSG("this function will accept a code of Type Int and not Int32 in future releases"); - (void)onPaymentSuccess:(NSString * _Nonnull)payment_id andData:(NSDictionary * _Nullable)response; @end SWIFT_PROTOCOL("_TtP8Razorpay22RazorpayResultProtocol_") @protocol RazorpayResultProtocol <RazorpayProtocol> - (void)onCompleteWithResponse:(NSDictionary * _Nonnull)response; @end #if __has_attribute(external_source_symbol) # pragma clang attribute pop #endif #pragma clang diagnostic pop #endif #else //Start of iphoneos #if 0 #elif defined(__arm64__) && __arm64__ // Generated by Apple Swift version 5.0.1 (swiftlang-1001.0.82.4 clang-1001.0.46.5) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgcc-compat" #if !defined(__has_include) # define __has_include(x) 0 #endif #if !defined(__has_attribute) # define __has_attribute(x) 0 #endif #if !defined(__has_feature) # define __has_feature(x) 0 #endif #if !defined(__has_warning) # define __has_warning(x) 0 #endif #if __has_include(<swift/objc-prologue.h>) # include <swift/objc-prologue.h> #endif #pragma clang diagnostic ignored "-Wauto-import" #include <Foundation/Foundation.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #if !defined(SWIFT_TYPEDEFS) # define SWIFT_TYPEDEFS 1 # if __has_include(<uchar.h>) # include <uchar.h> # elif !defined(__cplusplus) typedef uint_least16_t char16_t; typedef uint_least32_t char32_t; # endif typedef float swift_float2 __attribute__((__ext_vector_type__(2))); typedef float swift_float3 __attribute__((__ext_vector_type__(3))); typedef float swift_float4 __attribute__((__ext_vector_type__(4))); typedef double swift_double2 __attribute__((__ext_vector_type__(2))); typedef double swift_double3 __attribute__((__ext_vector_type__(3))); typedef double swift_double4 __attribute__((__ext_vector_type__(4))); typedef int swift_int2 __attribute__((__ext_vector_type__(2))); typedef int swift_int3 __attribute__((__ext_vector_type__(3))); typedef int swift_int4 __attribute__((__ext_vector_type__(4))); typedef unsigned int swift_uint2 __attribute__((__ext_vector_type__(2))); typedef unsigned int swift_uint3 __attribute__((__ext_vector_type__(3))); typedef unsigned int swift_uint4 __attribute__((__ext_vector_type__(4))); #endif #if !defined(SWIFT_PASTE) # define SWIFT_PASTE_HELPER(x, y) x##y # define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) #endif #if !defined(SWIFT_METATYPE) # define SWIFT_METATYPE(X) Class #endif #if !defined(SWIFT_CLASS_PROPERTY) # if __has_feature(objc_class_property) # define SWIFT_CLASS_PROPERTY(...) __VA_ARGS__ # else # define SWIFT_CLASS_PROPERTY(...) # endif #endif #if __has_attribute(objc_runtime_name) # define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) #else # define SWIFT_RUNTIME_NAME(X) #endif #if __has_attribute(swift_name) # define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X))) #else # define SWIFT_COMPILE_NAME(X) #endif #if __has_attribute(objc_method_family) # define SWIFT_METHOD_FAMILY(X) __attribute__((objc_method_family(X))) #else # define SWIFT_METHOD_FAMILY(X) #endif #if __has_attribute(noescape) # define SWIFT_NOESCAPE __attribute__((noescape)) #else # define SWIFT_NOESCAPE #endif #if __has_attribute(warn_unused_result) # define SWIFT_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #else # define SWIFT_WARN_UNUSED_RESULT #endif #if __has_attribute(noreturn) # define SWIFT_NORETURN __attribute__((noreturn)) #else # define SWIFT_NORETURN #endif #if !defined(SWIFT_CLASS_EXTRA) # define SWIFT_CLASS_EXTRA #endif #if !defined(SWIFT_PROTOCOL_EXTRA) # define SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_ENUM_EXTRA) # define SWIFT_ENUM_EXTRA #endif #if !defined(SWIFT_CLASS) # if __has_attribute(objc_subclassing_restricted) # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # else # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # endif #endif #if !defined(SWIFT_PROTOCOL) # define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA # define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_EXTENSION) # define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) #endif #if !defined(OBJC_DESIGNATED_INITIALIZER) # if __has_attribute(objc_designated_initializer) # define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) # else # define OBJC_DESIGNATED_INITIALIZER # endif #endif #if !defined(SWIFT_ENUM_ATTR) # if defined(__has_attribute) && __has_attribute(enum_extensibility) # define SWIFT_ENUM_ATTR(_extensibility) __attribute__((enum_extensibility(_extensibility))) # else # define SWIFT_ENUM_ATTR(_extensibility) # endif #endif #if !defined(SWIFT_ENUM) # define SWIFT_ENUM(_type, _name, _extensibility) enum _name : _type _name; enum SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type # if __has_feature(generalized_swift_name) # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type # else # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) SWIFT_ENUM(_type, _name, _extensibility) # endif #endif #if !defined(SWIFT_UNAVAILABLE) # define SWIFT_UNAVAILABLE __attribute__((unavailable)) #endif #if !defined(SWIFT_UNAVAILABLE_MSG) # define SWIFT_UNAVAILABLE_MSG(msg) __attribute__((unavailable(msg))) #endif #if !defined(SWIFT_AVAILABILITY) # define SWIFT_AVAILABILITY(plat, ...) __attribute__((availability(plat, __VA_ARGS__))) #endif #if !defined(SWIFT_DEPRECATED) # define SWIFT_DEPRECATED __attribute__((deprecated)) #endif #if !defined(SWIFT_DEPRECATED_MSG) # define SWIFT_DEPRECATED_MSG(...) __attribute__((deprecated(__VA_ARGS__))) #endif #if __has_feature(attribute_diagnose_if_objc) # define SWIFT_DEPRECATED_OBJC(Msg) __attribute__((diagnose_if(1, Msg, "warning"))) #else # define SWIFT_DEPRECATED_OBJC(Msg) SWIFT_DEPRECATED_MSG(Msg) #endif #if __has_feature(modules) #if __has_warning("-Watimport-in-framework-header") #pragma clang diagnostic ignored "-Watimport-in-framework-header" #endif @import ObjectiveC; @import UIKit; #endif #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" #pragma clang diagnostic ignored "-Wduplicate-method-arg" #if __has_warning("-Wpragma-clang-attribute") # pragma clang diagnostic ignored "-Wpragma-clang-attribute" #endif #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Wnullability" #if __has_attribute(external_source_symbol) # pragma push_macro("any") # undef any # pragma clang attribute push(__attribute__((external_source_symbol(language="Swift", defined_in="Razorpay",generated_declaration))), apply_to=any(function,enum,objc_interface,objc_category,objc_protocol)) # pragma pop_macro("any") #endif SWIFT_PROTOCOL("_TtP8Razorpay31ExternalWalletSelectionProtocol_") @protocol ExternalWalletSelectionProtocol - (void)onExternalWalletSelected:(NSString * _Nonnull)walletName withPaymentData:(NSDictionary * _Nullable)paymentData; @end @class WKWebView; @class WKNavigation; SWIFT_CLASS("_TtC8Razorpay6Otpelf") @interface Otpelf : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); + (void)initWithWebView:(WKWebView * _Nonnull)webView andMerchantKey:(NSString * _Nullable)merchantKey SWIFT_METHOD_FAMILY(none); + (Otpelf * _Nullable)getSharedInstance SWIFT_WARN_UNUSED_RESULT; - (void)setPaymentData:(NSDictionary * _Nonnull)data; - (BOOL)webViewWithDidFinish:(WKNavigation * _Null_unspecified)navigation error:(NSError * _Nullable * _Nullable)error; - (void)close; @end @class PluginPaymentModel; SWIFT_PROTOCOL("_TtP8Razorpay21PluginPaymentDelegate_") @protocol PluginPaymentDelegate - (BOOL)canProcessPaymentWithModel:(PluginPaymentModel * _Nonnull)model SWIFT_WARN_UNUSED_RESULT; - (NSString * _Nonnull)identifier SWIFT_WARN_UNUSED_RESULT; - (void)payWithModel:(PluginPaymentModel * _Nonnull)model; @end SWIFT_CLASS("_TtC8Razorpay18PluginPaymentModel") @interface PluginPaymentModel : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); @end @protocol RazorpayPaymentCompletionProtocol; @class UIViewController; @protocol RazorpayProtocol; @protocol RazorpayPaymentCompletionProtocolWithData; SWIFT_CLASS("_TtC8Razorpay8Razorpay") @interface Razorpay : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); + (void)initWithKey:(NSString * _Nonnull)key andDelegate:(id <RazorpayPaymentCompletionProtocol> _Nonnull)delegate forViewController:(UIViewController * _Nonnull)vc SWIFT_METHOD_FAMILY(none) SWIFT_UNAVAILABLE_MSG("This method is unavailable. Use initWithKey:andDelegate: instead. See https://docs.razorpay.com/docs/ios for more information."); + (Razorpay * _Nonnull)initWithKey:(NSString * _Nonnull)key andDelegate:(id <RazorpayProtocol> _Nonnull)delegate SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT; + (Razorpay * _Nonnull)initWithKey:(NSString * _Nonnull)key andDelegateWithData:(id <RazorpayPaymentCompletionProtocolWithData> _Nonnull)delegate SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT; - (void)setExternalWalletSelectionDelegate:(id <ExternalWalletSelectionProtocol> _Nonnull)walletDelegate; - (void)open:(NSDictionary * _Nonnull)options displayController:(UIViewController * _Nonnull)displayController; - (void)open:(NSDictionary * _Nonnull)options; - (void)open:(NSDictionary * _Nonnull)options displayController:(UIViewController * _Nonnull)displayController arrExternalPaymentEntities:(NSArray<id <PluginPaymentDelegate>> * _Nonnull)arrExternalPaymentEntities; - (void)open:(NSDictionary * _Nonnull)options arrExternalPaymentEntities:(NSArray<id <PluginPaymentDelegate>> * _Nonnull)arrExternalPaymentEntities; - (void)close; @end SWIFT_PROTOCOL("_TtP8Razorpay16RazorpayProtocol_") @protocol RazorpayProtocol @end SWIFT_PROTOCOL("_TtP8Razorpay33RazorpayPaymentCompletionProtocol_") @protocol RazorpayPaymentCompletionProtocol <RazorpayProtocol> - (void)onPaymentError:(int32_t)code description:(NSString * _Nonnull)str SWIFT_DEPRECATED_MSG("this function will accept a code of Type Int and not Int32 in future releases"); - (void)onPaymentSuccess:(NSString * _Nonnull)payment_id; @end SWIFT_PROTOCOL("_TtP8Razorpay41RazorpayPaymentCompletionProtocolWithData_") @protocol RazorpayPaymentCompletionProtocolWithData <RazorpayProtocol> - (void)onPaymentError:(int32_t)code description:(NSString * _Nonnull)str andData:(NSDictionary * _Nullable)response SWIFT_DEPRECATED_MSG("this function will accept a code of Type Int and not Int32 in future releases"); - (void)onPaymentSuccess:(NSString * _Nonnull)payment_id andData:(NSDictionary * _Nullable)response; @end SWIFT_PROTOCOL("_TtP8Razorpay22RazorpayResultProtocol_") @protocol RazorpayResultProtocol <RazorpayProtocol> - (void)onCompleteWithResponse:(NSDictionary * _Nonnull)response; @end #if __has_attribute(external_source_symbol) # pragma clang attribute pop #endif #pragma clang diagnostic pop #elif defined(__ARM_ARCH_7A__) && __ARM_ARCH_7A__ // Generated by Apple Swift version 5.0.1 (swiftlang-1001.0.82.4 clang-1001.0.46.5) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgcc-compat" #if !defined(__has_include) # define __has_include(x) 0 #endif #if !defined(__has_attribute) # define __has_attribute(x) 0 #endif #if !defined(__has_feature) # define __has_feature(x) 0 #endif #if !defined(__has_warning) # define __has_warning(x) 0 #endif #if __has_include(<swift/objc-prologue.h>) # include <swift/objc-prologue.h> #endif #pragma clang diagnostic ignored "-Wauto-import" #include <Foundation/Foundation.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #if !defined(SWIFT_TYPEDEFS) # define SWIFT_TYPEDEFS 1 # if __has_include(<uchar.h>) # include <uchar.h> # elif !defined(__cplusplus) typedef uint_least16_t char16_t; typedef uint_least32_t char32_t; # endif typedef float swift_float2 __attribute__((__ext_vector_type__(2))); typedef float swift_float3 __attribute__((__ext_vector_type__(3))); typedef float swift_float4 __attribute__((__ext_vector_type__(4))); typedef double swift_double2 __attribute__((__ext_vector_type__(2))); typedef double swift_double3 __attribute__((__ext_vector_type__(3))); typedef double swift_double4 __attribute__((__ext_vector_type__(4))); typedef int swift_int2 __attribute__((__ext_vector_type__(2))); typedef int swift_int3 __attribute__((__ext_vector_type__(3))); typedef int swift_int4 __attribute__((__ext_vector_type__(4))); typedef unsigned int swift_uint2 __attribute__((__ext_vector_type__(2))); typedef unsigned int swift_uint3 __attribute__((__ext_vector_type__(3))); typedef unsigned int swift_uint4 __attribute__((__ext_vector_type__(4))); #endif #if !defined(SWIFT_PASTE) # define SWIFT_PASTE_HELPER(x, y) x##y # define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) #endif #if !defined(SWIFT_METATYPE) # define SWIFT_METATYPE(X) Class #endif #if !defined(SWIFT_CLASS_PROPERTY) # if __has_feature(objc_class_property) # define SWIFT_CLASS_PROPERTY(...) __VA_ARGS__ # else # define SWIFT_CLASS_PROPERTY(...) # endif #endif #if __has_attribute(objc_runtime_name) # define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) #else # define SWIFT_RUNTIME_NAME(X) #endif #if __has_attribute(swift_name) # define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X))) #else # define SWIFT_COMPILE_NAME(X) #endif #if __has_attribute(objc_method_family) # define SWIFT_METHOD_FAMILY(X) __attribute__((objc_method_family(X))) #else # define SWIFT_METHOD_FAMILY(X) #endif #if __has_attribute(noescape) # define SWIFT_NOESCAPE __attribute__((noescape)) #else # define SWIFT_NOESCAPE #endif #if __has_attribute(warn_unused_result) # define SWIFT_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #else # define SWIFT_WARN_UNUSED_RESULT #endif #if __has_attribute(noreturn) # define SWIFT_NORETURN __attribute__((noreturn)) #else # define SWIFT_NORETURN #endif #if !defined(SWIFT_CLASS_EXTRA) # define SWIFT_CLASS_EXTRA #endif #if !defined(SWIFT_PROTOCOL_EXTRA) # define SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_ENUM_EXTRA) # define SWIFT_ENUM_EXTRA #endif #if !defined(SWIFT_CLASS) # if __has_attribute(objc_subclassing_restricted) # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # else # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # endif #endif #if !defined(SWIFT_PROTOCOL) # define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA # define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_EXTENSION) # define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) #endif #if !defined(OBJC_DESIGNATED_INITIALIZER) # if __has_attribute(objc_designated_initializer) # define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) # else # define OBJC_DESIGNATED_INITIALIZER # endif #endif #if !defined(SWIFT_ENUM_ATTR) # if defined(__has_attribute) && __has_attribute(enum_extensibility) # define SWIFT_ENUM_ATTR(_extensibility) __attribute__((enum_extensibility(_extensibility))) # else # define SWIFT_ENUM_ATTR(_extensibility) # endif #endif #if !defined(SWIFT_ENUM) # define SWIFT_ENUM(_type, _name, _extensibility) enum _name : _type _name; enum SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type # if __has_feature(generalized_swift_name) # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type # else # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) SWIFT_ENUM(_type, _name, _extensibility) # endif #endif #if !defined(SWIFT_UNAVAILABLE) # define SWIFT_UNAVAILABLE __attribute__((unavailable)) #endif #if !defined(SWIFT_UNAVAILABLE_MSG) # define SWIFT_UNAVAILABLE_MSG(msg) __attribute__((unavailable(msg))) #endif #if !defined(SWIFT_AVAILABILITY) # define SWIFT_AVAILABILITY(plat, ...) __attribute__((availability(plat, __VA_ARGS__))) #endif #if !defined(SWIFT_DEPRECATED) # define SWIFT_DEPRECATED __attribute__((deprecated)) #endif #if !defined(SWIFT_DEPRECATED_MSG) # define SWIFT_DEPRECATED_MSG(...) __attribute__((deprecated(__VA_ARGS__))) #endif #if __has_feature(attribute_diagnose_if_objc) # define SWIFT_DEPRECATED_OBJC(Msg) __attribute__((diagnose_if(1, Msg, "warning"))) #else # define SWIFT_DEPRECATED_OBJC(Msg) SWIFT_DEPRECATED_MSG(Msg) #endif #if __has_feature(modules) #if __has_warning("-Watimport-in-framework-header") #pragma clang diagnostic ignored "-Watimport-in-framework-header" #endif @import ObjectiveC; @import UIKit; #endif #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" #pragma clang diagnostic ignored "-Wduplicate-method-arg" #if __has_warning("-Wpragma-clang-attribute") # pragma clang diagnostic ignored "-Wpragma-clang-attribute" #endif #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Wnullability" #if __has_attribute(external_source_symbol) # pragma push_macro("any") # undef any # pragma clang attribute push(__attribute__((external_source_symbol(language="Swift", defined_in="Razorpay",generated_declaration))), apply_to=any(function,enum,objc_interface,objc_category,objc_protocol)) # pragma pop_macro("any") #endif SWIFT_PROTOCOL("_TtP8Razorpay31ExternalWalletSelectionProtocol_") @protocol ExternalWalletSelectionProtocol - (void)onExternalWalletSelected:(NSString * _Nonnull)walletName withPaymentData:(NSDictionary * _Nullable)paymentData; @end @class WKWebView; @class WKNavigation; SWIFT_CLASS("_TtC8Razorpay6Otpelf") @interface Otpelf : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); + (void)initWithWebView:(WKWebView * _Nonnull)webView andMerchantKey:(NSString * _Nullable)merchantKey SWIFT_METHOD_FAMILY(none); + (Otpelf * _Nullable)getSharedInstance SWIFT_WARN_UNUSED_RESULT; - (void)setPaymentData:(NSDictionary * _Nonnull)data; - (BOOL)webViewWithDidFinish:(WKNavigation * _Null_unspecified)navigation error:(NSError * _Nullable * _Nullable)error; - (void)close; @end @class PluginPaymentModel; SWIFT_PROTOCOL("_TtP8Razorpay21PluginPaymentDelegate_") @protocol PluginPaymentDelegate - (BOOL)canProcessPaymentWithModel:(PluginPaymentModel * _Nonnull)model SWIFT_WARN_UNUSED_RESULT; - (NSString * _Nonnull)identifier SWIFT_WARN_UNUSED_RESULT; - (void)payWithModel:(PluginPaymentModel * _Nonnull)model; @end SWIFT_CLASS("_TtC8Razorpay18PluginPaymentModel") @interface PluginPaymentModel : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); @end @protocol RazorpayPaymentCompletionProtocol; @class UIViewController; @protocol RazorpayProtocol; @protocol RazorpayPaymentCompletionProtocolWithData; SWIFT_CLASS("_TtC8Razorpay8Razorpay") @interface Razorpay : NSObject - (nonnull instancetype)init SWIFT_UNAVAILABLE; + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable"); + (void)initWithKey:(NSString * _Nonnull)key andDelegate:(id <RazorpayPaymentCompletionProtocol> _Nonnull)delegate forViewController:(UIViewController * _Nonnull)vc SWIFT_METHOD_FAMILY(none) SWIFT_UNAVAILABLE_MSG("This method is unavailable. Use initWithKey:andDelegate: instead. See https://docs.razorpay.com/docs/ios for more information."); + (Razorpay * _Nonnull)initWithKey:(NSString * _Nonnull)key andDelegate:(id <RazorpayProtocol> _Nonnull)delegate SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT; + (Razorpay * _Nonnull)initWithKey:(NSString * _Nonnull)key andDelegateWithData:(id <RazorpayPaymentCompletionProtocolWithData> _Nonnull)delegate SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT; - (void)setExternalWalletSelectionDelegate:(id <ExternalWalletSelectionProtocol> _Nonnull)walletDelegate; - (void)open:(NSDictionary * _Nonnull)options displayController:(UIViewController * _Nonnull)displayController; - (void)open:(NSDictionary * _Nonnull)options; - (void)open:(NSDictionary * _Nonnull)options displayController:(UIViewController * _Nonnull)displayController arrExternalPaymentEntities:(NSArray<id <PluginPaymentDelegate>> * _Nonnull)arrExternalPaymentEntities; - (void)open:(NSDictionary * _Nonnull)options arrExternalPaymentEntities:(NSArray<id <PluginPaymentDelegate>> * _Nonnull)arrExternalPaymentEntities; - (void)close; @end SWIFT_PROTOCOL("_TtP8Razorpay16RazorpayProtocol_") @protocol RazorpayProtocol @end SWIFT_PROTOCOL("_TtP8Razorpay33RazorpayPaymentCompletionProtocol_") @protocol RazorpayPaymentCompletionProtocol <RazorpayProtocol> - (void)onPaymentError:(int32_t)code description:(NSString * _Nonnull)str SWIFT_DEPRECATED_MSG("this function will accept a code of Type Int and not Int32 in future releases"); - (void)onPaymentSuccess:(NSString * _Nonnull)payment_id; @end SWIFT_PROTOCOL("_TtP8Razorpay41RazorpayPaymentCompletionProtocolWithData_") @protocol RazorpayPaymentCompletionProtocolWithData <RazorpayProtocol> - (void)onPaymentError:(int32_t)code description:(NSString * _Nonnull)str andData:(NSDictionary * _Nullable)response SWIFT_DEPRECATED_MSG("this function will accept a code of Type Int and not Int32 in future releases"); - (void)onPaymentSuccess:(NSString * _Nonnull)payment_id andData:(NSDictionary * _Nullable)response; @end SWIFT_PROTOCOL("_TtP8Razorpay22RazorpayResultProtocol_") @protocol RazorpayResultProtocol <RazorpayProtocol> - (void)onCompleteWithResponse:(NSDictionary * _Nonnull)response; @end #if __has_attribute(external_source_symbol) # pragma clang attribute pop #endif #pragma clang diagnostic pop #endif #endif
from jsonrpc import ServiceProxy import sys import string # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:9332") else: access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:9332") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a HappyCoin address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n" elif cmd == "getaccountaddress": try: acct = raw_input("Enter an account name: ") print access.getaccountaddress(acct) except: print "\n---An error occurred---\n" elif cmd == "getaddressesbyaccount": try: acct = raw_input("Enter an account name: ") print access.getaddressesbyaccount(acct) except: print "\n---An error occurred---\n" elif cmd == "getbalance": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getbalance(acct, mc) except: print access.getbalance() except: print "\n---An error occurred---\n" elif cmd == "getblockbycount": try: height = raw_input("Height: ") print access.getblockbycount(height) except: print "\n---An error occurred---\n" elif cmd == "getblockcount": try: print access.getblockcount() except: print "\n---An error occurred---\n" elif cmd == "getblocknumber": try: print access.getblocknumber() except: print "\n---An error occurred---\n" elif cmd == "getconnectioncount": try: print access.getconnectioncount() except: print "\n---An error occurred---\n" elif cmd == "getdifficulty": try: print access.getdifficulty() except: print "\n---An error occurred---\n" elif cmd == "getgenerate": try: print access.getgenerate() except: print "\n---An error occurred---\n" elif cmd == "gethashespersec": try: print access.gethashespersec() except: print "\n---An error occurred---\n" elif cmd == "getinfo": try: print access.getinfo() except: print "\n---An error occurred---\n" elif cmd == "getnewaddress": try: acct = raw_input("Enter an account name: ") try: print access.getnewaddress(acct) except: print access.getnewaddress() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaccount": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaccount(acct, mc) except: print access.getreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaddress": try: addr = raw_input("Enter a HappyCoin address (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaddress(addr, mc) except: print access.getreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "gettransaction": try: txid = raw_input("Enter a transaction ID: ") print access.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: data = raw_input("Data (optional): ") try: print access.gettransaction(data) except: print access.gettransaction() except: print "\n---An error occurred---\n" elif cmd == "help": try: cmd = raw_input("Command (optional): ") try: print access.help(cmd) except: print access.help() except: print "\n---An error occurred---\n" elif cmd == "listaccounts": try: mc = raw_input("Minimum confirmations (optional): ") try: print access.listaccounts(mc) except: print access.listaccounts() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaccount": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaccount(mc, incemp) except: print access.listreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaddress": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaddress(mc, incemp) except: print access.listreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "listtransactions": try: acct = raw_input("Account (optional): ") count = raw_input("Number of transactions (optional): ") frm = raw_input("Skip (optional):") try: print access.listtransactions(acct, count, frm) except: print access.listtransactions() except: print "\n---An error occurred---\n" elif cmd == "move": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.move(frm, to, amt, mc, comment) except: print access.move(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendfrom": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendfrom(frm, to, amt, mc, comment, commentto) except: print access.sendfrom(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendmany": try: frm = raw_input("From: ") to = raw_input("To (in format address1:amount1,address2:amount2,...): ") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.sendmany(frm,to,mc,comment) except: print access.sendmany(frm,to) except: print "\n---An error occurred---\n" elif cmd == "sendtoaddress": try: to = raw_input("To (in format address1:amount1,address2:amount2,...): ") amt = raw_input("Amount:") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendtoaddress(to,amt,comment,commentto) except: print access.sendtoaddress(to,amt) except: print "\n---An error occurred---\n" elif cmd == "setaccount": try: addr = raw_input("Address: ") acct = raw_input("Account:") print access.setaccount(addr,acct) except: print "\n---An error occurred---\n" elif cmd == "setgenerate": try: gen= raw_input("Generate? (true/false): ") cpus = raw_input("Max processors/cores (-1 for unlimited, optional):") try: print access.setgenerate(gen, cpus) except: print access.setgenerate(gen) except: print "\n---An error occurred---\n" elif cmd == "settxfee": try: amt = raw_input("Amount:") print access.settxfee(amt) except: print "\n---An error occurred---\n" elif cmd == "stop": try: print access.stop() except: print "\n---An error occurred---\n" elif cmd == "validateaddress": try: addr = raw_input("Address: ") print access.validateaddress(addr) except: print "\n---An error occurred---\n" elif cmd == "walletpassphrase": try: pwd = raw_input("Enter wallet passphrase: ") access.walletpassphrase(pwd, 60) print "\n---Wallet unlocked---\n" except: print "\n---An error occurred---\n" elif cmd == "walletpassphrasechange": try: pwd = raw_input("Enter old wallet passphrase: ") pwd2 = raw_input("Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2) print print "\n---Passphrase changed---\n" except: print print "\n---An error occurred---\n" print else: print "Command not found or not supported"
import unittest from main import decode class TestSum(unittest.TestCase): def test(self): self.assertEqual(decode([20, 12, 18, 30, 21], 1939), "scout") self.assertEqual(decode([14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8], 1939), "masterpiece") if __name__ == '__main__': unittest.main()
module.exports = function toReadable(number) { const units = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '] const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] var getLT20 = function(n) { return units[n] } var getGT20 = function(n) { let n2 = (n - n % 10) / 10 let n1 = n % 10 return tens[n2] + ' ' + units[n1] } if (number === 0) return 'zero' if (number > 999) { throw new Error('overflow') } let str = '' let n3 = (number - number % 100) / 100 let n21 = number % 100 str = str + n3 != 0 ? getLT20(n3) + 'hundred ' : '' str = str + (getLT20(n21) || getGT20(n21)) return str.trim() }
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Version, NgModule, InjectionToken, Optional, Inject, isDevMode, inject, LOCALE_ID, Injectable, Directive, ElementRef, Input, NgZone, Component, ViewEncapsulation, ChangeDetectionStrategy, ChangeDetectorRef, EventEmitter, Output, ɵɵdefineInjectable } from '@angular/core'; import { HAMMER_LOADER, HammerGestureConfig } from '@angular/platform-browser'; import { BidiModule } from '@angular/cdk/bidi'; import { VERSION } from '@angular/cdk'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { Subject, Observable } from 'rxjs'; import { Platform, PlatformModule, normalizePassiveListenerOptions } from '@angular/cdk/platform'; import { startWith } from 'rxjs/operators'; import { isFakeMousedownFromScreenReader } from '@angular/cdk/a11y'; import { ANIMATION_MODULE_TYPE } from '@angular/platform-browser/animations'; import { ENTER, SPACE, hasModifierKey } from '@angular/cdk/keycodes'; import { CommonModule } from '@angular/common'; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Current version of Angular Material. * @type {?} */ const VERSION$1 = new Version('8.1.4'); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * \@docs-private */ class AnimationCurves { } AnimationCurves.STANDARD_CURVE = 'cubic-bezier(0.4,0.0,0.2,1)'; AnimationCurves.DECELERATION_CURVE = 'cubic-bezier(0.0,0.0,0.2,1)'; AnimationCurves.ACCELERATION_CURVE = 'cubic-bezier(0.4,0.0,1,1)'; AnimationCurves.SHARP_CURVE = 'cubic-bezier(0.4,0.0,0.6,1)'; /** * \@docs-private */ class AnimationDurations { } AnimationDurations.COMPLEX = '375ms'; AnimationDurations.ENTERING = '225ms'; AnimationDurations.EXITING = '195ms'; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ // Private version constant to circumvent test/build issues, // i.e. avoid core to depend on the @angular/material primary entry-point // Can be removed once the Material primary entry-point no longer // re-exports all secondary entry-points /** @type {?} */ const VERSION$2 = new Version('8.1.4'); /** * Injection token that configures whether the Material sanity checks are enabled. * @type {?} */ const MATERIAL_SANITY_CHECKS = new InjectionToken('mat-sanity-checks', { providedIn: 'root', factory: MATERIAL_SANITY_CHECKS_FACTORY, }); /** * \@docs-private * @return {?} */ function MATERIAL_SANITY_CHECKS_FACTORY() { return true; } /** * Module that captures anything that should be loaded and/or run for *all* Angular Material * components. This includes Bidi, etc. * * This module should be imported to each top-level component module (e.g., MatTabsModule). */ class MatCommonModule { /** * @param {?} _sanityChecksEnabled * @param {?=} _hammerLoader */ constructor(_sanityChecksEnabled, _hammerLoader) { this._sanityChecksEnabled = _sanityChecksEnabled; this._hammerLoader = _hammerLoader; /** * Whether we've done the global sanity checks (e.g. a theme is loaded, there is a doctype). */ this._hasDoneGlobalChecks = false; /** * Whether we've already checked for HammerJs availability. */ this._hasCheckedHammer = false; /** * Reference to the global `document` object. */ this._document = typeof document === 'object' && document ? document : null; /** * Reference to the global 'window' object. */ this._window = typeof window === 'object' && window ? window : null; if (this._areChecksEnabled() && !this._hasDoneGlobalChecks) { this._checkDoctypeIsDefined(); this._checkThemeIsPresent(); this._checkCdkVersionMatch(); this._hasDoneGlobalChecks = true; } } /** * Whether any sanity checks are enabled * @private * @return {?} */ _areChecksEnabled() { return this._sanityChecksEnabled && isDevMode() && !this._isTestEnv(); } /** * Whether the code is running in tests. * @private * @return {?} */ _isTestEnv() { /** @type {?} */ const window = (/** @type {?} */ (this._window)); return window && (window.__karma__ || window.jasmine); } /** * @private * @return {?} */ _checkDoctypeIsDefined() { if (this._document && !this._document.doctype) { console.warn('Current document does not have a doctype. This may cause ' + 'some Angular Material components not to behave as expected.'); } } /** * @private * @return {?} */ _checkThemeIsPresent() { // We need to assert that the `body` is defined, because these checks run very early // and the `body` won't be defined if the consumer put their scripts in the `head`. if (!this._document || !this._document.body || typeof getComputedStyle !== 'function') { return; } /** @type {?} */ const testElement = this._document.createElement('div'); testElement.classList.add('mat-theme-loaded-marker'); this._document.body.appendChild(testElement); /** @type {?} */ const computedStyle = getComputedStyle(testElement); // In some situations the computed style of the test element can be null. For example in // Firefox, the computed style is null if an application is running inside of a hidden iframe. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=548397 if (computedStyle && computedStyle.display !== 'none') { console.warn('Could not find Angular Material core theme. Most Material ' + 'components may not work as expected. For more info refer ' + 'to the theming guide: https://material.angular.io/guide/theming'); } this._document.body.removeChild(testElement); } /** * Checks whether the material version matches the cdk version * @private * @return {?} */ _checkCdkVersionMatch() { if (VERSION$2.full !== VERSION.full) { console.warn('The Angular Material version (' + VERSION$2.full + ') does not match ' + 'the Angular CDK version (' + VERSION.full + ').\n' + 'Please ensure the versions of these two packages exactly match.'); } } /** * Checks whether HammerJS is available. * @return {?} */ _checkHammerIsAvailable() { if (this._hasCheckedHammer || !this._window) { return; } if (this._areChecksEnabled() && !((/** @type {?} */ (this._window)))['Hammer'] && !this._hammerLoader) { console.warn('Could not find HammerJS. Certain Angular Material components may not work correctly.'); } this._hasCheckedHammer = true; } } MatCommonModule.decorators = [ { type: NgModule, args: [{ imports: [BidiModule], exports: [BidiModule], },] }, ]; /** @nocollapse */ MatCommonModule.ctorParameters = () => [ { type: Boolean, decorators: [{ type: Optional }, { type: Inject, args: [MATERIAL_SANITY_CHECKS,] }] }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [HAMMER_LOADER,] }] } ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Mixin to augment a directive with a `disabled` property. * @template T * @param {?} base * @return {?} */ function mixinDisabled(base) { return class extends base { /** * @param {...?} args */ constructor(...args) { super(...args); this._disabled = false; } /** * @return {?} */ get disabled() { return this._disabled; } /** * @param {?} value * @return {?} */ set disabled(value) { this._disabled = coerceBooleanProperty(value); } }; } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Mixin to augment a directive with a `color` property. * @template T * @param {?} base * @param {?=} defaultColor * @return {?} */ function mixinColor(base, defaultColor) { return class extends base { /** * @return {?} */ get color() { return this._color; } /** * @param {?} value * @return {?} */ set color(value) { /** @type {?} */ const colorPalette = value || defaultColor; if (colorPalette !== this._color) { if (this._color) { this._elementRef.nativeElement.classList.remove(`mat-${this._color}`); } if (colorPalette) { this._elementRef.nativeElement.classList.add(`mat-${colorPalette}`); } this._color = colorPalette; } } /** * @param {...?} args */ constructor(...args) { super(...args); // Set the default color that can be specified from the mixin. this.color = defaultColor; } }; } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Mixin to augment a directive with a `disableRipple` property. * @template T * @param {?} base * @return {?} */ function mixinDisableRipple(base) { return class extends base { /** * @param {...?} args */ constructor(...args) { super(...args); this._disableRipple = false; } /** * Whether the ripple effect is disabled or not. * @return {?} */ get disableRipple() { return this._disableRipple; } /** * @param {?} value * @return {?} */ set disableRipple(value) { this._disableRipple = coerceBooleanProperty(value); } }; } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Mixin to augment a directive with a `tabIndex` property. * @template T * @param {?} base * @param {?=} defaultTabIndex * @return {?} */ function mixinTabIndex(base, defaultTabIndex = 0) { return class extends base { /** * @param {...?} args */ constructor(...args) { super(...args); this._tabIndex = defaultTabIndex; } /** * @return {?} */ get tabIndex() { return this.disabled ? -1 : this._tabIndex; } /** * @param {?} value * @return {?} */ set tabIndex(value) { // If the specified tabIndex value is null or undefined, fall back to the default value. this._tabIndex = value != null ? value : defaultTabIndex; } }; } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Mixin to augment a directive with updateErrorState method. * For component with `errorState` and need to update `errorState`. * @template T * @param {?} base * @return {?} */ function mixinErrorState(base) { return class extends base { /** * @param {...?} args */ constructor(...args) { super(...args); /** * Whether the component is in an error state. */ this.errorState = false; /** * Stream that emits whenever the state of the input changes such that the wrapping * `MatFormField` needs to run change detection. */ this.stateChanges = new Subject(); } /** * @return {?} */ updateErrorState() { /** @type {?} */ const oldState = this.errorState; /** @type {?} */ const parent = this._parentFormGroup || this._parentForm; /** @type {?} */ const matcher = this.errorStateMatcher || this._defaultErrorStateMatcher; /** @type {?} */ const control = this.ngControl ? (/** @type {?} */ (this.ngControl.control)) : null; /** @type {?} */ const newState = matcher.isErrorState(control, parent); if (newState !== oldState) { this.errorState = newState; this.stateChanges.next(); } } }; } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Mixin to augment a directive with an initialized property that will emits when ngOnInit ends. * @template T * @param {?} base * @return {?} */ function mixinInitialized(base) { return class extends base { /** * @param {...?} args */ constructor(...args) { super(...args); /** * Whether this directive has been marked as initialized. */ this._isInitialized = false; /** * List of subscribers that subscribed before the directive was initialized. Should be notified * during _markInitialized. Set to null after pending subscribers are notified, and should * not expect to be populated after. */ this._pendingSubscribers = []; /** * Observable stream that emits when the directive initializes. If already initialized, the * subscriber is stored to be notified once _markInitialized is called. */ this.initialized = new Observable((/** * @param {?} subscriber * @return {?} */ subscriber => { // If initialized, immediately notify the subscriber. Otherwise store the subscriber to notify // when _markInitialized is called. if (this._isInitialized) { this._notifySubscriber(subscriber); } else { (/** @type {?} */ (this._pendingSubscribers)).push(subscriber); } })); } /** * Marks the state as initialized and notifies pending subscribers. Should be called at the end * of ngOnInit. * \@docs-private * @return {?} */ _markInitialized() { if (this._isInitialized) { throw Error('This directive has already been marked as initialized and ' + 'should not be called twice.'); } this._isInitialized = true; (/** @type {?} */ (this._pendingSubscribers)).forEach(this._notifySubscriber); this._pendingSubscribers = null; } /** * Emits and completes the subscriber stream (should only emit once). * @param {?} subscriber * @return {?} */ _notifySubscriber(subscriber) { subscriber.next(); subscriber.complete(); } }; } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * InjectionToken for datepicker that can be used to override default locale code. * @type {?} */ const MAT_DATE_LOCALE = new InjectionToken('MAT_DATE_LOCALE', { providedIn: 'root', factory: MAT_DATE_LOCALE_FACTORY, }); /** * \@docs-private * @return {?} */ function MAT_DATE_LOCALE_FACTORY() { return inject(LOCALE_ID); } /** * No longer needed since MAT_DATE_LOCALE has been changed to a scoped injectable. * If you are importing and providing this in your code you can simply remove it. * @deprecated * \@breaking-change 8.0.0 * @type {?} */ const MAT_DATE_LOCALE_PROVIDER = { provide: MAT_DATE_LOCALE, useExisting: LOCALE_ID }; /** * Adapts type `D` to be usable as a date by cdk-based components that work with dates. * @abstract * @template D */ class DateAdapter { constructor() { this._localeChanges = new Subject(); } /** * A stream that emits when the locale changes. * @return {?} */ get localeChanges() { return this._localeChanges; } /** * Attempts to deserialize a value to a valid date object. This is different from parsing in that * deserialize should only accept non-ambiguous, locale-independent formats (e.g. a ISO 8601 * string). The default implementation does not allow any deserialization, it simply checks that * the given value is already a valid date object or null. The `<mat-datepicker>` will call this * method on all of it's `\@Input()` properties that accept dates. It is therefore possible to * support passing values from your backend directly to these properties by overriding this method * to also deserialize the format used by your backend. * @param {?} value The value to be deserialized into a date object. * @return {?} The deserialized date object, either a valid date, null if the value can be * deserialized into a null date (e.g. the empty string), or an invalid date. */ deserialize(value) { if (value == null || this.isDateInstance(value) && this.isValid(value)) { return value; } return this.invalid(); } /** * Sets the locale used for all dates. * @param {?} locale The new locale. * @return {?} */ setLocale(locale) { this.locale = locale; this._localeChanges.next(); } /** * Compares two dates. * @param {?} first The first date to compare. * @param {?} second The second date to compare. * @return {?} 0 if the dates are equal, a number less than 0 if the first date is earlier, * a number greater than 0 if the first date is later. */ compareDate(first, second) { return this.getYear(first) - this.getYear(second) || this.getMonth(first) - this.getMonth(second) || this.getDate(first) - this.getDate(second); } /** * Checks if two dates are equal. * @param {?} first The first date to check. * @param {?} second The second date to check. * @return {?} Whether the two dates are equal. * Null dates are considered equal to other null dates. */ sameDate(first, second) { if (first && second) { /** @type {?} */ let firstValid = this.isValid(first); /** @type {?} */ let secondValid = this.isValid(second); if (firstValid && secondValid) { return !this.compareDate(first, second); } return firstValid == secondValid; } return first == second; } /** * Clamp the given date between min and max dates. * @param {?} date The date to clamp. * @param {?=} min The minimum value to allow. If null or omitted no min is enforced. * @param {?=} max The maximum value to allow. If null or omitted no max is enforced. * @return {?} `min` if `date` is less than `min`, `max` if date is greater than `max`, * otherwise `date`. */ clampDate(date, min, max) { if (min && this.compareDate(date, min) < 0) { return min; } if (max && this.compareDate(date, max) > 0) { return max; } return date; } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ const MAT_DATE_FORMATS = new InjectionToken('mat-date-formats'); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ // TODO(mmalerba): Remove when we no longer support safari 9. /** * Whether the browser supports the Intl API. * @type {?} */ let SUPPORTS_INTL_API; // We need a try/catch around the reference to `Intl`, because accessing it in some cases can // cause IE to throw. These cases are tied to particular versions of Windows and can happen if // the consumer is providing a polyfilled `Map`. See: // https://github.com/Microsoft/ChakraCore/issues/3189 // https://github.com/angular/components/issues/15687 try { SUPPORTS_INTL_API = typeof Intl != 'undefined'; } catch (_a) { SUPPORTS_INTL_API = false; } /** * The default month names to use if Intl API is not available. * @type {?} */ const DEFAULT_MONTH_NAMES = { 'long': [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], 'short': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], 'narrow': ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'] }; const ɵ0 = /** * @param {?} i * @return {?} */ i => String(i + 1); /** * The default date names to use if Intl API is not available. * @type {?} */ const DEFAULT_DATE_NAMES = range(31, (ɵ0)); /** * The default day of the week names to use if Intl API is not available. * @type {?} */ const DEFAULT_DAY_OF_WEEK_NAMES = { 'long': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], 'short': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], 'narrow': ['S', 'M', 'T', 'W', 'T', 'F', 'S'] }; /** * Matches strings that have the form of a valid RFC 3339 string * (https://tools.ietf.org/html/rfc3339). Note that the string may not actually be a valid date * because the regex will match strings an with out of bounds month, date, etc. * @type {?} */ const ISO_8601_REGEX = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|(?:(?:\+|-)\d{2}:\d{2}))?)?$/; /** * Creates an array and fills it with values. * @template T * @param {?} length * @param {?} valueFunction * @return {?} */ function range(length, valueFunction) { /** @type {?} */ const valuesArray = Array(length); for (let i = 0; i < length; i++) { valuesArray[i] = valueFunction(i); } return valuesArray; } /** * Adapts the native JS Date for use with cdk-based components that work with dates. */ class NativeDateAdapter extends DateAdapter { /** * @param {?} matDateLocale * @param {?} platform */ constructor(matDateLocale, platform) { super(); /** * Whether to use `timeZone: 'utc'` with `Intl.DateTimeFormat` when formatting dates. * Without this `Intl.DateTimeFormat` sometimes chooses the wrong timeZone, which can throw off * the result. (e.g. in the en-US locale `new Date(1800, 7, 14).toLocaleDateString()` * will produce `'8/13/1800'`. * * TODO(mmalerba): drop this variable. It's not being used in the code right now. We're now * getting the string representation of a Date object from it's utc representation. We're keeping * it here for sometime, just for precaution, in case we decide to revert some of these changes * though. */ this.useUtcForDisplay = true; super.setLocale(matDateLocale); // IE does its own time zone correction, so we disable this on IE. this.useUtcForDisplay = !platform.TRIDENT; this._clampDate = platform.TRIDENT || platform.EDGE; } /** * @param {?} date * @return {?} */ getYear(date) { return date.getFullYear(); } /** * @param {?} date * @return {?} */ getMonth(date) { return date.getMonth(); } /** * @param {?} date * @return {?} */ getDate(date) { return date.getDate(); } /** * @param {?} date * @return {?} */ getDayOfWeek(date) { return date.getDay(); } /** * @param {?} style * @return {?} */ getMonthNames(style) { if (SUPPORTS_INTL_API) { /** @type {?} */ const dtf = new Intl.DateTimeFormat(this.locale, { month: style, timeZone: 'utc' }); return range(12, (/** * @param {?} i * @return {?} */ i => this._stripDirectionalityCharacters(this._format(dtf, new Date(2017, i, 1))))); } return DEFAULT_MONTH_NAMES[style]; } /** * @return {?} */ getDateNames() { if (SUPPORTS_INTL_API) { /** @type {?} */ const dtf = new Intl.DateTimeFormat(this.locale, { day: 'numeric', timeZone: 'utc' }); return range(31, (/** * @param {?} i * @return {?} */ i => this._stripDirectionalityCharacters(this._format(dtf, new Date(2017, 0, i + 1))))); } return DEFAULT_DATE_NAMES; } /** * @param {?} style * @return {?} */ getDayOfWeekNames(style) { if (SUPPORTS_INTL_API) { /** @type {?} */ const dtf = new Intl.DateTimeFormat(this.locale, { weekday: style, timeZone: 'utc' }); return range(7, (/** * @param {?} i * @return {?} */ i => this._stripDirectionalityCharacters(this._format(dtf, new Date(2017, 0, i + 1))))); } return DEFAULT_DAY_OF_WEEK_NAMES[style]; } /** * @param {?} date * @return {?} */ getYearName(date) { if (SUPPORTS_INTL_API) { /** @type {?} */ const dtf = new Intl.DateTimeFormat(this.locale, { year: 'numeric', timeZone: 'utc' }); return this._stripDirectionalityCharacters(this._format(dtf, date)); } return String(this.getYear(date)); } /** * @return {?} */ getFirstDayOfWeek() { // We can't tell using native JS Date what the first day of the week is, we default to Sunday. return 0; } /** * @param {?} date * @return {?} */ getNumDaysInMonth(date) { return this.getDate(this._createDateWithOverflow(this.getYear(date), this.getMonth(date) + 1, 0)); } /** * @param {?} date * @return {?} */ clone(date) { return new Date(date.getTime()); } /** * @param {?} year * @param {?} month * @param {?} date * @return {?} */ createDate(year, month, date) { // Check for invalid month and date (except upper bound on date which we have to check after // creating the Date). if (month < 0 || month > 11) { throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`); } if (date < 1) { throw Error(`Invalid date "${date}". Date has to be greater than 0.`); } /** @type {?} */ let result = this._createDateWithOverflow(year, month, date); // Check that the date wasn't above the upper bound for the month, causing the month to overflow if (result.getMonth() != month) { throw Error(`Invalid date "${date}" for month with index "${month}".`); } return result; } /** * @return {?} */ today() { return new Date(); } /** * @param {?} value * @return {?} */ parse(value) { // We have no way using the native JS Date to set the parse format or locale, so we ignore these // parameters. if (typeof value == 'number') { return new Date(value); } return value ? new Date(Date.parse(value)) : null; } /** * @param {?} date * @param {?} displayFormat * @return {?} */ format(date, displayFormat) { if (!this.isValid(date)) { throw Error('NativeDateAdapter: Cannot format invalid date.'); } if (SUPPORTS_INTL_API) { // On IE and Edge the i18n API will throw a hard error that can crash the entire app // if we attempt to format a date whose year is less than 1 or greater than 9999. if (this._clampDate && (date.getFullYear() < 1 || date.getFullYear() > 9999)) { date = this.clone(date); date.setFullYear(Math.max(1, Math.min(9999, date.getFullYear()))); } displayFormat = Object.assign({}, displayFormat, { timeZone: 'utc' }); /** @type {?} */ const dtf = new Intl.DateTimeFormat(this.locale, displayFormat); return this._stripDirectionalityCharacters(this._format(dtf, date)); } return this._stripDirectionalityCharacters(date.toDateString()); } /** * @param {?} date * @param {?} years * @return {?} */ addCalendarYears(date, years) { return this.addCalendarMonths(date, years * 12); } /** * @param {?} date * @param {?} months * @return {?} */ addCalendarMonths(date, months) { /** @type {?} */ let newDate = this._createDateWithOverflow(this.getYear(date), this.getMonth(date) + months, this.getDate(date)); // It's possible to wind up in the wrong month if the original month has more days than the new // month. In this case we want to go to the last day of the desired month. // Note: the additional + 12 % 12 ensures we end up with a positive number, since JS % doesn't // guarantee this. if (this.getMonth(newDate) != ((this.getMonth(date) + months) % 12 + 12) % 12) { newDate = this._createDateWithOverflow(this.getYear(newDate), this.getMonth(newDate), 0); } return newDate; } /** * @param {?} date * @param {?} days * @return {?} */ addCalendarDays(date, days) { return this._createDateWithOverflow(this.getYear(date), this.getMonth(date), this.getDate(date) + days); } /** * @param {?} date * @return {?} */ toIso8601(date) { return [ date.getUTCFullYear(), this._2digit(date.getUTCMonth() + 1), this._2digit(date.getUTCDate()) ].join('-'); } /** * Returns the given value if given a valid Date or null. Deserializes valid ISO 8601 strings * (https://www.ietf.org/rfc/rfc3339.txt) into valid Dates and empty string into null. Returns an * invalid date for all other values. * @param {?} value * @return {?} */ deserialize(value) { if (typeof value === 'string') { if (!value) { return null; } // The `Date` constructor accepts formats other than ISO 8601, so we need to make sure the // string is the right format first. if (ISO_8601_REGEX.test(value)) { /** @type {?} */ let date = new Date(value); if (this.isValid(date)) { return date; } } } return super.deserialize(value); } /** * @param {?} obj * @return {?} */ isDateInstance(obj) { return obj instanceof Date; } /** * @param {?} date * @return {?} */ isValid(date) { return !isNaN(date.getTime()); } /** * @return {?} */ invalid() { return new Date(NaN); } /** * Creates a date but allows the month and date to overflow. * @private * @param {?} year * @param {?} month * @param {?} date * @return {?} */ _createDateWithOverflow(year, month, date) { /** @type {?} */ const result = new Date(year, month, date); // We need to correct for the fact that JS native Date treats years in range [0, 99] as // abbreviations for 19xx. if (year >= 0 && year < 100) { result.setFullYear(this.getYear(result) - 1900); } return result; } /** * Pads a number to make it two digits. * @private * @param {?} n The number to pad. * @return {?} The padded number. */ _2digit(n) { return ('00' + n).slice(-2); } /** * Strip out unicode LTR and RTL characters. Edge and IE insert these into formatted dates while * other browsers do not. We remove them to make output consistent and because they interfere with * date parsing. * @private * @param {?} str The string to strip direction characters from. * @return {?} The stripped string. */ _stripDirectionalityCharacters(str) { return str.replace(/[\u200e\u200f]/g, ''); } /** * When converting Date object to string, javascript built-in functions may return wrong * results because it applies its internal DST rules. The DST rules around the world change * very frequently, and the current valid rule is not always valid in previous years though. * We work around this problem building a new Date object which has its internal UTC * representation with the local date and time. * @private * @param {?} dtf Intl.DateTimeFormat object, containg the desired string format. It must have * timeZone set to 'utc' to work fine. * @param {?} date Date from which we want to get the string representation according to dtf * @return {?} A Date object with its UTC representation based on the passed in date info */ _format(dtf, date) { /** @type {?} */ const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds())); return dtf.format(d); } } NativeDateAdapter.decorators = [ { type: Injectable }, ]; /** @nocollapse */ NativeDateAdapter.ctorParameters = () => [ { type: String, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_LOCALE,] }] }, { type: Platform } ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ const MAT_NATIVE_DATE_FORMATS = { parse: { dateInput: null, }, display: { dateInput: { year: 'numeric', month: 'numeric', day: 'numeric' }, monthYearLabel: { year: 'numeric', month: 'short' }, dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' }, monthYearA11yLabel: { year: 'numeric', month: 'long' }, } }; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class NativeDateModule { } NativeDateModule.decorators = [ { type: NgModule, args: [{ imports: [PlatformModule], providers: [ { provide: DateAdapter, useClass: NativeDateAdapter }, ], },] }, ]; const ɵ0$1 = MAT_NATIVE_DATE_FORMATS; class MatNativeDateModule { } MatNativeDateModule.decorators = [ { type: NgModule, args: [{ imports: [NativeDateModule], providers: [{ provide: MAT_DATE_FORMATS, useValue: ɵ0$1 }], },] }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Error state matcher that matches when a control is invalid and dirty. */ class ShowOnDirtyErrorStateMatcher { /** * @param {?} control * @param {?} form * @return {?} */ isErrorState(control, form) { return !!(control && control.invalid && (control.dirty || (form && form.submitted))); } } ShowOnDirtyErrorStateMatcher.decorators = [ { type: Injectable }, ]; /** * Provider that defines how form controls behave with regards to displaying error messages. */ class ErrorStateMatcher { /** * @param {?} control * @param {?} form * @return {?} */ isErrorState(control, form) { return !!(control && control.invalid && (control.touched || (form && form.submitted))); } } ErrorStateMatcher.decorators = [ { type: Injectable, args: [{ providedIn: 'root' },] }, ]; /** @nocollapse */ ErrorStateMatcher.ngInjectableDef = ɵɵdefineInjectable({ factory: function ErrorStateMatcher_Factory() { return new ErrorStateMatcher(); }, token: ErrorStateMatcher, providedIn: "root" }); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Injection token that can be used to provide options to the Hammerjs instance. * More info at http://hammerjs.github.io/api/. * @type {?} */ const MAT_HAMMER_OPTIONS = new InjectionToken('MAT_HAMMER_OPTIONS'); /** @type {?} */ const ANGULAR_MATERIAL_SUPPORTED_HAMMER_GESTURES = [ 'longpress', 'slide', 'slidestart', 'slideend', 'slideright', 'slideleft' ]; const ɵ0$2 = /** * @return {?} */ () => { }, ɵ1 = /** * @return {?} */ () => { }; /** * Fake HammerInstance that is used when a Hammer instance is requested when HammerJS has not * been loaded on the page. * @type {?} */ const noopHammerInstance = { on: (ɵ0$2), off: (ɵ1), }; /** * Adjusts configuration of our gesture library, Hammer. */ class GestureConfig extends HammerGestureConfig { /** * @param {?=} _hammerOptions * @param {?=} commonModule */ constructor(_hammerOptions, commonModule) { super(); this._hammerOptions = _hammerOptions; /** * List of new event names to add to the gesture support list */ this.events = ANGULAR_MATERIAL_SUPPORTED_HAMMER_GESTURES; if (commonModule) { commonModule._checkHammerIsAvailable(); } } /** * Builds Hammer instance manually to add custom recognizers that match the Material Design spec. * * Our gesture names come from the Material Design gestures spec: * https://material.io/design/#gestures-touch-mechanics * * More information on default recognizers can be found in Hammer docs: * http://hammerjs.github.io/recognizer-pan/ * http://hammerjs.github.io/recognizer-press/ * * @param {?} element Element to which to assign the new HammerJS gestures. * @return {?} Newly-created HammerJS instance. */ buildHammer(element) { /** @type {?} */ const hammer = typeof window !== 'undefined' ? ((/** @type {?} */ (window))).Hammer : null; if (!hammer) { // If HammerJS is not loaded here, return the noop HammerInstance. This is necessary to // ensure that omitting HammerJS completely will not cause any errors while *also* supporting // the lazy-loading of HammerJS via the HAMMER_LOADER token introduced in Angular 6.1. // Because we can't depend on HAMMER_LOADER's existance until 7.0, we have to always set // `this.events` to the set we support, instead of conditionally setting it to `[]` if // `HAMMER_LOADER` is present (and then throwing an Error here if `window.Hammer` is // undefined). // @breaking-change 8.0.0 return noopHammerInstance; } /** @type {?} */ const mc = new hammer(element, this._hammerOptions || undefined); // Default Hammer Recognizers. /** @type {?} */ const pan = new hammer.Pan(); /** @type {?} */ const swipe = new hammer.Swipe(); /** @type {?} */ const press = new hammer.Press(); // Notice that a HammerJS recognizer can only depend on one other recognizer once. // Otherwise the previous `recognizeWith` will be dropped. // TODO: Confirm threshold numbers with Material Design UX Team /** @type {?} */ const slide = this._createRecognizer(pan, { event: 'slide', threshold: 0 }, swipe); /** @type {?} */ const longpress = this._createRecognizer(press, { event: 'longpress', time: 500 }); // Overwrite the default `pan` event to use the swipe event. pan.recognizeWith(swipe); // Since the slide event threshold is set to zero, the slide recognizer can fire and // accidentally reset the longpress recognizer. In order to make sure that the two // recognizers can run simultaneously but don't affect each other, we allow the slide // recognizer to recognize while a longpress is being processed. // See: https://github.com/hammerjs/hammer.js/blob/master/src/manager.js#L123-L124 longpress.recognizeWith(slide); // Add customized gestures to Hammer manager mc.add([swipe, press, pan, slide, longpress]); return (/** @type {?} */ (mc)); } /** * Creates a new recognizer, without affecting the default recognizers of HammerJS * @private * @param {?} base * @param {?} options * @param {...?} inheritances * @return {?} */ _createRecognizer(base, options, ...inheritances) { /** @type {?} */ let recognizer = new ((/** @type {?} */ (base.constructor)))(options); inheritances.push(base); inheritances.forEach((/** * @param {?} item * @return {?} */ item => recognizer.recognizeWith(item))); return recognizer; } } GestureConfig.decorators = [ { type: Injectable }, ]; /** @nocollapse */ GestureConfig.ctorParameters = () => [ { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_HAMMER_OPTIONS,] }] }, { type: MatCommonModule, decorators: [{ type: Optional }] } ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Shared directive to count lines inside a text area, such as a list item. * Line elements can be extracted with a \@ContentChildren(MatLine) query, then * counted by checking the query list's length. */ class MatLine { } MatLine.decorators = [ { type: Directive, args: [{ selector: '[mat-line], [matLine]', host: { 'class': 'mat-line' } },] }, ]; /** * Helper that takes a query list of lines and sets the correct class on the host. * \@docs-private * @param {?} lines * @param {?} element * @return {?} */ function setLines(lines, element) { // Note: doesn't need to unsubscribe, because `changes` // gets completed by Angular when the view is destroyed. lines.changes.pipe(startWith(lines)).subscribe((/** * @param {?} __0 * @return {?} */ ({ length }) => { setClass(element, 'mat-2-line', false); setClass(element, 'mat-3-line', false); setClass(element, 'mat-multi-line', false); if (length === 2 || length === 3) { setClass(element, `mat-${length}-line`, true); } else if (length > 3) { setClass(element, `mat-multi-line`, true); } })); } /** * Adds or removes a class from an element. * @param {?} element * @param {?} className * @param {?} isAdd * @return {?} */ function setClass(element, className, isAdd) { /** @type {?} */ const classList = element.nativeElement.classList; isAdd ? classList.add(className) : classList.remove(className); } /** * Helper that takes a query list of lines and sets the correct class on the host. * \@docs-private * @deprecated Use `setLines` instead. * \@breaking-change 8.0.0 */ class MatLineSetter { /** * @param {?} lines * @param {?} element */ constructor(lines, element) { setLines(lines, element); } } class MatLineModule { } MatLineModule.decorators = [ { type: NgModule, args: [{ imports: [MatCommonModule], exports: [MatLine, MatCommonModule], declarations: [MatLine], },] }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @enum {number} */ const RippleState = { FADING_IN: 0, VISIBLE: 1, FADING_OUT: 2, HIDDEN: 3, }; RippleState[RippleState.FADING_IN] = 'FADING_IN'; RippleState[RippleState.VISIBLE] = 'VISIBLE'; RippleState[RippleState.FADING_OUT] = 'FADING_OUT'; RippleState[RippleState.HIDDEN] = 'HIDDEN'; /** * Reference to a previously launched ripple element. */ class RippleRef { /** * @param {?} _renderer * @param {?} element * @param {?} config */ constructor(_renderer, element, config) { this._renderer = _renderer; this.element = element; this.config = config; /** * Current state of the ripple. */ this.state = RippleState.HIDDEN; } /** * Fades out the ripple element. * @return {?} */ fadeOut() { this._renderer.fadeOutRipple(this); } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Default ripple animation configuration for ripples without an explicit * animation config specified. * @type {?} */ const defaultRippleAnimationConfig = { enterDuration: 450, exitDuration: 400 }; /** * Timeout for ignoring mouse events. Mouse events will be temporary ignored after touch * events to avoid synthetic mouse events. * @type {?} */ const ignoreMouseEventsTimeout = 800; /** * Options that apply to all the event listeners that are bound by the ripple renderer. * @type {?} */ const passiveEventOptions = normalizePassiveListenerOptions({ passive: true }); /** * Helper service that performs DOM manipulations. Not intended to be used outside this module. * The constructor takes a reference to the ripple directive's host element and a map of DOM * event handlers to be installed on the element that triggers ripple animations. * This will eventually become a custom renderer once Angular support exists. * \@docs-private */ class RippleRenderer { /** * @param {?} _target * @param {?} _ngZone * @param {?} elementRef * @param {?} platform */ constructor(_target, _ngZone, elementRef, platform) { this._target = _target; this._ngZone = _ngZone; /** * Whether the pointer is currently down or not. */ this._isPointerDown = false; /** * Events to be registered on the trigger element. */ this._triggerEvents = new Map(); /** * Set of currently active ripple references. */ this._activeRipples = new Set(); /** * Function being called whenever the trigger is being pressed using mouse. */ this._onMousedown = (/** * @param {?} event * @return {?} */ (event) => { // Screen readers will fire fake mouse events for space/enter. Skip launching a // ripple in this case for consistency with the non-screen-reader experience. /** @type {?} */ const isFakeMousedown = isFakeMousedownFromScreenReader(event); /** @type {?} */ const isSyntheticEvent = this._lastTouchStartEvent && Date.now() < this._lastTouchStartEvent + ignoreMouseEventsTimeout; if (!this._target.rippleDisabled && !isFakeMousedown && !isSyntheticEvent) { this._isPointerDown = true; this.fadeInRipple(event.clientX, event.clientY, this._target.rippleConfig); } }); /** * Function being called whenever the trigger is being pressed using touch. */ this._onTouchStart = (/** * @param {?} event * @return {?} */ (event) => { if (!this._target.rippleDisabled) { // Some browsers fire mouse events after a `touchstart` event. Those synthetic mouse // events will launch a second ripple if we don't ignore mouse events for a specific // time after a touchstart event. this._lastTouchStartEvent = Date.now(); this._isPointerDown = true; // Use `changedTouches` so we skip any touches where the user put // their finger down, but used another finger to tap the element again. /** @type {?} */ const touches = event.changedTouches; for (let i = 0; i < touches.length; i++) { this.fadeInRipple(touches[i].clientX, touches[i].clientY, this._target.rippleConfig); } } }); /** * Function being called whenever the trigger is being released. */ this._onPointerUp = (/** * @return {?} */ () => { if (!this._isPointerDown) { return; } this._isPointerDown = false; // Fade-out all ripples that are visible and not persistent. this._activeRipples.forEach((/** * @param {?} ripple * @return {?} */ ripple => { // By default, only ripples that are completely visible will fade out on pointer release. // If the `terminateOnPointerUp` option is set, ripples that still fade in will also fade out. /** @type {?} */ const isVisible = ripple.state === RippleState.VISIBLE || ripple.config.terminateOnPointerUp && ripple.state === RippleState.FADING_IN; if (!ripple.config.persistent && isVisible) { ripple.fadeOut(); } })); }); // Only do anything if we're on the browser. if (platform.isBrowser) { this._containerElement = elementRef.nativeElement; // Specify events which need to be registered on the trigger. this._triggerEvents .set('mousedown', this._onMousedown) .set('mouseup', this._onPointerUp) .set('mouseleave', this._onPointerUp) .set('touchstart', this._onTouchStart) .set('touchend', this._onPointerUp) .set('touchcancel', this._onPointerUp); } } /** * Fades in a ripple at the given coordinates. * @param {?} x Coordinate within the element, along the X axis at which to start the ripple. * @param {?} y Coordinate within the element, along the Y axis at which to start the ripple. * @param {?=} config Extra ripple options. * @return {?} */ fadeInRipple(x, y, config = {}) { /** @type {?} */ const containerRect = this._containerRect = this._containerRect || this._containerElement.getBoundingClientRect(); /** @type {?} */ const animationConfig = Object.assign({}, defaultRippleAnimationConfig, config.animation); if (config.centered) { x = containerRect.left + containerRect.width / 2; y = containerRect.top + containerRect.height / 2; } /** @type {?} */ const radius = config.radius || distanceToFurthestCorner(x, y, containerRect); /** @type {?} */ const offsetX = x - containerRect.left; /** @type {?} */ const offsetY = y - containerRect.top; /** @type {?} */ const duration = animationConfig.enterDuration; /** @type {?} */ const ripple = document.createElement('div'); ripple.classList.add('mat-ripple-element'); ripple.style.left = `${offsetX - radius}px`; ripple.style.top = `${offsetY - radius}px`; ripple.style.height = `${radius * 2}px`; ripple.style.width = `${radius * 2}px`; // If the color is not set, the default CSS color will be used. ripple.style.backgroundColor = config.color || null; ripple.style.transitionDuration = `${duration}ms`; this._containerElement.appendChild(ripple); // By default the browser does not recalculate the styles of dynamically created // ripple elements. This is critical because then the `scale` would not animate properly. enforceStyleRecalculation(ripple); ripple.style.transform = 'scale(1)'; // Exposed reference to the ripple that will be returned. /** @type {?} */ const rippleRef = new RippleRef(this, ripple, config); rippleRef.state = RippleState.FADING_IN; // Add the ripple reference to the list of all active ripples. this._activeRipples.add(rippleRef); if (!config.persistent) { this._mostRecentTransientRipple = rippleRef; } // Wait for the ripple element to be completely faded in. // Once it's faded in, the ripple can be hidden immediately if the mouse is released. this._runTimeoutOutsideZone((/** * @return {?} */ () => { /** @type {?} */ const isMostRecentTransientRipple = rippleRef === this._mostRecentTransientRipple; rippleRef.state = RippleState.VISIBLE; // When the timer runs out while the user has kept their pointer down, we want to // keep only the persistent ripples and the latest transient ripple. We do this, // because we don't want stacked transient ripples to appear after their enter // animation has finished. if (!config.persistent && (!isMostRecentTransientRipple || !this._isPointerDown)) { rippleRef.fadeOut(); } }), duration); return rippleRef; } /** * Fades out a ripple reference. * @param {?} rippleRef * @return {?} */ fadeOutRipple(rippleRef) { /** @type {?} */ const wasActive = this._activeRipples.delete(rippleRef); if (rippleRef === this._mostRecentTransientRipple) { this._mostRecentTransientRipple = null; } // Clear out the cached bounding rect if we have no more ripples. if (!this._activeRipples.size) { this._containerRect = null; } // For ripples that are not active anymore, don't re-run the fade-out animation. if (!wasActive) { return; } /** @type {?} */ const rippleEl = rippleRef.element; /** @type {?} */ const animationConfig = Object.assign({}, defaultRippleAnimationConfig, rippleRef.config.animation); rippleEl.style.transitionDuration = `${animationConfig.exitDuration}ms`; rippleEl.style.opacity = '0'; rippleRef.state = RippleState.FADING_OUT; // Once the ripple faded out, the ripple can be safely removed from the DOM. this._runTimeoutOutsideZone((/** * @return {?} */ () => { rippleRef.state = RippleState.HIDDEN; (/** @type {?} */ (rippleEl.parentNode)).removeChild(rippleEl); }), animationConfig.exitDuration); } /** * Fades out all currently active ripples. * @return {?} */ fadeOutAll() { this._activeRipples.forEach((/** * @param {?} ripple * @return {?} */ ripple => ripple.fadeOut())); } /** * Sets up the trigger event listeners * @param {?} element * @return {?} */ setupTriggerEvents(element) { if (!element || element === this._triggerElement) { return; } // Remove all previously registered event listeners from the trigger element. this._removeTriggerEvents(); this._ngZone.runOutsideAngular((/** * @return {?} */ () => { this._triggerEvents.forEach((/** * @param {?} fn * @param {?} type * @return {?} */ (fn, type) => { element.addEventListener(type, fn, passiveEventOptions); })); })); this._triggerElement = element; } /** * Runs a timeout outside of the Angular zone to avoid triggering the change detection. * @private * @param {?} fn * @param {?=} delay * @return {?} */ _runTimeoutOutsideZone(fn, delay = 0) { this._ngZone.runOutsideAngular((/** * @return {?} */ () => setTimeout(fn, delay))); } /** * Removes previously registered event listeners from the trigger element. * @return {?} */ _removeTriggerEvents() { if (this._triggerElement) { this._triggerEvents.forEach((/** * @param {?} fn * @param {?} type * @return {?} */ (fn, type) => { (/** @type {?} */ (this._triggerElement)).removeEventListener(type, fn, passiveEventOptions); })); } } } /** * Enforces a style recalculation of a DOM element by computing its styles. * @param {?} element * @return {?} */ function enforceStyleRecalculation(element) { // Enforce a style recalculation by calling `getComputedStyle` and accessing any property. // Calling `getPropertyValue` is important to let optimizers know that this is not a noop. // See: https://gist.github.com/paulirish/5d52fb081b3570c81e3a window.getComputedStyle(element).getPropertyValue('opacity'); } /** * Returns the distance from the point (x, y) to the furthest corner of a rectangle. * @param {?} x * @param {?} y * @param {?} rect * @return {?} */ function distanceToFurthestCorner(x, y, rect) { /** @type {?} */ const distX = Math.max(Math.abs(x - rect.left), Math.abs(x - rect.right)); /** @type {?} */ const distY = Math.max(Math.abs(y - rect.top), Math.abs(y - rect.bottom)); return Math.sqrt(distX * distX + distY * distY); } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Injection token that can be used to specify the global ripple options. * @type {?} */ const MAT_RIPPLE_GLOBAL_OPTIONS = new InjectionToken('mat-ripple-global-options'); class MatRipple { /** * @param {?} _elementRef * @param {?} ngZone * @param {?} platform * @param {?=} globalOptions * @param {?=} animationMode */ constructor(_elementRef, ngZone, platform, globalOptions, animationMode) { this._elementRef = _elementRef; /** * If set, the radius in pixels of foreground ripples when fully expanded. If unset, the radius * will be the distance from the center of the ripple to the furthest corner of the host element's * bounding rectangle. */ this.radius = 0; this._disabled = false; /** * Whether ripple directive is initialized and the input bindings are set. */ this._isInitialized = false; this._globalOptions = globalOptions || {}; this._rippleRenderer = new RippleRenderer(this, ngZone, _elementRef, platform); if (animationMode === 'NoopAnimations') { this._globalOptions.animation = { enterDuration: 0, exitDuration: 0 }; } } /** * Whether click events will not trigger the ripple. Ripples can be still launched manually * by using the `launch()` method. * @return {?} */ get disabled() { return this._disabled; } /** * @param {?} value * @return {?} */ set disabled(value) { this._disabled = value; this._setupTriggerEventsIfEnabled(); } /** * The element that triggers the ripple when click events are received. * Defaults to the directive's host element. * @return {?} */ get trigger() { return this._trigger || this._elementRef.nativeElement; } /** * @param {?} trigger * @return {?} */ set trigger(trigger) { this._trigger = trigger; this._setupTriggerEventsIfEnabled(); } /** * @return {?} */ ngOnInit() { this._isInitialized = true; this._setupTriggerEventsIfEnabled(); } /** * @return {?} */ ngOnDestroy() { this._rippleRenderer._removeTriggerEvents(); } /** * Fades out all currently showing ripple elements. * @return {?} */ fadeOutAll() { this._rippleRenderer.fadeOutAll(); } /** * Ripple configuration from the directive's input values. * \@docs-private Implemented as part of RippleTarget * @return {?} */ get rippleConfig() { return { centered: this.centered, radius: this.radius, color: this.color, animation: Object.assign({}, this._globalOptions.animation, this.animation), terminateOnPointerUp: this._globalOptions.terminateOnPointerUp, }; } /** * Whether ripples on pointer-down are disabled or not. * \@docs-private Implemented as part of RippleTarget * @return {?} */ get rippleDisabled() { return this.disabled || !!this._globalOptions.disabled; } /** * Sets up the trigger event listeners if ripples are enabled. * @private * @return {?} */ _setupTriggerEventsIfEnabled() { if (!this.disabled && this._isInitialized) { this._rippleRenderer.setupTriggerEvents(this.trigger); } } /** * Launches a manual ripple at the specified coordinated or just by the ripple config. * @param {?} configOrX * @param {?=} y * @param {?=} config * @return {?} */ launch(configOrX, y = 0, config) { if (typeof configOrX === 'number') { return this._rippleRenderer.fadeInRipple(configOrX, y, Object.assign({}, this.rippleConfig, config)); } else { return this._rippleRenderer.fadeInRipple(0, 0, Object.assign({}, this.rippleConfig, configOrX)); } } } MatRipple.decorators = [ { type: Directive, args: [{ selector: '[mat-ripple], [matRipple]', exportAs: 'matRipple', host: { 'class': 'mat-ripple', '[class.mat-ripple-unbounded]': 'unbounded' } },] }, ]; /** @nocollapse */ MatRipple.ctorParameters = () => [ { type: ElementRef }, { type: NgZone }, { type: Platform }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_RIPPLE_GLOBAL_OPTIONS,] }] }, { type: String, decorators: [{ type: Optional }, { type: Inject, args: [ANIMATION_MODULE_TYPE,] }] } ]; MatRipple.propDecorators = { color: [{ type: Input, args: ['matRippleColor',] }], unbounded: [{ type: Input, args: ['matRippleUnbounded',] }], centered: [{ type: Input, args: ['matRippleCentered',] }], radius: [{ type: Input, args: ['matRippleRadius',] }], animation: [{ type: Input, args: ['matRippleAnimation',] }], disabled: [{ type: Input, args: ['matRippleDisabled',] }], trigger: [{ type: Input, args: ['matRippleTrigger',] }] }; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class MatRippleModule { } MatRippleModule.decorators = [ { type: NgModule, args: [{ imports: [MatCommonModule, PlatformModule], exports: [MatRipple, MatCommonModule], declarations: [MatRipple], },] }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Component that shows a simplified checkbox without including any kind of "real" checkbox. * Meant to be used when the checkbox is purely decorative and a large number of them will be * included, such as for the options in a multi-select. Uses no SVGs or complex animations. * Note that theming is meant to be handled by the parent element, e.g. * `mat-primary .mat-pseudo-checkbox`. * * Note that this component will be completely invisible to screen-reader users. This is *not* * interchangeable with `<mat-checkbox>` and should *not* be used if the user would directly * interact with the checkbox. The pseudo-checkbox should only be used as an implementation detail * of more complex components that appropriately handle selected / checked state. * \@docs-private */ class MatPseudoCheckbox { /** * @param {?=} _animationMode */ constructor(_animationMode) { this._animationMode = _animationMode; /** * Display state of the checkbox. */ this.state = 'unchecked'; /** * Whether the checkbox is disabled. */ this.disabled = false; } } MatPseudoCheckbox.decorators = [ { type: Component, args: [{encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, selector: 'mat-pseudo-checkbox', styles: [".mat-pseudo-checkbox{width:16px;height:16px;border:2px solid;border-radius:2px;cursor:pointer;display:inline-block;vertical-align:middle;box-sizing:border-box;position:relative;flex-shrink:0;transition:border-color 90ms cubic-bezier(0,0,.2,.1),background-color 90ms cubic-bezier(0,0,.2,.1)}.mat-pseudo-checkbox::after{position:absolute;opacity:0;content:'';border-bottom:2px solid currentColor;transition:opacity 90ms cubic-bezier(0,0,.2,.1)}.mat-pseudo-checkbox.mat-pseudo-checkbox-checked,.mat-pseudo-checkbox.mat-pseudo-checkbox-indeterminate{border-color:transparent}._mat-animation-noopable.mat-pseudo-checkbox{transition:none;animation:none}._mat-animation-noopable.mat-pseudo-checkbox::after{transition:none}.mat-pseudo-checkbox-disabled{cursor:default}.mat-pseudo-checkbox-indeterminate::after{top:5px;left:1px;width:10px;opacity:1;border-radius:2px}.mat-pseudo-checkbox-checked::after{top:2.4px;left:1px;width:8px;height:3px;border-left:2px solid currentColor;transform:rotate(-45deg);opacity:1;box-sizing:content-box}"], template: '', host: { 'class': 'mat-pseudo-checkbox', '[class.mat-pseudo-checkbox-indeterminate]': 'state === "indeterminate"', '[class.mat-pseudo-checkbox-checked]': 'state === "checked"', '[class.mat-pseudo-checkbox-disabled]': 'disabled', '[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"', }, },] }, ]; /** @nocollapse */ MatPseudoCheckbox.ctorParameters = () => [ { type: String, decorators: [{ type: Optional }, { type: Inject, args: [ANIMATION_MODULE_TYPE,] }] } ]; MatPseudoCheckbox.propDecorators = { state: [{ type: Input }], disabled: [{ type: Input }] }; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class MatPseudoCheckboxModule { } MatPseudoCheckboxModule.decorators = [ { type: NgModule, args: [{ exports: [MatPseudoCheckbox], declarations: [MatPseudoCheckbox] },] }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ // Boilerplate for applying mixins to MatOptgroup. /** * \@docs-private */ class MatOptgroupBase { } /** @type {?} */ const _MatOptgroupMixinBase = mixinDisabled(MatOptgroupBase); // Counter for unique group ids. /** @type {?} */ let _uniqueOptgroupIdCounter = 0; /** * Component that is used to group instances of `mat-option`. */ class MatOptgroup extends _MatOptgroupMixinBase { constructor() { super(...arguments); /** * Unique id for the underlying label. */ this._labelId = `mat-optgroup-label-${_uniqueOptgroupIdCounter++}`; } } MatOptgroup.decorators = [ { type: Component, args: [{selector: 'mat-optgroup', exportAs: 'matOptgroup', template: "<label class=\"mat-optgroup-label\" [id]=\"_labelId\">{{ label }}<ng-content></ng-content></label><ng-content select=\"mat-option, ng-container\"></ng-content>", encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, inputs: ['disabled'], styles: [".mat-optgroup-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:default}.mat-optgroup-label[disabled]{cursor:default}[dir=rtl] .mat-optgroup-label{text-align:right}.mat-optgroup-label .mat-icon{margin-right:16px;vertical-align:middle}.mat-optgroup-label .mat-icon svg{vertical-align:top}[dir=rtl] .mat-optgroup-label .mat-icon{margin-left:16px;margin-right:0}"], host: { 'class': 'mat-optgroup', 'role': 'group', '[class.mat-optgroup-disabled]': 'disabled', '[attr.aria-disabled]': 'disabled.toString()', '[attr.aria-labelledby]': '_labelId', } },] }, ]; MatOptgroup.propDecorators = { label: [{ type: Input }] }; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Option IDs need to be unique across components, so this counter exists outside of * the component definition. * @type {?} */ let _uniqueIdCounter = 0; /** * Event object emitted by MatOption when selected or deselected. */ class MatOptionSelectionChange { /** * @param {?} source * @param {?=} isUserInput */ constructor(source, isUserInput = false) { this.source = source; this.isUserInput = isUserInput; } } /** * Injection token used to provide the parent component to options. * @type {?} */ const MAT_OPTION_PARENT_COMPONENT = new InjectionToken('MAT_OPTION_PARENT_COMPONENT'); /** * Single option inside of a `<mat-select>` element. */ class MatOption { /** * @param {?} _element * @param {?} _changeDetectorRef * @param {?} _parent * @param {?} group */ constructor(_element, _changeDetectorRef, _parent, group) { this._element = _element; this._changeDetectorRef = _changeDetectorRef; this._parent = _parent; this.group = group; this._selected = false; this._active = false; this._disabled = false; this._mostRecentViewValue = ''; /** * The unique ID of the option. */ this.id = `mat-option-${_uniqueIdCounter++}`; /** * Event emitted when the option is selected or deselected. */ // tslint:disable-next-line:no-output-on-prefix this.onSelectionChange = new EventEmitter(); /** * Emits when the state of the option changes and any parents have to be notified. */ this._stateChanges = new Subject(); } /** * Whether the wrapping component is in multiple selection mode. * @return {?} */ get multiple() { return this._parent && this._parent.multiple; } /** * Whether or not the option is currently selected. * @return {?} */ get selected() { return this._selected; } /** * Whether the option is disabled. * @return {?} */ get disabled() { return (this.group && this.group.disabled) || this._disabled; } /** * @param {?} value * @return {?} */ set disabled(value) { this._disabled = coerceBooleanProperty(value); } /** * Whether ripples for the option are disabled. * @return {?} */ get disableRipple() { return this._parent && this._parent.disableRipple; } /** * Whether or not the option is currently active and ready to be selected. * An active option displays styles as if it is focused, but the * focus is actually retained somewhere else. This comes in handy * for components like autocomplete where focus must remain on the input. * @return {?} */ get active() { return this._active; } /** * The displayed value of the option. It is necessary to show the selected option in the * select's trigger. * @return {?} */ get viewValue() { // TODO(kara): Add input property alternative for node envs. return (this._getHostElement().textContent || '').trim(); } /** * Selects the option. * @return {?} */ select() { if (!this._selected) { this._selected = true; this._changeDetectorRef.markForCheck(); this._emitSelectionChangeEvent(); } } /** * Deselects the option. * @return {?} */ deselect() { if (this._selected) { this._selected = false; this._changeDetectorRef.markForCheck(); this._emitSelectionChangeEvent(); } } /** * Sets focus onto this option. * @param {?=} _origin * @param {?=} options * @return {?} */ focus(_origin, options) { // Note that we aren't using `_origin`, but we need to keep it because some internal consumers // use `MatOption` in a `FocusKeyManager` and we need it to match `FocusableOption`. /** @type {?} */ const element = this._getHostElement(); if (typeof element.focus === 'function') { element.focus(options); } } /** * This method sets display styles on the option to make it appear * active. This is used by the ActiveDescendantKeyManager so key * events will display the proper options as active on arrow key events. * @return {?} */ setActiveStyles() { if (!this._active) { this._active = true; this._changeDetectorRef.markForCheck(); } } /** * This method removes display styles on the option that made it appear * active. This is used by the ActiveDescendantKeyManager so key * events will display the proper options as active on arrow key events. * @return {?} */ setInactiveStyles() { if (this._active) { this._active = false; this._changeDetectorRef.markForCheck(); } } /** * Gets the label to be used when determining whether the option should be focused. * @return {?} */ getLabel() { return this.viewValue; } /** * Ensures the option is selected when activated from the keyboard. * @param {?} event * @return {?} */ _handleKeydown(event) { if ((event.keyCode === ENTER || event.keyCode === SPACE) && !hasModifierKey(event)) { this._selectViaInteraction(); // Prevent the page from scrolling down and form submits. event.preventDefault(); } } /** * `Selects the option while indicating the selection came from the user. Used to * determine if the select's view -> model callback should be invoked.` * @return {?} */ _selectViaInteraction() { if (!this.disabled) { this._selected = this.multiple ? !this._selected : true; this._changeDetectorRef.markForCheck(); this._emitSelectionChangeEvent(true); } } /** * Gets the `aria-selected` value for the option. We explicitly omit the `aria-selected` * attribute from single-selection, unselected options. Including the `aria-selected="false"` * attributes adds a significant amount of noise to screen-reader users without providing useful * information. * @return {?} */ _getAriaSelected() { return this.selected || (this.multiple ? false : null); } /** * Returns the correct tabindex for the option depending on disabled state. * @return {?} */ _getTabIndex() { return this.disabled ? '-1' : '0'; } /** * Gets the host DOM element. * @return {?} */ _getHostElement() { return this._element.nativeElement; } /** * @return {?} */ ngAfterViewChecked() { // Since parent components could be using the option's label to display the selected values // (e.g. `mat-select`) and they don't have a way of knowing if the option's label has changed // we have to check for changes in the DOM ourselves and dispatch an event. These checks are // relatively cheap, however we still limit them only to selected options in order to avoid // hitting the DOM too often. if (this._selected) { /** @type {?} */ const viewValue = this.viewValue; if (viewValue !== this._mostRecentViewValue) { this._mostRecentViewValue = viewValue; this._stateChanges.next(); } } } /** * @return {?} */ ngOnDestroy() { this._stateChanges.complete(); } /** * Emits the selection change event. * @private * @param {?=} isUserInput * @return {?} */ _emitSelectionChangeEvent(isUserInput = false) { this.onSelectionChange.emit(new MatOptionSelectionChange(this, isUserInput)); } } MatOption.decorators = [ { type: Component, args: [{selector: 'mat-option', exportAs: 'matOption', host: { 'role': 'option', '[attr.tabindex]': '_getTabIndex()', '[class.mat-selected]': 'selected', '[class.mat-option-multiple]': 'multiple', '[class.mat-active]': 'active', '[id]': 'id', '[attr.aria-selected]': '_getAriaSelected()', '[attr.aria-disabled]': 'disabled.toString()', '[class.mat-option-disabled]': 'disabled', '(click)': '_selectViaInteraction()', '(keydown)': '_handleKeydown($event)', 'class': 'mat-option', }, styles: [".mat-option{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;position:relative;cursor:pointer;outline:0;display:flex;flex-direction:row;max-width:100%;box-sizing:border-box;align-items:center;-webkit-tap-highlight-color:transparent}.mat-option[disabled]{cursor:default}[dir=rtl] .mat-option{text-align:right}.mat-option .mat-icon{margin-right:16px;vertical-align:middle}.mat-option .mat-icon svg{vertical-align:top}[dir=rtl] .mat-option .mat-icon{margin-left:16px;margin-right:0}.mat-option[aria-disabled=true]{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:default}.mat-optgroup .mat-option:not(.mat-option-multiple){padding-left:32px}[dir=rtl] .mat-optgroup .mat-option:not(.mat-option-multiple){padding-left:16px;padding-right:32px}@media (-ms-high-contrast:active){.mat-option{margin:0 1px}.mat-option.mat-active{border:solid 1px currentColor;margin:0}}.mat-option-text{display:inline-block;flex-grow:1;overflow:hidden;text-overflow:ellipsis}.mat-option .mat-option-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}@media (-ms-high-contrast:active){.mat-option .mat-option-ripple{opacity:.5}}.mat-option-pseudo-checkbox{margin-right:8px}[dir=rtl] .mat-option-pseudo-checkbox{margin-left:8px;margin-right:0}"], template: "<mat-pseudo-checkbox *ngIf=\"multiple\" class=\"mat-option-pseudo-checkbox\" [state]=\"selected ? 'checked' : ''\" [disabled]=\"disabled\"></mat-pseudo-checkbox><span class=\"mat-option-text\"><ng-content></ng-content></span><div class=\"mat-option-ripple\" mat-ripple [matRippleTrigger]=\"_getHostElement()\" [matRippleDisabled]=\"disabled || disableRipple\"></div>", encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, },] }, ]; /** @nocollapse */ MatOption.ctorParameters = () => [ { type: ElementRef }, { type: ChangeDetectorRef }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_OPTION_PARENT_COMPONENT,] }] }, { type: MatOptgroup, decorators: [{ type: Optional }] } ]; MatOption.propDecorators = { value: [{ type: Input }], id: [{ type: Input }], disabled: [{ type: Input }], onSelectionChange: [{ type: Output }] }; /** * Counts the amount of option group labels that precede the specified option. * \@docs-private * @param {?} optionIndex Index of the option at which to start counting. * @param {?} options Flat list of all of the options. * @param {?} optionGroups Flat list of all of the option groups. * @return {?} */ function _countGroupLabelsBeforeOption(optionIndex, options, optionGroups) { if (optionGroups.length) { /** @type {?} */ let optionsArray = options.toArray(); /** @type {?} */ let groups = optionGroups.toArray(); /** @type {?} */ let groupCounter = 0; for (let i = 0; i < optionIndex + 1; i++) { if (optionsArray[i].group && optionsArray[i].group === groups[groupCounter]) { groupCounter++; } } return groupCounter; } return 0; } /** * Determines the position to which to scroll a panel in order for an option to be into view. * \@docs-private * @param {?} optionIndex Index of the option to be scrolled into the view. * @param {?} optionHeight Height of the options. * @param {?} currentScrollPosition Current scroll position of the panel. * @param {?} panelHeight Height of the panel. * @return {?} */ function _getOptionScrollPosition(optionIndex, optionHeight, currentScrollPosition, panelHeight) { /** @type {?} */ const optionOffset = optionIndex * optionHeight; if (optionOffset < currentScrollPosition) { return optionOffset; } if (optionOffset + optionHeight > currentScrollPosition + panelHeight) { return Math.max(0, optionOffset - panelHeight + optionHeight); } return currentScrollPosition; } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class MatOptionModule { } MatOptionModule.decorators = [ { type: NgModule, args: [{ imports: [MatRippleModule, CommonModule, MatPseudoCheckboxModule], exports: [MatOption, MatOptgroup], declarations: [MatOption, MatOptgroup] },] }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * InjectionToken that can be used to specify the global label options. * @type {?} */ const MAT_LABEL_GLOBAL_OPTIONS = new InjectionToken('mat-label-global-options'); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * When constructing a Date, the month is zero-based. This can be confusing, since people are * used to seeing them one-based. So we create these aliases to make writing the tests easier. * \@docs-private * \@breaking-change 8.0.0 Remove this with V8 since it was only targeted for testing. * @type {?} */ const JAN = 0; /** @type {?} */ const FEB = 1; /** @type {?} */ const MAR = 2; /** @type {?} */ const APR = 3; /** @type {?} */ const MAY = 4; /** @type {?} */ const JUN = 5; /** @type {?} */ const JUL = 6; /** @type {?} */ const AUG = 7; /** @type {?} */ const SEP = 8; /** @type {?} */ const OCT = 9; /** @type {?} */ const NOV = 10; /** @type {?} */ const DEC = 11; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ export { VERSION$1 as VERSION, AnimationCurves, AnimationDurations, MatCommonModule, MATERIAL_SANITY_CHECKS, mixinDisabled, mixinColor, mixinDisableRipple, mixinTabIndex, mixinErrorState, mixinInitialized, NativeDateModule, MatNativeDateModule, MAT_DATE_LOCALE_FACTORY, MAT_DATE_LOCALE, MAT_DATE_LOCALE_PROVIDER, DateAdapter, MAT_DATE_FORMATS, NativeDateAdapter, MAT_NATIVE_DATE_FORMATS, ShowOnDirtyErrorStateMatcher, ErrorStateMatcher, MAT_HAMMER_OPTIONS, GestureConfig, setLines, MatLine, MatLineSetter, MatLineModule, MatOptionModule, _countGroupLabelsBeforeOption, _getOptionScrollPosition, MatOptionSelectionChange, MAT_OPTION_PARENT_COMPONENT, MatOption, MatOptgroup, MAT_LABEL_GLOBAL_OPTIONS, MatRippleModule, MAT_RIPPLE_GLOBAL_OPTIONS, MatRipple, RippleState, RippleRef, defaultRippleAnimationConfig, RippleRenderer, MatPseudoCheckboxModule, MatPseudoCheckbox, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC, MATERIAL_SANITY_CHECKS_FACTORY as ɵa1 }; //# sourceMappingURL=core.js.map
/** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var d3 = require('d3'); var isNumeric = require('fast-isnumeric'); var hasHover = require('has-hover'); var Plotly = require('../plotly'); var Lib = require('../lib'); var Events = require('../lib/events'); var Queue = require('../lib/queue'); var Registry = require('../registry'); var PlotSchema = require('./plot_schema'); var Plots = require('../plots/plots'); var Polar = require('../plots/polar/legacy'); var initInteractions = require('../plots/cartesian/graph_interact'); var Drawing = require('../components/drawing'); var Color = require('../components/color'); var ErrorBars = require('../components/errorbars'); var xmlnsNamespaces = require('../constants/xmlns_namespaces'); var svgTextUtils = require('../lib/svg_text_utils'); var manageArrays = require('./manage_arrays'); var helpers = require('./helpers'); var subroutines = require('./subroutines'); var editTypes = require('./edit_types'); var cartesianConstants = require('../plots/cartesian/constants'); var axisConstraints = require('../plots/cartesian/constraints'); var enforceAxisConstraints = axisConstraints.enforce; var cleanAxisConstraints = axisConstraints.clean; var axisIds = require('../plots/cartesian/axis_ids'); /** * Main plot-creation function * * @param {string id or DOM element} gd * the id or DOM element of the graph container div * @param {array of objects} data * array of traces, containing the data and display information for each trace * @param {object} layout * object describing the overall display of the plot, * all the stuff that doesn't pertain to any individual trace * @param {object} config * configuration options (see ./plot_config.js for more info) * */ Plotly.plot = function(gd, data, layout, config) { var frames; gd = Lib.getGraphDiv(gd); // Events.init is idempotent and bails early if gd has already been init'd Events.init(gd); if(Lib.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; config = obj.config; frames = obj.frames; } var okToPlot = Events.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); if(okToPlot === false) return Promise.reject(); // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug if(!data && !layout && !Lib.isPlotDiv(gd)) { Lib.warn('Calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } function addFrames() { if(frames) { return Plotly.addFrames(gd, frames); } } // transfer configuration options to gd until we move over to // a more OO like model setPlotContext(gd, config); if(!layout) layout = {}; // hook class for plots main container (in case of plotly.js // this won't be #embedded-graph or .js-tab-contents) d3.select(gd).classed('js-plotly-plot', true); // off-screen getBoundingClientRect testing space, // in #js-plotly-tester (and stored as Drawing.tester) // so we can share cached text across tabs Drawing.makeTester(); // collect promises for any async actions during plotting // any part of the plotting code can push to gd._promises, then // before we move to the next step, we check that they're all // complete, and empty out the promise list again. if(!Array.isArray(gd._promises)) gd._promises = []; var graphWasEmpty = ((gd.data || []).length === 0 && Array.isArray(data)); // if there is already data on the graph, append the new data // if you only want to redraw, pass a non-array for data if(Array.isArray(data)) { helpers.cleanData(data, gd.data); if(graphWasEmpty) gd.data = data; else gd.data.push.apply(gd.data, data); // for routines outside graph_obj that want a clean tab // (rather than appending to an existing one) gd.empty // is used to determine whether to make a new tab gd.empty = false; } if(!gd.layout || graphWasEmpty) gd.layout = helpers.cleanLayout(layout); // if the user is trying to drag the axes, allow new data and layout // to come in but don't allow a replot. if(gd._dragging && !gd._transitioning) { // signal to drag handler that after everything else is done // we need to replot, because something has changed gd._replotPending = true; return Promise.reject(); } else { // we're going ahead with a replot now gd._replotPending = false; } Plots.supplyDefaults(gd); var fullLayout = gd._fullLayout; // Legacy polar plots if(!fullLayout._has('polar') && data && data[0] && data[0].r) { Lib.log('Legacy polar charts are deprecated!'); return plotPolar(gd, data, layout); } // so we don't try to re-call Plotly.plot from inside // legend and colorbar, if margins changed fullLayout._replotting = true; // make or remake the framework if we need to if(graphWasEmpty) makePlotFramework(gd); // polar need a different framework if(gd.framework !== makePlotFramework) { gd.framework = makePlotFramework; makePlotFramework(gd); } // clear gradient defs on each .plot call, because we know we'll loop through all traces Drawing.initGradients(gd); // save initial show spikes once per graph if(graphWasEmpty) Plotly.Axes.saveShowSpikeInitial(gd); // prepare the data and find the autorange // generate calcdata, if we need to // to force redoing calcdata, just delete it before calling Plotly.plot var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length; if(recalc) Plots.doCalcdata(gd); // in case it has changed, attach fullData traces to calcdata for(var i = 0; i < gd.calcdata.length; i++) { gd.calcdata[i][0].trace = gd._fullData[i]; } /* * start async-friendly code - now we're actually drawing things */ var oldmargins = JSON.stringify(fullLayout._size); // draw framework first so that margin-pushing // components can position themselves correctly function drawFramework() { var basePlotModules = fullLayout._basePlotModules; for(var i = 0; i < basePlotModules.length; i++) { if(basePlotModules[i].drawFramework) { basePlotModules[i].drawFramework(gd); } } if(!fullLayout._glcanvas && fullLayout._has('gl')) { fullLayout._glcanvas = fullLayout._glcontainer.selectAll('.gl-canvas').data([{ key: 'contextLayer', context: true, pick: false }, { key: 'focusLayer', context: false, pick: false }, { key: 'pickLayer', context: false, pick: true }], function(d) { return d.key; }); fullLayout._glcanvas.enter().append('canvas') .attr('class', function(d) { return 'gl-canvas gl-canvas-' + d.key.replace('Layer', ''); }) .style({ 'position': 'absolute', 'top': 0, 'left': 0, 'width': '100%', 'height': '100%', 'overflow': 'visible', 'pointer-events': 'none' }); } if(fullLayout._glcanvas) { fullLayout._glcanvas .attr('width', fullLayout.width) .attr('height', fullLayout.height); } return Lib.syncOrAsync([ subroutines.layoutStyles ], gd); } // draw anything that can affect margins. function marginPushers() { var calcdata = gd.calcdata; var i, cd, trace; Registry.getComponentMethod('legend', 'draw')(gd); Registry.getComponentMethod('rangeselector', 'draw')(gd); Registry.getComponentMethod('sliders', 'draw')(gd); Registry.getComponentMethod('updatemenus', 'draw')(gd); for(i = 0; i < calcdata.length; i++) { cd = calcdata[i]; trace = cd[0].trace; if(trace.visible !== true || !trace._module.colorbar) { Plots.autoMargin(gd, 'cb' + trace.uid); } else trace._module.colorbar(gd, cd); } Plots.doAutoMargin(gd); return Plots.previousPromises(gd); } // in case the margins changed, draw margin pushers again function marginPushersAgain() { if(JSON.stringify(fullLayout._size) === oldmargins) return; return Lib.syncOrAsync([ marginPushers, subroutines.layoutStyles ], gd); } function positionAndAutorange() { if(!recalc) { enforceAxisConstraints(gd); return; } var subplots = fullLayout._subplots.cartesian; var modules = fullLayout._modules; var setPositionsArray = []; // position and range calculations for traces that // depend on each other ie bars (stacked or grouped) // and boxes (grouped) push each other out of the way var subplotInfo, i, j; for(j = 0; j < modules.length; j++) { Lib.pushUnique(setPositionsArray, modules[j].setPositions); } if(setPositionsArray.length) { for(i = 0; i < subplots.length; i++) { subplotInfo = fullLayout._plots[subplots[i]]; for(j = 0; j < setPositionsArray.length; j++) { setPositionsArray[j](gd, subplotInfo); } } } // calc and autorange for errorbars ErrorBars.calc(gd); // TODO: autosize extra for text markers and images // see https://github.com/plotly/plotly.js/issues/1111 return Lib.syncOrAsync([ Registry.getComponentMethod('shapes', 'calcAutorange'), Registry.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints, Registry.getComponentMethod('rangeslider', 'calcAutorange') ], gd); } function doAutoRangeAndConstraints() { if(gd._transitioning) return; var axList = Plotly.Axes.list(gd, '', true); for(var i = 0; i < axList.length; i++) { var ax = axList[i]; cleanAxisConstraints(gd, ax); Plotly.Axes.doAutoRange(ax); } enforceAxisConstraints(gd); // store initial ranges *after* enforcing constraints, otherwise // we will never look like we're at the initial ranges if(graphWasEmpty) Plotly.Axes.saveRangeInitial(gd); } // draw ticks, titles, and calculate axis scaling (._b, ._m) function drawAxes() { return Plotly.Axes.doTicks(gd, 'redraw'); } // Now plot the data function drawData() { var calcdata = gd.calcdata, i, rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); // in case of traces that were heatmaps or contour maps // previously, remove them and their colorbars explicitly for(i = 0; i < calcdata.length; i++) { var trace = calcdata[i][0].trace, isVisible = (trace.visible === true), uid = trace.uid; if(!isVisible || !Registry.traceIs(trace, '2dMap')) { var query = ( '.hm' + uid + ',.contour' + uid + ',#clip' + uid ); fullLayout._paper .selectAll(query) .remove(); rangesliderContainers .selectAll(query) .remove(); } if(!isVisible || !trace._module.colorbar) { fullLayout._infolayer.selectAll('.cb' + uid).remove(); } } // loop over the base plot modules present on graph var basePlotModules = fullLayout._basePlotModules; for(i = 0; i < basePlotModules.length; i++) { basePlotModules[i].plot(gd); } // keep reference to shape layers in subplots var layerSubplot = fullLayout._paper.selectAll('.layer-subplot'); fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer'); // styling separate from drawing Plots.style(gd); // show annotations and shapes Registry.getComponentMethod('shapes', 'draw')(gd); Registry.getComponentMethod('annotations', 'draw')(gd); // source links Plots.addLinks(gd); // Mark the first render as complete fullLayout._replotting = false; return Plots.previousPromises(gd); } // An initial paint must be completed before these components can be // correctly sized and the whole plot re-margined. fullLayout._replotting must // be set to false before these will work properly. function finalDraw() { Registry.getComponentMethod('shapes', 'draw')(gd); Registry.getComponentMethod('images', 'draw')(gd); Registry.getComponentMethod('annotations', 'draw')(gd); Registry.getComponentMethod('legend', 'draw')(gd); Registry.getComponentMethod('rangeslider', 'draw')(gd); Registry.getComponentMethod('rangeselector', 'draw')(gd); Registry.getComponentMethod('sliders', 'draw')(gd); Registry.getComponentMethod('updatemenus', 'draw')(gd); } var seq = [ Plots.previousPromises, addFrames, drawFramework, marginPushers, marginPushersAgain, positionAndAutorange, subroutines.layoutStyles, drawAxes, drawData, finalDraw, initInteractions, Plots.rehover, Plots.previousPromises ]; // even if everything we did was synchronous, return a promise // so that the caller doesn't care which route we took var plotDone = Lib.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { gd.emit('plotly_afterplot'); return gd; }); }; function setBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } catch(e) { Lib.error(e); } } function opaqueSetBackground(gd, bgColor) { var blend = Color.combine(bgColor, 'white'); setBackground(gd, blend); } function setPlotContext(gd, config) { if(!gd._context) gd._context = Lib.extendDeep({}, Plotly.defaultConfig); var context = gd._context; var i, keys, key; if(config) { keys = Object.keys(config); for(i = 0; i < keys.length; i++) { key = keys[i]; if(key === 'editable' || key === 'edits') continue; if(key in context) { if(key === 'setBackground' && config[key] === 'opaque') { context[key] = opaqueSetBackground; } else { context[key] = config[key]; } } } // map plot3dPixelRatio to plotGlPixelRatio for backward compatibility if(config.plot3dPixelRatio && !context.plotGlPixelRatio) { context.plotGlPixelRatio = context.plot3dPixelRatio; } // now deal with editable and edits - first editable overrides // everything, then edits refines var editable = config.editable; if(editable !== undefined) { // we're not going to *use* context.editable, we're only going to // use context.edits... but keep it for the record context.editable = editable; keys = Object.keys(context.edits); for(i = 0; i < keys.length; i++) { context.edits[keys[i]] = editable; } } if(config.edits) { keys = Object.keys(config.edits); for(i = 0; i < keys.length; i++) { key = keys[i]; if(key in context.edits) { context.edits[key] = config.edits[key]; } } } } // staticPlot forces a bunch of others: if(context.staticPlot) { context.editable = false; context.edits = {}; context.autosizable = false; context.scrollZoom = false; context.doubleClick = false; context.showTips = false; context.showLink = false; context.displayModeBar = false; } // make sure hover-only devices have mode bar visible if(context.displayModeBar === 'hover' && !hasHover) { context.displayModeBar = true; } // default and fallback for setBackground if(context.setBackground === 'transparent' || typeof context.setBackground !== 'function') { context.setBackground = setBackground; } } function plotPolar(gd, data, layout) { // build or reuse the container skeleton var plotContainer = d3.select(gd).selectAll('.plot-container') .data([0]); plotContainer.enter() .insert('div', ':first-child') .classed('plot-container plotly', true); var paperDiv = plotContainer.selectAll('.svg-container') .data([0]); paperDiv.enter().append('div') .classed('svg-container', true) .style('position', 'relative'); // empty it everytime for now paperDiv.html(''); // fulfill gd requirements if(data) gd.data = data; if(layout) gd.layout = layout; Polar.manager.fillLayout(gd); // resize canvas paperDiv.style({ width: gd._fullLayout.width + 'px', height: gd._fullLayout.height + 'px' }); // instantiate framework gd.framework = Polar.manager.framework(gd); // plot gd.framework({data: gd.data, layout: gd.layout}, paperDiv.node()); // set undo point gd.framework.setUndoPoint(); // get the resulting svg for extending it var polarPlotSVG = gd.framework.svg(); // editable title var opacity = 1; var txt = gd._fullLayout.title; if(txt === '' || !txt) opacity = 0; var titleLayout = function() { this.call(svgTextUtils.convertToTspans, gd); // TODO: html/mathjax // TODO: center title }; var title = polarPlotSVG.select('.title-group text') .call(titleLayout); if(gd._context.edits.titleText) { var placeholderText = Lib._(gd, 'Click to enter Plot title'); if(!txt || txt === placeholderText) { opacity = 0.2; // placeholder is not going through convertToTspans // so needs explicit data-unformatted title.attr({'data-unformatted': placeholderText}) .text(placeholderText) .style({opacity: opacity}) .on('mouseover.opacity', function() { d3.select(this).transition().duration(100) .style('opacity', 1); }) .on('mouseout.opacity', function() { d3.select(this).transition().duration(1000) .style('opacity', 0); }); } var setContenteditable = function() { this.call(svgTextUtils.makeEditable, {gd: gd}) .on('edit', function(text) { gd.framework({layout: {title: text}}); this.text(text) .call(titleLayout); this.call(setContenteditable); }) .on('cancel', function() { var txt = this.attr('data-unformatted'); this.text(txt).call(titleLayout); }); }; title.call(setContenteditable); } gd._context.setBackground(gd, gd._fullLayout.paper_bgcolor); Plots.addLinks(gd); return Promise.resolve(); } // convenience function to force a full redraw, mostly for use by plotly.js Plotly.redraw = function(gd) { gd = Lib.getGraphDiv(gd); if(!Lib.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } helpers.cleanData(gd.data, gd.data); helpers.cleanLayout(gd.layout); gd.calcdata = undefined; return Plotly.plot(gd).then(function() { gd.emit('plotly_redraw'); return gd; }); }; /** * Convenience function to make idempotent plot option obvious to users. * * @param gd * @param {Object[]} data * @param {Object} layout * @param {Object} config */ Plotly.newPlot = function(gd, data, layout, config) { gd = Lib.getGraphDiv(gd); // remove gl contexts Plots.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {}); Plots.purge(gd); return Plotly.plot(gd, data, layout, config); }; /** * Wrap negative indicies to their positive counterparts. * * @param {Number[]} indices An array of indices * @param {Number} maxIndex The maximum index allowable (arr.length - 1) */ function positivifyIndices(indices, maxIndex) { var parentLength = maxIndex + 1, positiveIndices = [], i, index; for(i = 0; i < indices.length; i++) { index = indices[i]; if(index < 0) { positiveIndices.push(parentLength + index); } else { positiveIndices.push(index); } } return positiveIndices; } /** * Ensures that an index array for manipulating gd.data is valid. * * Intended for use with addTraces, deleteTraces, and moveTraces. * * @param gd * @param indices * @param arrayName */ function assertIndexArray(gd, indices, arrayName) { var i, index; for(i = 0; i < indices.length; i++) { index = indices[i]; // validate that indices are indeed integers if(index !== parseInt(index, 10)) { throw new Error('all values in ' + arrayName + ' must be integers'); } // check that all indices are in bounds for given gd.data array length if(index >= gd.data.length || index < -gd.data.length) { throw new Error(arrayName + ' must be valid indices for gd.data.'); } // check that indices aren't repeated if(indices.indexOf(index, i + 1) > -1 || index >= 0 && indices.indexOf(-gd.data.length + index) > -1 || index < 0 && indices.indexOf(gd.data.length + index) > -1) { throw new Error('each index in ' + arrayName + ' must be unique.'); } } } /** * Private function used by Plotly.moveTraces to check input args * * @param gd * @param currentIndices * @param newIndices */ function checkMoveTracesArgs(gd, currentIndices, newIndices) { // check that gd has attribute 'data' and 'data' is array if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array.'); } // validate currentIndices array if(typeof currentIndices === 'undefined') { throw new Error('currentIndices is a required argument.'); } else if(!Array.isArray(currentIndices)) { currentIndices = [currentIndices]; } assertIndexArray(gd, currentIndices, 'currentIndices'); // validate newIndices array if it exists if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) { newIndices = [newIndices]; } if(typeof newIndices !== 'undefined') { assertIndexArray(gd, newIndices, 'newIndices'); } // check currentIndices and newIndices are the same length if newIdices exists if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) { throw new Error('current and new indices must be of equal length.'); } } /** * A private function to reduce the type checking clutter in addTraces. * * @param gd * @param traces * @param newIndices */ function checkAddTracesArgs(gd, traces, newIndices) { var i, value; // check that gd has attribute 'data' and 'data' is array if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array.'); } // make sure traces exists if(typeof traces === 'undefined') { throw new Error('traces must be defined.'); } // make sure traces is an array if(!Array.isArray(traces)) { traces = [traces]; } // make sure each value in traces is an object for(i = 0; i < traces.length; i++) { value = traces[i]; if(typeof value !== 'object' || (Array.isArray(value) || value === null)) { throw new Error('all values in traces array must be non-array objects'); } } // make sure we have an index for each trace if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) { newIndices = [newIndices]; } if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) { throw new Error( 'if indices is specified, traces.length must equal indices.length' ); } } /** * A private function to reduce the type checking clutter in spliceTraces. * Get all update Properties from gd.data. Validate inputs and outputs. * Used by prependTrace and extendTraces * * @param gd * @param update * @param indices * @param maxPoints */ function assertExtendTracesArgs(gd, update, indices, maxPoints) { var maxPointsIsObject = Lib.isPlainObject(maxPoints); if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array'); } if(!Lib.isPlainObject(update)) { throw new Error('update must be a key:value object'); } if(typeof indices === 'undefined') { throw new Error('indices must be an integer or array of integers'); } assertIndexArray(gd, indices, 'indices'); for(var key in update) { /* * Verify that the attribute to be updated contains as many trace updates * as indices. Failure must result in throw and no-op */ if(!Array.isArray(update[key]) || update[key].length !== indices.length) { throw new Error('attribute ' + key + ' must be an array of length equal to indices array length'); } /* * if maxPoints is an object it must match keys and array lengths of 'update' 1:1 */ if(maxPointsIsObject && (!(key in maxPoints) || !Array.isArray(maxPoints[key]) || maxPoints[key].length !== update[key].length)) { throw new Error('when maxPoints is set as a key:value object it must contain a 1:1 ' + 'corrispondence with the keys and number of traces in the update object'); } } } /** * A private function to reduce the type checking clutter in spliceTraces. * * @param {Object|HTMLDivElement} gd * @param {Object} update * @param {Number[]} indices * @param {Number||Object} maxPoints * @return {Object[]} */ function getExtendProperties(gd, update, indices, maxPoints) { var maxPointsIsObject = Lib.isPlainObject(maxPoints), updateProps = []; var trace, target, prop, insert, maxp; // allow scalar index to represent a single trace position if(!Array.isArray(indices)) indices = [indices]; // negative indices are wrapped around to their positive value. Equivalent to python indexing. indices = positivifyIndices(indices, gd.data.length - 1); // loop through all update keys and traces and harvest validated data. for(var key in update) { for(var j = 0; j < indices.length; j++) { /* * Choose the trace indexed by the indices map argument and get the prop setter-getter * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; prop = Lib.nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" * Target must exist as an Array to allow the extend operation to be performed. */ target = prop.get(); insert = update[key][j]; if(!Array.isArray(insert)) { throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array'); } if(!Array.isArray(target)) { throw new Error('cannot extend missing or non-array attribute: ' + key); } /* * maxPoints may be an object map or a scalar. If object select the key:value, else * Use the scalar maxPoints for all key and trace combinations. */ maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints; // could have chosen null here, -1 just tells us to not take a window if(!isNumeric(maxp)) maxp = -1; /* * Wrap the nestedProperty in an object containing required data * for lengthening and windowing this particular trace - key combination. * Flooring maxp mirrors the behaviour of floats in the Array.slice JSnative function. */ updateProps.push({ prop: prop, target: target, insert: insert, maxp: Math.floor(maxp) }); } } // all target and insertion data now validated return updateProps; } /** * A private function to key Extend and Prepend traces DRY * * @param {Object|HTMLDivElement} gd * @param {Object} update * @param {Number[]} indices * @param {Number||Object} maxPoints * @param {Function} lengthenArray * @param {Function} spliceArray * @return {Object} */ function spliceTraces(gd, update, indices, maxPoints, lengthenArray, spliceArray) { assertExtendTracesArgs(gd, update, indices, maxPoints); var updateProps = getExtendProperties(gd, update, indices, maxPoints), remainder = [], undoUpdate = {}, undoPoints = {}; var target, prop, maxp; for(var i = 0; i < updateProps.length; i++) { /* * prop is the object returned by Lib.nestedProperties */ prop = updateProps[i].prop; maxp = updateProps[i].maxp; target = lengthenArray(updateProps[i].target, updateProps[i].insert); /* * If maxp is set within post-extension trace.length, splice to maxp length. * Otherwise skip function call as splice op will have no effect anyway. */ if(maxp >= 0 && maxp < target.length) remainder = spliceArray(target, maxp); /* * to reverse this operation we need the size of the original trace as the reverse * operation will need to window out any lengthening operation performed in this pass. */ maxp = updateProps[i].target.length; /* * Magic happens here! update gd.data.trace[key] with new array data. */ prop.set(target); if(!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = []; if(!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = []; /* * build the inverse update object for the undo operation */ undoUpdate[prop.astr].push(remainder); /* * build the matching maxPoints undo object containing original trace lengths. */ undoPoints[prop.astr].push(maxp); } return {update: undoUpdate, maxPoints: undoPoints}; } /** * extend && prepend traces at indices with update arrays, window trace lengths to maxPoints * * Extend and Prepend have identical APIs. Prepend inserts an array at the head while Extend * inserts an array off the tail. Prepend truncates the tail of the array - counting maxPoints * from the head, whereas Extend truncates the head of the array, counting backward maxPoints * from the tail. * * If maxPoints is undefined, nonNumeric, negative or greater than extended trace length no * truncation / windowing will be performed. If its zero, well the whole trace is truncated. * * @param {Object|HTMLDivElement} gd The graph div * @param {Object} update The key:array map of target attributes to extend * @param {Number|Number[]} indices The locations of traces to be extended * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening. * */ Plotly.extendTraces = function extendTraces(gd, update, indices, maxPoints) { gd = Lib.getGraphDiv(gd); var undo = spliceTraces(gd, update, indices, maxPoints, /* * The Lengthen operation extends trace from end with insert */ function(target, insert) { return target.concat(insert); }, /* * Window the trace keeping maxPoints, counting back from the end */ function(target, maxPoints) { return target.splice(0, target.length - maxPoints); }); var promise = Plotly.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; Queue.add(gd, Plotly.prependTraces, undoArgs, extendTraces, arguments); return promise; }; Plotly.prependTraces = function prependTraces(gd, update, indices, maxPoints) { gd = Lib.getGraphDiv(gd); var undo = spliceTraces(gd, update, indices, maxPoints, /* * The Lengthen operation extends trace by appending insert to start */ function(target, insert) { return insert.concat(target); }, /* * Window the trace keeping maxPoints, counting forward from the start */ function(target, maxPoints) { return target.splice(maxPoints, target.length); }); var promise = Plotly.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; Queue.add(gd, Plotly.extendTraces, undoArgs, prependTraces, arguments); return promise; }; /** * Add data traces to an existing graph div. * * @param {Object|HTMLDivElement} gd The graph div * @param {Object[]} gd.data The array of traces we're adding to * @param {Object[]|Object} traces The object or array of objects to add * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces * */ Plotly.addTraces = function addTraces(gd, traces, newIndices) { gd = Lib.getGraphDiv(gd); var currentIndices = [], undoFunc = Plotly.deleteTraces, redoFunc = addTraces, undoArgs = [gd, currentIndices], redoArgs = [gd, traces], // no newIndices here i, promise; // all validation is done elsewhere to remove clutter here checkAddTracesArgs(gd, traces, newIndices); // make sure traces is an array if(!Array.isArray(traces)) { traces = [traces]; } // make sure traces do not repeat existing ones traces = traces.map(function(trace) { return Lib.extendFlat({}, trace); }); helpers.cleanData(traces, gd.data); // add the traces to gd.data (no redrawing yet!) for(i = 0; i < traces.length; i++) { gd.data.push(traces[i]); } // to continue, we need to call moveTraces which requires currentIndices for(i = 0; i < traces.length; i++) { currentIndices.push(-traces.length + i); } // if the user didn't define newIndices, they just want the traces appended // i.e., we can simply redraw and be done if(typeof newIndices === 'undefined') { promise = Plotly.redraw(gd); Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; } // make sure indices is property defined if(!Array.isArray(newIndices)) { newIndices = [newIndices]; } try { // this is redundant, but necessary to not catch later possible errors! checkMoveTracesArgs(gd, currentIndices, newIndices); } catch(error) { // something went wrong, reset gd to be safe and rethrow error gd.data.splice(gd.data.length - traces.length, traces.length); throw error; } // if we're here, the user has defined specific places to place the new traces // this requires some extra work that moveTraces will do Queue.startSequence(gd); Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); promise = Plotly.moveTraces(gd, currentIndices, newIndices); Queue.stopSequence(gd); return promise; }; /** * Delete traces at `indices` from gd.data array. * * @param {Object|HTMLDivElement} gd The graph div * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} indices The indices */ Plotly.deleteTraces = function deleteTraces(gd, indices) { gd = Lib.getGraphDiv(gd); var traces = [], undoFunc = Plotly.addTraces, redoFunc = deleteTraces, undoArgs = [gd, traces, indices], redoArgs = [gd, indices], i, deletedTrace; // make sure indices are defined if(typeof indices === 'undefined') { throw new Error('indices must be an integer or array of integers.'); } else if(!Array.isArray(indices)) { indices = [indices]; } assertIndexArray(gd, indices, 'indices'); // convert negative indices to positive indices indices = positivifyIndices(indices, gd.data.length - 1); // we want descending here so that splicing later doesn't affect indexing indices.sort(Lib.sorterDes); for(i = 0; i < indices.length; i += 1) { deletedTrace = gd.data.splice(indices[i], 1)[0]; traces.push(deletedTrace); } var promise = Plotly.redraw(gd); Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; /** * Move traces at currentIndices array to locations in newIndices array. * * If newIndices is omitted, currentIndices will be moved to the end. E.g., * these are equivalent: * * Plotly.moveTraces(gd, [1, 2, 3], [-3, -2, -1]) * Plotly.moveTraces(gd, [1, 2, 3]) * * @param {Object|HTMLDivElement} gd The graph div * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} currentIndices The locations of traces to be moved * @param {Number|Number[]} [newIndices] The locations to move traces to * * Example calls: * * // move trace i to location x * Plotly.moveTraces(gd, i, x) * * // move trace i to end of array * Plotly.moveTraces(gd, i) * * // move traces i, j, k to end of array (i != j != k) * Plotly.moveTraces(gd, [i, j, k]) * * // move traces [i, j, k] to [x, y, z] (i != j != k) (x != y != z) * Plotly.moveTraces(gd, [i, j, k], [x, y, z]) * * // reorder all traces (assume there are 5--a, b, c, d, e) * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end' */ Plotly.moveTraces = function moveTraces(gd, currentIndices, newIndices) { gd = Lib.getGraphDiv(gd); var newData = [], movingTraceMap = [], undoFunc = moveTraces, redoFunc = moveTraces, undoArgs = [gd, newIndices, currentIndices], redoArgs = [gd, currentIndices, newIndices], i; // to reduce complexity here, check args elsewhere // this throws errors where appropriate checkMoveTracesArgs(gd, currentIndices, newIndices); // make sure currentIndices is an array currentIndices = Array.isArray(currentIndices) ? currentIndices : [currentIndices]; // if undefined, define newIndices to point to the end of gd.data array if(typeof newIndices === 'undefined') { newIndices = []; for(i = 0; i < currentIndices.length; i++) { newIndices.push(-currentIndices.length + i); } } // make sure newIndices is an array if it's user-defined newIndices = Array.isArray(newIndices) ? newIndices : [newIndices]; // convert negative indices to positive indices (they're the same length) currentIndices = positivifyIndices(currentIndices, gd.data.length - 1); newIndices = positivifyIndices(newIndices, gd.data.length - 1); // at this point, we've coerced the index arrays into predictable forms // get the traces that aren't being moved around for(i = 0; i < gd.data.length; i++) { // if index isn't in currentIndices, include it in ignored! if(currentIndices.indexOf(i) === -1) { newData.push(gd.data[i]); } } // get a mapping of indices to moving traces for(i = 0; i < currentIndices.length; i++) { movingTraceMap.push({newIndex: newIndices[i], trace: gd.data[currentIndices[i]]}); } // reorder this mapping by newIndex, ascending movingTraceMap.sort(function(a, b) { return a.newIndex - b.newIndex; }); // now, add the moving traces back in, in order! for(i = 0; i < movingTraceMap.length; i += 1) { newData.splice(movingTraceMap[i].newIndex, 0, movingTraceMap[i].trace); } gd.data = newData; var promise = Plotly.redraw(gd); Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; /** * restyle: update trace attributes of an existing plot * * Can be called two ways. * * Signature 1: * @param {String | HTMLDivElement} gd * the id or DOM element of the graph container div * @param {String} astr * attribute string (like `'marker.symbol'`) to update * @param {*} val * value to give this attribute * @param {Number[] | Number} [traces] * integer or array of integers for the traces to alter (all if omitted) * * Signature 2: * @param {String | HTMLDivElement} gd * (as in signature 1) * @param {Object} aobj * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously * @param {Number[] | Number} [traces] * (as in signature 1) * * `val` (or `val1`, `val2` ... in the object form) can be an array, * to apply different values to each trace. * * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ Plotly.restyle = function restyle(gd, astr, val, _traces) { gd = Lib.getGraphDiv(gd); helpers.clearPromiseQueue(gd); var aobj = {}; if(typeof astr === 'string') aobj[astr] = val; else if(Lib.isPlainObject(astr)) { // the 3-arg form aobj = Lib.extendFlat({}, astr); if(_traces === undefined) _traces = val; } else { Lib.warn('Restyle fail.', astr, val, _traces); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; var traces = helpers.coerceTraceIndices(gd, _traces); var specs = _restyle(gd, aobj, traces), flags = specs.flags; // clear calcdata and/or axis types if required so they get regenerated if(flags.clearCalc) gd.calcdata = undefined; if(flags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, {}); // fill in redraw sequence var seq = []; if(flags.fullReplot) { seq.push(Plotly.plot); } else { seq.push(Plots.previousPromises); Plots.supplyDefaults(gd); if(flags.style) seq.push(subroutines.doTraceStyle); if(flags.colorbars) seq.push(subroutines.doColorBars); } seq.push(Plots.rehover); Queue.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces] ); var plotDone = Lib.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { gd.emit('plotly_restyle', specs.eventData); return gd; }); }; // for undo: undefined initial vals must be turned into nulls // so that we unset rather than ignore them function undefinedToNull(val) { if(val === undefined) return null; return val; } function _restyle(gd, aobj, traces) { var fullLayout = gd._fullLayout, fullData = gd._fullData, data = gd.data, i; // initialize flags var flags = editTypes.traceFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue var redoit = {}, undoit = {}, axlist, flagAxForDelete = {}; // make a new empty vals array for undoit function a0() { return traces.map(function() { return undefined; }); } // for autoranging multiple axes function addToAxlist(axid) { var axName = Plotly.Axes.id2name(axid); if(axlist.indexOf(axName) === -1) axlist.push(axName); } function autorangeAttr(axName) { return 'LAYOUT' + axName + '.autorange'; } function rangeAttr(axName) { return 'LAYOUT' + axName + '.range'; } // for attrs that interact (like scales & autoscales), save the // old vals before making the change // val=undefined will not set a value, just record what the value was. // val=null will delete the attribute // attr can be an array to set several at once (all to the same val) function doextra(attr, val, i) { if(Array.isArray(attr)) { attr.forEach(function(a) { doextra(a, val, i); }); return; } // quit if explicitly setting this elsewhere if(attr in aobj || helpers.hasParent(aobj, attr)) return; var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { extraparam = Lib.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); } else { extraparam = Lib.nestedProperty(data[traces[i]], attr); } if(!(attr in undoit)) { undoit[attr] = a0(); } if(undoit[attr][i] === undefined) { undoit[attr][i] = undefinedToNull(extraparam.get()); } if(val !== undefined) { extraparam.set(val); } } // now make the changes to gd.data (and occasionally gd.layout) // and figure out what kind of graphics update we need to do for(var ai in aobj) { if(helpers.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } var vi = aobj[ai], cont, contFull, param, oldVal, newVal, valObject; redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { param = Lib.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless param.set(Array.isArray(vi) ? vi[0] : vi); // ironically, the layout attrs in restyle only require replot, // not relayout flags.calc = true; continue; } // set attribute in gd.data undoit[ai] = a0(); for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = fullData[traces[i]]; param = Lib.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; if(newVal === undefined) continue; valObject = PlotSchema.getTraceValObject(contFull, param.parts); if(valObject && valObject.impliedEdits && newVal !== null) { for(var impliedKey in valObject.impliedEdits) { doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); } } // changing colorbar size modes, // make the resulting size not change // note that colorbar fractional sizing is based on the // original plot size, before anything (like a colorbar) // increases the margins else if(ai === 'colorbar.thicknessmode' && param.get() !== newVal && ['fraction', 'pixels'].indexOf(newVal) !== -1 && contFull.colorbar) { var thicknorm = ['top', 'bottom'].indexOf(contFull.colorbar.orient) !== -1 ? (fullLayout.height - fullLayout.margin.t - fullLayout.margin.b) : (fullLayout.width - fullLayout.margin.l - fullLayout.margin.r); doextra('colorbar.thickness', contFull.colorbar.thickness * (newVal === 'fraction' ? 1 / thicknorm : thicknorm), i); } else if(ai === 'colorbar.lenmode' && param.get() !== newVal && ['fraction', 'pixels'].indexOf(newVal) !== -1 && contFull.colorbar) { var lennorm = ['top', 'bottom'].indexOf(contFull.colorbar.orient) !== -1 ? (fullLayout.width - fullLayout.margin.l - fullLayout.margin.r) : (fullLayout.height - fullLayout.margin.t - fullLayout.margin.b); doextra('colorbar.len', contFull.colorbar.len * (newVal === 'fraction' ? 1 / lennorm : lennorm), i); } else if(ai === 'colorbar.tick0' || ai === 'colorbar.dtick') { doextra('colorbar.tickmode', 'linear', i); } if(ai === 'type' && (newVal === 'pie') !== (oldVal === 'pie')) { var labelsTo = 'x', valuesTo = 'y'; if((newVal === 'bar' || oldVal === 'bar') && cont.orientation === 'h') { labelsTo = 'y'; valuesTo = 'x'; } Lib.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); Lib.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); Lib.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { Lib.nestedProperty(cont, 'marker.color') .set(Lib.nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); } else if(Registry.traceIs(cont, 'cartesian')) { Lib.nestedProperty(cont, 'marker.colors') .set(Lib.nestedProperty(cont, 'marker.color').get()); // look for axes that are no longer in use and delete them flagAxForDelete[cont.xaxis || 'x'] = true; flagAxForDelete[cont.yaxis || 'y'] = true; } } undoit[ai][i] = undefinedToNull(oldVal); // set the new value - if val is an array, it's one el per trace // first check for attributes that get more complex alterations var swapAttrs = [ 'swapxy', 'swapxyaxes', 'orientation', 'orientationaxes' ]; if(swapAttrs.indexOf(ai) !== -1) { // setting an orientation: make sure it's changing // before we swap everything else if(ai === 'orientation') { param.set(newVal); // obnoxious that we need this level of coupling... but in order to // properly handle setting orientation to `null` we need to mimic // the logic inside Bars.supplyDefaults for default orientation var defaultOrientation = (cont.x && !cont.y) ? 'h' : 'v'; if((param.get() || defaultOrientation) === contFull.orientation) { continue; } } // orientationaxes has no value, // it flips everything and the axes else if(ai === 'orientationaxes') { cont.orientation = {v: 'h', h: 'v'}[contFull.orientation]; } helpers.swapXYData(cont); flags.calc = flags.clearAxisTypes = true; } else if(Plots.dataArrayContainers.indexOf(param.parts[0]) !== -1) { // TODO: use manageArrays.applyContainerArrayChanges here too helpers.manageArrayContainers(param, newVal, undoit); flags.calc = true; } else { if(valObject) { // must redo calcdata when restyling array values of arrayOk attributes if(valObject.arrayOk && (Array.isArray(newVal) || Array.isArray(oldVal))) { flags.calc = true; } else editTypes.update(flags, valObject); } else { /* * if we couldn't find valObject, assume a full recalc. * This can happen if you're changing type and making * some other edits too, so the modules we're * looking at don't have these attributes in them. */ flags.calc = true; } // all the other ones, just modify that one attribute param.set(newVal); } } // swap the data attributes of the relevant x and y axes? if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) { Plotly.Axes.swap(gd, traces); } // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { var hovermode = Lib.nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { hovermode.set('x'); } } // major enough changes deserve autoscale, autobin, and // non-reversed axes so people don't get confused if(['orientation', 'type'].indexOf(ai) !== -1) { axlist = []; for(i = 0; i < traces.length; i++) { var trace = data[traces[i]]; if(Registry.traceIs(trace, 'cartesian')) { addToAxlist(trace.xaxis || 'x'); addToAxlist(trace.yaxis || 'y'); if(ai === 'type') { doextra(['autobinx', 'autobiny'], true, i); } } } doextra(axlist.map(autorangeAttr), true, 0); doextra(axlist.map(rangeAttr), [0, 1], 0); } } // do we need to force a recalc? var autorangeOn = false; var axList = Plotly.Axes.list(gd); for(i = 0; i < axList.length; i++) { if(axList[i].autorange) { autorangeOn = true; break; } } // check axes we've flagged for possible deletion // flagAxForDelete is a hash so we can make sure we only get each axis once var axListForDelete = Object.keys(flagAxForDelete); axisLoop: for(i = 0; i < axListForDelete.length; i++) { var axId = axListForDelete[i], axLetter = axId.charAt(0), axAttr = axLetter + 'axis'; for(var j = 0; j < data.length; j++) { if(Registry.traceIs(data[j], 'cartesian') && (data[j][axAttr] || axLetter) === axId) { continue axisLoop; } } // no data on this axis - delete it. doextra('LAYOUT' + Plotly.Axes.id2name(axId), null, 0); } // combine a few flags together; if(flags.calc || (flags.calcIfAutorange && autorangeOn)) { flags.clearCalc = true; } if(flags.calc || flags.plot || flags.calcIfAutorange) { flags.fullReplot = true; } return { flags: flags, undoit: undoit, redoit: redoit, traces: traces, eventData: Lib.extendDeepNoArrays([], [redoit, traces]) }; } /** * relayout: update layout attributes of an existing plot * * Can be called two ways: * * Signature 1: * @param {String | HTMLDivElement} gd * the id or dom element of the graph container div * @param {String} astr * attribute string (like `'xaxis.range[0]'`) to update * @param {*} val * value to give this attribute * * Signature 2: * @param {String | HTMLDivElement} gd * (as in signature 1) * @param {Object} aobj * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ Plotly.relayout = function relayout(gd, astr, val) { gd = Lib.getGraphDiv(gd); helpers.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } var aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; } else if(Lib.isPlainObject(astr)) { aobj = Lib.extendFlat({}, astr); } else { Lib.warn('Relayout fail.', astr, val); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; var specs = _relayout(gd, aobj), flags = specs.flags; // clear calcdata if required if(flags.calc) gd.calcdata = undefined; // fill in redraw sequence // even if we don't have anything left in aobj, // something may have happened within relayout that we // need to wait for var seq = [Plots.previousPromises]; if(flags.layoutReplot) { seq.push(subroutines.layoutReplot); } else if(Object.keys(aobj).length) { Plots.supplyDefaults(gd); if(flags.legend) seq.push(subroutines.doLegend); if(flags.layoutstyle) seq.push(subroutines.layoutStyles); if(flags.ticks) seq.push(subroutines.doTicksRelayout); if(flags.modebar) seq.push(subroutines.doModeBar); if(flags.camera) seq.push(subroutines.doCamera); } seq.push(Plots.rehover); Queue.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit] ); var plotDone = Lib.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { gd.emit('plotly_relayout', specs.eventData); return gd; }); }; function _relayout(gd, aobj) { var layout = gd.layout, fullLayout = gd._fullLayout, keys = Object.keys(aobj), axes = Plotly.Axes.list(gd), arrayEdits = {}, arrayStr, i, j; // look for 'allaxes', split out into all axes // in case of 3D the axis are nested within a scene which is held in _id for(i = 0; i < keys.length; i++) { if(keys[i].indexOf('allaxes') === 0) { for(j = 0; j < axes.length; j++) { var scene = axes[j]._id.substr(1), axisAttr = (scene.indexOf('scene') !== -1) ? (scene + '.') : '', newkey = keys[i].replace('allaxes', axisAttr + axes[j]._name); if(!aobj[newkey]) aobj[newkey] = aobj[keys[i]]; } delete aobj[keys[i]]; } } // initialize flags var flags = editTypes.layoutFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue var redoit = {}, undoit = {}; // for attrs that interact (like scales & autoscales), save the // old vals before making the change // val=undefined will not set a value, just record what the value was. // attr can be an array to set several at once (all to the same val) function doextra(attr, val) { if(Array.isArray(attr)) { attr.forEach(function(a) { doextra(a, val); }); return; } // if we have another value for this attribute (explicitly or // via a parent) do not override with this auto-generated extra if(attr in aobj || helpers.hasParent(aobj, attr)) return; var p = Lib.nestedProperty(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } if(val !== undefined) p.set(val); } // for editing annotations or shapes - is it on autoscaled axes? function refAutorange(obj, axLetter) { if(!Lib.isPlainObject(obj)) return false; var axRef = obj[axLetter + 'ref'] || axLetter, ax = Plotly.Axes.getFromId(gd, axRef); if(!ax && axRef.charAt(0) === axLetter) { // fall back on the primary axis in case we've referenced a // nonexistent axis (as we do above if axRef is missing). // This assumes the object defaults to data referenced, which // is the case for shapes and annotations but not for images. // The only thing this is used for is to determine whether to // do a full `recalc`, so the only ill effect of this error is // to waste some time. ax = Plotly.Axes.getFromId(gd, axLetter); } return (ax || {}).autorange; } // for constraint enforcement: keep track of all axes (as {id: name}) // we're editing the (auto)range of, so we can tell the others constrained // to scale with them that it's OK for them to shrink var rangesAltered = {}; var axId; function recordAlteredAxis(pleafPlus) { var axId = axisIds.name2id(pleafPlus.split('.')[0]); rangesAltered[axId] = 1; return axId; } // alter gd.layout for(var ai in aobj) { if(helpers.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } var p = Lib.nestedProperty(layout, ai), vi = aobj[ai], plen = p.parts.length, // p.parts may end with an index integer if the property is an array pend = typeof p.parts[plen - 1] === 'string' ? (plen - 1) : (plen - 2), // last property in chain (leaf node) pleaf = p.parts[pend], // leaf plus immediate parent pleafPlus = p.parts[pend - 1] + '.' + pleaf, // trunk nodes (everything except the leaf) ptrunk = p.parts.slice(0, pend).join('.'), parentIn = Lib.nestedProperty(gd.layout, ptrunk).get(), parentFull = Lib.nestedProperty(fullLayout, ptrunk).get(), vOld = p.get(); if(vi === undefined) continue; redoit[ai] = vi; // axis reverse is special - it is its own inverse // op and has no flag. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld); var valObject = PlotSchema.getLayoutValObject(fullLayout, p.parts); if(valObject && valObject.impliedEdits && vi !== null) { for(var impliedKey in valObject.impliedEdits) { doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); } } // Setting width or height to null must reset the graph's width / height // back to its initial value as computed during the first pass in Plots.plotAutoSize. // // To do so, we must manually set them back here using the _initialAutoSize cache. if(['width', 'height'].indexOf(ai) !== -1 && vi === null) { fullLayout[ai] = gd._initialAutoSize[ai]; } // check autorange vs range else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) { recordAlteredAxis(pleafPlus); Lib.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) { recordAlteredAxis(pleafPlus); Lib.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); var axFull = Lib.nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size axFull._input.domain = axFull._inputDomain.slice(); } } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) { Lib.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert // positions for components that are still using linearized values, // not data values like newer components. // previously we did this for log <-> not-log, but now only do it // for log <-> linear if(pleaf === 'type') { var ax = parentIn, toLog = parentFull.type === 'linear' && vi === 'log', fromLog = parentFull.type === 'log' && vi === 'linear'; if(toLog || fromLog) { if(!ax || !ax.range) { // 2D never gets here, but 3D does // I don't think this is needed, but left here in case there // are edge cases I'm not thinking of. doextra(ptrunk + '.autorange', true); } else if(!parentFull.autorange) { // toggling log without autorange: need to also recalculate ranges // because log axes use linearized values for range endpoints var r0 = ax.range[0], r1 = ax.range[1]; if(toLog) { // if both limits are negative, autorange if(r0 <= 0 && r1 <= 0) { doextra(ptrunk + '.autorange', true); } // if one is negative, set it 6 orders below the other. if(r0 <= 0) r0 = r1 / 1e6; else if(r1 <= 0) r1 = r0 / 1e6; // now set the range values as appropriate doextra(ptrunk + '.range[0]', Math.log(r0) / Math.LN10); doextra(ptrunk + '.range[1]', Math.log(r1) / Math.LN10); } else { doextra(ptrunk + '.range[0]', Math.pow(10, r0)); doextra(ptrunk + '.range[1]', Math.pow(10, r1)); } } else if(toLog) { // just make sure the range is positive and in the right // order, it'll get recalculated later ax.range = (ax.range[1] > ax.range[0]) ? [1, 2] : [2, 1]; } // clear polar view initial stash for radial range so that // value get recomputed in correct units if(Array.isArray(fullLayout._subplots.polar) && fullLayout._subplots.polar.length && fullLayout[p.parts[0]] && p.parts[1] === 'radialaxis' ) { delete fullLayout[p.parts[0]]._subplot.viewInitial['radialaxis.range']; } // Annotations and images also need to convert to/from linearized coords // Shapes do not need this :) Registry.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); Registry.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); } else { // any other type changes: the range from the previous type // will not make sense, so autorange it. doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } Lib.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleaf.match(cartesianConstants.AX_NAME_PATTERN)) { var fullProp = Lib.nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not // numeric (linear, because we don't auto-log) but the previous type // was log. That's a very strange edge case though if(!newType || newType === '-') newType = 'linear'; Registry.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); Registry.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); } // alter gd.layout // collect array component edits for execution all together // so we can ensure consistent behavior adding/removing items // and order-independence for add/remove/edit all together in // one relayout call var containerArrayMatch = manageArrays.containerArrayMatch(ai); if(containerArrayMatch) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; var componentArray = Lib.nestedProperty(layout, arrayStr); var obji = (componentArray || [])[i] || {}; var objToAutorange = obji; var updateValObject = valObject || {editType: 'calc'}; var checkForAutorange = updateValObject.editType.indexOf('calcIfAutorange') !== -1; if(i === '') { // replacing the entire array - too many possibilities, just recalc if(checkForAutorange) flags.calc = true; else editTypes.update(flags, updateValObject); checkForAutorange = false; // clear this, we're already doing a recalc } else if(propStr === '') { // special handling of undoit if we're adding or removing an element // ie 'annotations[2]' which can be {...} (add) or null (remove) objToAutorange = vi; if(manageArrays.isAddVal(vi)) { undoit[ai] = null; } else if(manageArrays.isRemoveVal(vi)) { undoit[ai] = obji; objToAutorange = obji; } else Lib.warn('unrecognized full object value', aobj); } if(checkForAutorange && (refAutorange(objToAutorange, 'x') || refAutorange(objToAutorange, 'y'))) { flags.calc = true; } else editTypes.update(flags, updateValObject); // prepare the edits object we'll send to applyContainerArrayChanges if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; var objEdits = arrayEdits[arrayStr][i]; if(!objEdits) objEdits = arrayEdits[arrayStr][i] = {}; objEdits[propStr] = vi; delete aobj[ai]; } // handle axis reversal explicitly, as there's no 'reverse' attribute else if(pleaf === 'reverse') { if(parentIn.range) parentIn.range.reverse(); else { doextra(ptrunk + '.autorange', true); parentIn.range = [1, 0]; } if(parentFull.autorange) flags.calc = true; else flags.plot = true; } else { if((fullLayout._has('gl2d') || fullLayout._has('regl')) && (ai === 'dragmode' && (vi === 'lasso' || vi === 'select') && !(vOld === 'lasso' || vOld === 'select')) ) { flags.calc = true; } else if(valObject) editTypes.update(flags, valObject); else flags.calc = true; p.set(vi); } } // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { var finished = manageArrays.applyContainerArrayChanges(gd, Lib.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } // figure out if we need to recalculate axis constraints var constraints = fullLayout._axisConstraintGroups || []; for(axId in rangesAltered) { for(i = 0; i < constraints.length; i++) { var group = constraints[i]; if(group[axId]) { // Always recalc if we're changing constrained ranges. // Otherwise it's possible to violate the constraints by // specifying arbitrary ranges for all axes in the group. // this way some ranges may expand beyond what's specified, // as they do at first draw, to satisfy the constraints. flags.calc = true; for(var groupAxId in group) { if(!rangesAltered[groupAxId]) { axisIds.getFromId(gd, groupAxId)._constraintShrinkable = true; } } } } } var oldWidth = fullLayout.width, oldHeight = fullLayout.height; // calculate autosizing if(gd.layout.autosize) Plots.plotAutoSize(gd, gd.layout, fullLayout); // avoid unnecessary redraws var hasSizechanged = aobj.height || aobj.width || (fullLayout.width !== oldWidth) || (fullLayout.height !== oldHeight); if(hasSizechanged) flags.calc = true; if(flags.plot || flags.calc) { flags.layoutReplot = true; } // now all attribute mods are done, as are // redo and undo so we can save them return { flags: flags, undoit: undoit, redoit: redoit, eventData: Lib.extendDeep({}, redoit) }; } /** * update: update trace and layout attributes of an existing plot * * @param {String | HTMLDivElement} gd * the id or DOM element of the graph container div * @param {Object} traceUpdate * attribute object `{astr1: val1, astr2: val2 ...}` * corresponding to updates in the plot's traces * @param {Object} layoutUpdate * attribute object `{astr1: val1, astr2: val2 ...}` * corresponding to updates in the plot's layout * @param {Number[] | Number} [traces] * integer or array of integers for the traces to alter (all if omitted) * */ Plotly.update = function update(gd, traceUpdate, layoutUpdate, _traces) { gd = Lib.getGraphDiv(gd); helpers.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } if(!Lib.isPlainObject(traceUpdate)) traceUpdate = {}; if(!Lib.isPlainObject(layoutUpdate)) layoutUpdate = {}; if(Object.keys(traceUpdate).length) gd.changed = true; if(Object.keys(layoutUpdate).length) gd.changed = true; var traces = helpers.coerceTraceIndices(gd, _traces); var restyleSpecs = _restyle(gd, Lib.extendFlat({}, traceUpdate), traces), restyleFlags = restyleSpecs.flags; var relayoutSpecs = _relayout(gd, Lib.extendFlat({}, layoutUpdate)), relayoutFlags = relayoutSpecs.flags; // clear calcdata and/or axis types if required if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined; if(restyleFlags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, layoutUpdate); // fill in redraw sequence var seq = []; if(restyleFlags.fullReplot && relayoutFlags.layoutReplot) { var data = gd.data, layout = gd.layout; // clear existing data/layout on gd // so that Plotly.plot doesn't try to extend them gd.data = undefined; gd.layout = undefined; seq.push(function() { return Plotly.plot(gd, data, layout); }); } else if(restyleFlags.fullReplot) { seq.push(Plotly.plot); } else if(relayoutFlags.layoutReplot) { seq.push(subroutines.layoutReplot); } else { seq.push(Plots.previousPromises); Plots.supplyDefaults(gd); if(restyleFlags.style) seq.push(subroutines.doTraceStyle); if(restyleFlags.colorbars) seq.push(subroutines.doColorBars); if(relayoutFlags.legend) seq.push(subroutines.doLegend); if(relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles); if(relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout); if(relayoutFlags.modebar) seq.push(subroutines.doModeBar); if(relayoutFlags.camera) seq.push(subroutines.doCamera); } seq.push(Plots.rehover); Queue.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] ); var plotDone = Lib.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { gd.emit('plotly_update', { data: restyleSpecs.eventData, layout: relayoutSpecs.eventData }); return gd; }); }; /** * Animate to a frame, sequence of frame, frame group, or frame definition * * @param {string id or DOM element} gd * the id or DOM element of the graph container div * * @param {string or object or array of strings or array of objects} frameOrGroupNameOrFrameList * a single frame, array of frames, or group to which to animate. The intent is * inferred by the type of the input. Valid inputs are: * * - string, e.g. 'groupname': animate all frames of a given `group` in the order * in which they are defined via `Plotly.addFrames`. * * - array of strings, e.g. ['frame1', frame2']: a list of frames by name to which * to animate in sequence * * - object: {data: ...}: a frame definition to which to animate. The frame is not * and does not need to be added via `Plotly.addFrames`. It may contain any of * the properties of a frame, including `data`, `layout`, and `traces`. The * frame is used as provided and does not use the `baseframe` property. * * - array of objects, e.g. [{data: ...}, {data: ...}]: a list of frame objects, * each following the same rules as a single `object`. * * @param {object} animationOpts * configuration for the animation */ Plotly.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { gd = Lib.getGraphDiv(gd); if(!Lib.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + 'https://plot.ly/javascript/animations/' ); } var trans = gd._transitionData; // This is the queue of frames that will be animated as soon as possible. They // are popped immediately upon the *start* of a transition: if(!trans._frameQueue) { trans._frameQueue = []; } animationOpts = Plots.supplyAnimationDefaults(animationOpts); var transitionOpts = animationOpts.transition; var frameOpts = animationOpts.frame; // Since frames are popped immediately, an empty queue only means all frames have // *started* to transition, not that the animation is complete. To solve that, // track a separate counter that increments at the same time as frames are added // to the queue, but decrements only when the transition is complete. if(trans._frameWaitingCnt === undefined) { trans._frameWaitingCnt = 0; } function getTransitionOpts(i) { if(Array.isArray(transitionOpts)) { if(i >= transitionOpts.length) { return transitionOpts[0]; } else { return transitionOpts[i]; } } else { return transitionOpts; } } function getFrameOpts(i) { if(Array.isArray(frameOpts)) { if(i >= frameOpts.length) { return frameOpts[0]; } else { return frameOpts[i]; } } else { return frameOpts; } } // Execute a callback after the wrapper function has been called n times. // This is used to defer the resolution until a transition has resovled *and* // the frame has completed. If it's not done this way, then we get a race // condition in which the animation might resolve before a transition is complete // or vice versa. function callbackOnNthTime(cb, n) { var cnt = 0; return function() { if(cb && ++cnt === n) { return cb(); } }; } return new Promise(function(resolve, reject) { function discardExistingFrames() { if(trans._frameQueue.length === 0) { return; } while(trans._frameQueue.length) { var next = trans._frameQueue.pop(); if(next.onInterrupt) { next.onInterrupt(); } } gd.emit('plotly_animationinterrupted', []); } function queueFrames(frameList) { if(frameList.length === 0) return; for(var i = 0; i < frameList.length; i++) { var computedFrame; if(frameList[i].type === 'byname') { // If it's a named frame, compute it: computedFrame = Plots.computeFrame(gd, frameList[i].name); } else { // Otherwise we must have been given a simple object, so treat // the input itself as the computed frame. computedFrame = frameList[i].data; } var frameOpts = getFrameOpts(i); var transitionOpts = getTransitionOpts(i); // It doesn't make much sense for the transition duration to be greater than // the frame duration, so limit it: transitionOpts.duration = Math.min(transitionOpts.duration, frameOpts.duration); var nextFrame = { frame: computedFrame, name: frameList[i].name, frameOpts: frameOpts, transitionOpts: transitionOpts, }; if(i === frameList.length - 1) { // The last frame in this .animate call stores the promise resolve // and reject callbacks. This is how we ensure that the animation // loop (which may exist as a result of a *different* .animate call) // still resolves or rejecdts this .animate call's promise. once it's // complete. nextFrame.onComplete = callbackOnNthTime(resolve, 2); nextFrame.onInterrupt = reject; } trans._frameQueue.push(nextFrame); } // Set it as never having transitioned to a frame. This will cause the animation // loop to immediately transition to the next frame (which, for immediate mode, // is the first frame in the list since all others would have been discarded // below) if(animationOpts.mode === 'immediate') { trans._lastFrameAt = -Infinity; } // Only it's not already running, start a RAF loop. This could be avoided in the // case that there's only one frame, but it significantly complicated the logic // and only sped things up by about 5% or so for a lorenz attractor simulation. // It would be a fine thing to implement, but the benefit of that optimization // doesn't seem worth the extra complexity. if(!trans._animationRaf) { beginAnimationLoop(); } } function stopAnimationLoop() { gd.emit('plotly_animated'); // Be sure to unset also since it's how we know whether a loop is already running: window.cancelAnimationFrame(trans._animationRaf); trans._animationRaf = null; } function nextFrame() { if(trans._currentFrame && trans._currentFrame.onComplete) { // Execute the callback and unset it to ensure it doesn't // accidentally get called twice trans._currentFrame.onComplete(); } var newFrame = trans._currentFrame = trans._frameQueue.shift(); if(newFrame) { // Since it's sometimes necessary to do deep digging into frame data, // we'll consider it not 100% impossible for nulls or numbers to sneak through, // so check when casting the name, just to be absolutely certain: var stringName = newFrame.name ? newFrame.name.toString() : null; gd._fullLayout._currentFrame = stringName; trans._lastFrameAt = Date.now(); trans._timeToNext = newFrame.frameOpts.duration; // This is simply called and it's left to .transition to decide how to manage // interrupting current transitions. That means we don't need to worry about // how it resolves or what happens after this: Plots.transition(gd, newFrame.frame.data, newFrame.frame.layout, helpers.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts ).then(function() { if(newFrame.onComplete) { newFrame.onComplete(); } }); gd.emit('plotly_animatingframe', { name: stringName, frame: newFrame.frame, animation: { frame: newFrame.frameOpts, transition: newFrame.transitionOpts, } }); } else { // If there are no more frames, then stop the RAF loop: stopAnimationLoop(); } } function beginAnimationLoop() { gd.emit('plotly_animating'); // If no timer is running, then set last frame = long ago so that the next // frame is immediately transitioned: trans._lastFrameAt = -Infinity; trans._timeToNext = 0; trans._runningTransitions = 0; trans._currentFrame = null; var doFrame = function() { // This *must* be requested before nextFrame since nextFrame may decide // to cancel it if there's nothing more to animated: trans._animationRaf = window.requestAnimationFrame(doFrame); // Check if we're ready for a new frame: if(Date.now() - trans._lastFrameAt > trans._timeToNext) { nextFrame(); } }; doFrame(); } // This is an animate-local counter that helps match up option input list // items with the particular frame. var configCounter = 0; function setTransitionConfig(frame) { if(Array.isArray(transitionOpts)) { if(configCounter >= transitionOpts.length) { frame.transitionOpts = transitionOpts[configCounter]; } else { frame.transitionOpts = transitionOpts[0]; } } else { frame.transitionOpts = transitionOpts; } configCounter++; return frame; } // Disambiguate what's sort of frames have been received var i, frame; var frameList = []; var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null; var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); var isSingleFrame = !allFrames && !isFrameArray && Lib.isPlainObject(frameOrGroupNameOrFrameList); if(isSingleFrame) { // In this case, a simple object has been passed to animate. frameList.push({ type: 'object', data: setTransitionConfig(Lib.extendFlat({}, frameOrGroupNameOrFrameList)) }); } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { // In this case, null or undefined has been passed so that we want to // animate *all* currently defined frames for(i = 0; i < trans._frames.length; i++) { frame = trans._frames[i]; if(!frame) continue; if(allFrames || String(frame.group) === String(frameOrGroupNameOrFrameList)) { frameList.push({ type: 'byname', name: String(frame.name), data: setTransitionConfig({name: frame.name}) }); } } } else if(isFrameArray) { for(i = 0; i < frameOrGroupNameOrFrameList.length; i++) { var frameOrName = frameOrGroupNameOrFrameList[i]; if(['number', 'string'].indexOf(typeof frameOrName) !== -1) { frameOrName = String(frameOrName); // In this case, there's an array and this frame is a string name: frameList.push({ type: 'byname', name: frameOrName, data: setTransitionConfig({name: frameOrName}) }); } else if(Lib.isPlainObject(frameOrName)) { frameList.push({ type: 'object', data: setTransitionConfig(Lib.extendFlat({}, frameOrName)) }); } } } // Verify that all of these frames actually exist; return and reject if not: for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) { Lib.warn('animate failure: frame not found: "' + frame.data.name + '"'); reject(); return; } } // If the mode is either next or immediate, then all currently queued frames must // be dumped and the corresponding .animate promises rejected. if(['next', 'immediate'].indexOf(animationOpts.mode) !== -1) { discardExistingFrames(); } if(animationOpts.direction === 'reverse') { frameList.reverse(); } var currentFrame = gd._fullLayout._currentFrame; if(currentFrame && animationOpts.fromcurrent) { var idx = -1; for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && frame.name === currentFrame) { idx = i; break; } } if(idx > 0 && idx < frameList.length - 1) { var filteredFrameList = []; for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frameList[i].type !== 'byname' || i > idx) { filteredFrameList.push(frame); } } frameList = filteredFrameList; } } if(frameList.length > 0) { queueFrames(frameList); } else { // This is the case where there were simply no frames. It's a little strange // since there's not much to do: gd.emit('plotly_animated'); resolve(); } }); }; /** * Register new frames * * @param {string id or DOM element} gd * the id or DOM element of the graph container div * * @param {array of objects} frameList * list of frame definitions, in which each object includes any of: * - name: {string} name of frame to add * - data: {array of objects} trace data * - layout {object} layout definition * - traces {array} trace indices * - baseframe {string} name of frame from which this frame gets defaults * * @param {array of integers) indices * an array of integer indices matching the respective frames in `frameList`. If not * provided, an index will be provided in serial order. If already used, the frame * will be overwritten. */ Plotly.addFrames = function(gd, frameList, indices) { gd = Lib.getGraphDiv(gd); var numericNameWarningCount = 0; if(frameList === null || frameList === undefined) { return Promise.resolve(); } if(!Lib.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + 'https://plot.ly/javascript/animations/' ); } var i, frame, j, idx; var _frames = gd._transitionData._frames; var _hash = gd._transitionData._frameHash; if(!Array.isArray(frameList)) { throw new Error('addFrames failure: frameList must be an Array of frame definitions' + frameList); } // Create a sorted list of insertions since we run into lots of problems if these // aren't in ascending order of index: // // Strictly for sorting. Make sure this is guaranteed to never collide with any // already-exisisting indices: var bigIndex = _frames.length + frameList.length * 2; var insertions = []; for(i = frameList.length - 1; i >= 0; i--) { if(!Lib.isPlainObject(frameList[i])) continue; var name = (_hash[frameList[i].name] || {}).name; var newName = frameList[i].name; if(name && newName && typeof newName === 'number' && _hash[name]) { numericNameWarningCount++; Lib.warn('addFrames: overwriting frame "' + _hash[name].name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.'); if(numericNameWarningCount > 5) { Lib.warn('addFrames: This API call has yielded too many warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.'); } } insertions.push({ frame: Plots.supplyFrameDefaults(frameList[i]), index: (indices && indices[i] !== undefined && indices[i] !== null) ? indices[i] : bigIndex + i }); } // Sort this, taking note that undefined insertions end up at the end: insertions.sort(function(a, b) { if(a.index > b.index) return -1; if(a.index < b.index) return 1; return 0; }); var ops = []; var revops = []; var frameCount = _frames.length; for(i = insertions.length - 1; i >= 0; i--) { frame = insertions[i].frame; if(typeof frame.name === 'number') { Lib.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings'); } if(!frame.name) { // Repeatedly assign a default name, incrementing the counter each time until // we get a name that's not in the hashed lookup table: while(_hash[(frame.name = 'frame ' + gd._transitionData._counter++)]); } if(_hash[frame.name]) { // If frame is present, overwrite its definition: for(j = 0; j < _frames.length; j++) { if((_frames[j] || {}).name === frame.name) break; } ops.push({type: 'replace', index: j, value: frame}); revops.unshift({type: 'replace', index: j, value: _frames[j]}); } else { // Otherwise insert it at the end of the list: idx = Math.max(0, Math.min(insertions[i].index, frameCount)); ops.push({type: 'insert', index: idx, value: frame}); revops.unshift({type: 'delete', index: idx}); frameCount++; } } var undoFunc = Plots.modifyFrames, redoFunc = Plots.modifyFrames, undoArgs = [gd, revops], redoArgs = [gd, ops]; if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return Plots.modifyFrames(gd, ops); }; /** * Delete frame * * @param {string id or DOM element} gd * the id or DOM element of the graph container div * * @param {array of integers} frameList * list of integer indices of frames to be deleted */ Plotly.deleteFrames = function(gd, frameList) { gd = Lib.getGraphDiv(gd); if(!Lib.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } var i, idx; var _frames = gd._transitionData._frames; var ops = []; var revops = []; if(!frameList) { frameList = []; for(i = 0; i < _frames.length; i++) { frameList.push(i); } } frameList = frameList.slice(0); frameList.sort(); for(i = frameList.length - 1; i >= 0; i--) { idx = frameList[i]; ops.push({type: 'delete', index: idx}); revops.unshift({type: 'insert', index: idx, value: _frames[idx]}); } var undoFunc = Plots.modifyFrames, redoFunc = Plots.modifyFrames, undoArgs = [gd, revops], redoArgs = [gd, ops]; if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return Plots.modifyFrames(gd, ops); }; /** * Purge a graph container div back to its initial pre-Plotly.plot state * * @param {string id or DOM element} gd * the id or DOM element of the graph container div */ Plotly.purge = function purge(gd) { gd = Lib.getGraphDiv(gd); var fullLayout = gd._fullLayout || {}, fullData = gd._fullData || []; // remove gl contexts Plots.cleanPlot([], {}, fullData, fullLayout); // purge properties Plots.purge(gd); // purge event emitter methods Events.purge(gd); // remove plot container if(fullLayout._container) fullLayout._container.remove(); // in contrast to Plotly.Plots.purge which does NOT clear _context! delete gd._context; return gd; }; // ------------------------------------------------------- // makePlotFramework: Create the plot container and axes // ------------------------------------------------------- function makePlotFramework(gd) { var gd3 = d3.select(gd); var fullLayout = gd._fullLayout; // Plot container fullLayout._container = gd3.selectAll('.plot-container').data([0]); fullLayout._container.enter().insert('div', ':first-child') .classed('plot-container', true) .classed('plotly', true); // Make the svg container fullLayout._paperdiv = fullLayout._container.selectAll('.svg-container').data([0]); fullLayout._paperdiv.enter().append('div') .classed('svg-container', true) .style('position', 'relative'); // Make the graph containers // start fresh each time we get here, so we know the order comes out // right, rather than enter/exit which can muck up the order // TODO: sort out all the ordering so we don't have to // explicitly delete anything // FIXME: parcoords reuses this object, not the best pattern fullLayout._glcontainer = fullLayout._paperdiv.selectAll('.gl-container') .data([{}]); fullLayout._glcontainer.enter().append('div') .classed('gl-container', true); // That is initialized in drawFramework if there are `gl` traces fullLayout._glcanvas = null; fullLayout._paperdiv.selectAll('.main-svg').remove(); fullLayout._paper = fullLayout._paperdiv.insert('svg', ':first-child') .classed('main-svg', true); fullLayout._toppaper = fullLayout._paperdiv.append('svg') .classed('main-svg', true); if(!fullLayout._uid) { var otherUids = []; d3.selectAll('defs').each(function() { if(this.id) otherUids.push(this.id.split('-')[1]); }); fullLayout._uid = Lib.randstr(otherUids); } fullLayout._paperdiv.selectAll('.main-svg') .attr(xmlnsNamespaces.svgAttrs); fullLayout._defs = fullLayout._paper.append('defs') .attr('id', 'defs-' + fullLayout._uid); fullLayout._clips = fullLayout._defs.append('g') .classed('clips', true); fullLayout._topdefs = fullLayout._toppaper.append('defs') .attr('id', 'topdefs-' + fullLayout._uid); fullLayout._topclips = fullLayout._topdefs.append('g') .classed('clips', true); fullLayout._bgLayer = fullLayout._paper.append('g') .classed('bglayer', true); fullLayout._draggers = fullLayout._paper.append('g') .classed('draglayer', true); // lower shape/image layer - note that this is behind // all subplots data/grids but above the backgrounds // except inset subplots, whose backgrounds are drawn // inside their own group so that they appear above // the data for the main subplot // lower shapes and images which are fully referenced to // a subplot still get drawn within the subplot's group // so they will work correctly on insets var layerBelow = fullLayout._paper.append('g') .classed('layer-below', true); fullLayout._imageLowerLayer = layerBelow.append('g') .classed('imagelayer', true); fullLayout._shapeLowerLayer = layerBelow.append('g') .classed('shapelayer', true); // single cartesian layer for the whole plot fullLayout._cartesianlayer = fullLayout._paper.append('g').classed('cartesianlayer', true); // single polar layer for the whole plot fullLayout._polarlayer = fullLayout._paper.append('g').classed('polarlayer', true); // single ternary layer for the whole plot fullLayout._ternarylayer = fullLayout._paper.append('g').classed('ternarylayer', true); // single geo layer for the whole plot fullLayout._geolayer = fullLayout._paper.append('g').classed('geolayer', true); // single pie layer for the whole plot fullLayout._pielayer = fullLayout._paper.append('g').classed('pielayer', true); // fill in image server scrape-svg fullLayout._glimages = fullLayout._paper.append('g').classed('glimages', true); // lastly upper shapes, info (legend, annotations) and hover layers go on top // these are in a different svg element normally, but get collapsed into a single // svg when exporting (after inserting 3D) // upper shapes/images are only those drawn above the whole plot, including subplots var layerAbove = fullLayout._toppaper.append('g') .classed('layer-above', true); fullLayout._imageUpperLayer = layerAbove.append('g') .classed('imagelayer', true); fullLayout._shapeUpperLayer = layerAbove.append('g') .classed('shapelayer', true); fullLayout._infolayer = fullLayout._toppaper.append('g').classed('infolayer', true); fullLayout._menulayer = fullLayout._toppaper.append('g').classed('menulayer', true); fullLayout._zoomlayer = fullLayout._toppaper.append('g').classed('zoomlayer', true); fullLayout._hoverlayer = fullLayout._toppaper.append('g').classed('hoverlayer', true); gd.emit('plotly_framework'); }
function equalNumber([arg1, arg2, arg3]) { let firstNumber = Number(arg1); let seconNumber = Number(arg2); let thirdNumber = Number(arg3); if (firstNumber == seconNumber && firstNumber == thirdNumber) { console.log("yes"); } else { console.log("no"); } } equalNumber(["3.2", "3.229888", "3.2"]); equalNumber(["13", "13", "13.0"]);
import unittest from os import path from parsers.miseq.parser import Parser from parsers.exceptions import DirectoryError, ValidationError, SampleSheetError import model path_to_module = path.abspath(path.dirname(__file__)) if len(path_to_module) == 0: path_to_module = '.' class TestFindRuns(unittest.TestCase): """ Test finding runs in a directory filled with (possible) run directories """ def setUp(self): print("\nStarting " + self.__module__ + ": " + self._testMethodName) def test_find_one_of_three(self): """ Given a directory with 3 potential run directories in it, determine which are new and invalid :return: """ directory = path.join(path_to_module, "three_dirs") dir_1 = path.join(directory, "first") dir_2 = path.join(directory, "second") dir_3 = path.join(directory, "third") correct_dirs = [dir_1, dir_2, dir_3] res = Parser.find_runs(directory) self.assertIn(res[0].directory, correct_dirs) self.assertIn(res[1].directory, correct_dirs) self.assertIn(res[2].directory, correct_dirs) for c_dir in res: if c_dir.directory == dir_1: self.assertEqual(c_dir.status, "new") elif c_dir.directory == dir_2: self.assertEqual(c_dir.status, "invalid") elif c_dir.directory == dir_3: self.assertEqual(c_dir.status, "invalid") def test_find_none(self): """ Given a directory with no run directories in it, return a empty list :return: """ directory = path.join(path_to_module, "no_dirs") res = Parser.find_runs(directory) self.assertEqual(res, []) class TestFindSingleRun(unittest.TestCase): """ Test checking if a single directory is a run """ def setUp(self): print("\nStarting " + self.__module__ + ": " + self._testMethodName) def test_find_in_dir_with_three_dirs(self): """ Given a directory with directories in it (but no actual run at highest level), show as invalid :return: """ directory = path.join(path_to_module, "three_dirs") res = Parser.find_single_run(directory) self.assertEqual(type(res), model.DirectoryStatus) self.assertEqual(res.status, "invalid") self.assertEqual(res.directory, directory) def test_find_none(self): """ Given a directory with nothing in it, show as invalid :return: """ directory = path.join(path_to_module, "no_dirs") res = Parser.find_single_run(directory) self.assertEqual(type(res), model.DirectoryStatus) self.assertEqual(res.status, "invalid") self.assertEqual(res.directory, directory) def test_find_dir(self): """ Given a valid run directory, show as new :return: """ directory = path.join(path_to_module, "three_dirs", "first") res = Parser.find_single_run(directory) self.assertEqual(type(res), model.DirectoryStatus) self.assertEqual(res.status, "new") self.assertEqual(res.directory, directory) def test_find_dir_no_completed_file(self): """ Given a run directory with no run completed file, show as invalid :return: """ directory = path.join(path_to_module, "fake_ngs_data_no_completed") res = Parser.find_single_run(directory) self.assertEqual(type(res), model.DirectoryStatus) self.assertEqual(res.status, "invalid") self.assertEqual(res.directory, directory) class TestGetSampleSheet(unittest.TestCase): """ Test cases related to getting a sample sheet from a known run directory """ def setUp(self): print("\nStarting " + self.__module__ + ": " + self._testMethodName) def test_valid_directory(self): """ test the file path of a valid sequencing run is gotten correctly :return: """ directory = path.join(path_to_module, "three_dirs", "first") file_path = path.join(directory, "SampleSheet.csv") res = Parser.get_sample_sheet(directory) self.assertEqual(res, file_path) def test_no_sheet_in_directory(self): """ Given an invalid directory, ensure an error is thrown :return: """ directory = path.join(path_to_module, "three_dirs", "third") with self.assertRaises(DirectoryError) as context: Parser.get_sample_sheet(directory) self.assertEqual(context.exception.directory, directory) def test_unreadable_directory(self): """ Given an invalid directory (chmod 000), ensure the correct error is thown :return: """ directory = path.join(path_to_module, "inaccessible_dir") with self.assertRaises(DirectoryError) as context: Parser.get_sample_sheet(directory) self.assertEqual(context.exception.directory, directory) class TestGetSequencingRun(unittest.TestCase): """ Test building a sequencing run from a sample sheet """ def setUp(self): print("\nStarting " + self.__module__ + ": " + self._testMethodName) def test_invalid_sample_sheets(self): """ Given an invalid sample sheet, ensure the correct errors are included in the validation result :return: """ sample_sheet = path.join(path_to_module, "invalid_sample_sheet", "SampleSheet.csv") with self.assertRaises(ValidationError) as context: Parser.get_sequencing_run(sample_sheet) validation_result = context.exception.validation_result self.assertEqual(type(validation_result), model.ValidationResult) for error in validation_result.error_list: self.assertEqual(type(error), SampleSheetError) def test_valid_run(self): """ Given a valid sample sheet, ensure a sequencing run is created :return: """ sample_sheet = path.join(path_to_module, "fake_ngs_data", "SampleSheet.csv") res = Parser.get_sequencing_run(sample_sheet) self.assertEqual(type(res), model.SequencingRun) class TestFindDirectoryList(unittest.TestCase): """ Test getting the list of directories """ def setUp(self): print("\nStarting " + self.__module__ + ": " + self._testMethodName) def test_find_three(self): """ Given a directory with 3 run directories in it, make sure all 3 directories are included in result :return: """ directory = path.join(path_to_module, "three_dirs") dir_1 = path.join(directory, "first") dir_2 = path.join(directory, "second") dir_3 = path.join(directory, "third") res = Parser._find_directory_list(directory) self.assertIn(dir_1, res) self.assertIn(dir_2, res) self.assertIn(dir_3, res) def test_find_none(self): """ Given a directory with no sequencing run directories in it, make sure an empty list is returned :return: """ directory = path.join(path_to_module, "no_dirs") res = Parser._find_directory_list(directory) self.assertEqual(res, [])
# -*- coding: utf-8 -*- # Copyright 2019 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from unittest.mock import Mock from signedjson import key, sign from signedjson.types import BaseKey, SigningKey from twisted.internet import defer from synapse.api.constants import RoomEncryptionAlgorithms from synapse.rest import admin from synapse.rest.client.v1 import login from synapse.types import JsonDict, ReadReceipt from tests.test_utils import make_awaitable from tests.unittest import HomeserverTestCase, override_config class FederationSenderReceiptsTestCases(HomeserverTestCase): def make_homeserver(self, reactor, clock): mock_state_handler = Mock(spec=["get_current_hosts_in_room"]) # Ensure a new Awaitable is created for each call. mock_state_handler.get_current_hosts_in_room.return_value = make_awaitable( ["test", "host2"] ) return self.setup_test_homeserver( state_handler=mock_state_handler, federation_transport_client=Mock(spec=["send_transaction"]), ) @override_config({"send_federation": True}) def test_send_receipts(self): mock_send_transaction = ( self.hs.get_federation_transport_client().send_transaction ) mock_send_transaction.return_value = make_awaitable({}) sender = self.hs.get_federation_sender() receipt = ReadReceipt( "room_id", "m.read", "user_id", ["event_id"], {"ts": 1234} ) self.successResultOf(defer.ensureDeferred(sender.send_read_receipt(receipt))) self.pump() # expect a call to send_transaction mock_send_transaction.assert_called_once() json_cb = mock_send_transaction.call_args[0][1] data = json_cb() self.assertEqual( data["edus"], [ { "edu_type": "m.receipt", "content": { "room_id": { "m.read": { "user_id": { "event_ids": ["event_id"], "data": {"ts": 1234}, } } } }, } ], ) @override_config({"send_federation": True}) def test_send_receipts_with_backoff(self): """Send two receipts in quick succession; the second should be flushed, but only after 20ms""" mock_send_transaction = ( self.hs.get_federation_transport_client().send_transaction ) mock_send_transaction.return_value = make_awaitable({}) sender = self.hs.get_federation_sender() receipt = ReadReceipt( "room_id", "m.read", "user_id", ["event_id"], {"ts": 1234} ) self.successResultOf(defer.ensureDeferred(sender.send_read_receipt(receipt))) self.pump() # expect a call to send_transaction mock_send_transaction.assert_called_once() json_cb = mock_send_transaction.call_args[0][1] data = json_cb() self.assertEqual( data["edus"], [ { "edu_type": "m.receipt", "content": { "room_id": { "m.read": { "user_id": { "event_ids": ["event_id"], "data": {"ts": 1234}, } } } }, } ], ) mock_send_transaction.reset_mock() # send the second RR receipt = ReadReceipt( "room_id", "m.read", "user_id", ["other_id"], {"ts": 1234} ) self.successResultOf(defer.ensureDeferred(sender.send_read_receipt(receipt))) self.pump() mock_send_transaction.assert_not_called() self.reactor.advance(19) mock_send_transaction.assert_not_called() self.reactor.advance(10) mock_send_transaction.assert_called_once() json_cb = mock_send_transaction.call_args[0][1] data = json_cb() self.assertEqual( data["edus"], [ { "edu_type": "m.receipt", "content": { "room_id": { "m.read": { "user_id": { "event_ids": ["other_id"], "data": {"ts": 1234}, } } } }, } ], ) class FederationSenderDevicesTestCases(HomeserverTestCase): servlets = [ admin.register_servlets, login.register_servlets, ] def make_homeserver(self, reactor, clock): return self.setup_test_homeserver( federation_transport_client=Mock(spec=["send_transaction"]), ) def default_config(self): c = super().default_config() c["send_federation"] = True return c def prepare(self, reactor, clock, hs): # stub out get_users_who_share_room_with_user so that it claims that # `@user2:host2` is in the room def get_users_who_share_room_with_user(user_id): return defer.succeed({"@user2:host2"}) hs.get_datastore().get_users_who_share_room_with_user = ( get_users_who_share_room_with_user ) # whenever send_transaction is called, record the edu data self.edus = [] self.hs.get_federation_transport_client().send_transaction.side_effect = ( self.record_transaction ) def record_transaction(self, txn, json_cb): data = json_cb() self.edus.extend(data["edus"]) return defer.succeed({}) def test_send_device_updates(self): """Basic case: each device update should result in an EDU""" # create a device u1 = self.register_user("user", "pass") self.login(u1, "pass", device_id="D1") # expect one edu self.assertEqual(len(self.edus), 1) stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", None) # a second call should produce no new device EDUs self.hs.get_federation_sender().send_device_messages("host2") self.pump() self.assertEqual(self.edus, []) # a second device self.login("user", "pass", device_id="D2") self.assertEqual(len(self.edus), 1) self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id) def test_upload_signatures(self): """Uploading signatures on some devices should produce updates for that user""" e2e_handler = self.hs.get_e2e_keys_handler() # register two devices u1 = self.register_user("user", "pass") self.login(u1, "pass", device_id="D1") self.login(u1, "pass", device_id="D2") # expect two edus self.assertEqual(len(self.edus), 2) stream_id = None stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", stream_id) stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id) # upload signing keys for each device device1_signing_key = self.generate_and_upload_device_signing_key(u1, "D1") device2_signing_key = self.generate_and_upload_device_signing_key(u1, "D2") # expect two more edus self.assertEqual(len(self.edus), 2) stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", stream_id) stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id) # upload master key and self-signing key master_signing_key = generate_self_id_key() master_key = { "user_id": u1, "usage": ["master"], "keys": {key_id(master_signing_key): encode_pubkey(master_signing_key)}, } # private key: HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8 selfsigning_signing_key = generate_self_id_key() selfsigning_key = { "user_id": u1, "usage": ["self_signing"], "keys": { key_id(selfsigning_signing_key): encode_pubkey(selfsigning_signing_key) }, } sign.sign_json(selfsigning_key, u1, master_signing_key) cross_signing_keys = { "master_key": master_key, "self_signing_key": selfsigning_key, } self.get_success( e2e_handler.upload_signing_keys_for_user(u1, cross_signing_keys) ) # expect signing key update edu self.assertEqual(len(self.edus), 1) self.assertEqual(self.edus.pop(0)["edu_type"], "org.matrix.signing_key_update") # sign the devices d1_json = build_device_dict(u1, "D1", device1_signing_key) sign.sign_json(d1_json, u1, selfsigning_signing_key) d2_json = build_device_dict(u1, "D2", device2_signing_key) sign.sign_json(d2_json, u1, selfsigning_signing_key) ret = self.get_success( e2e_handler.upload_signatures_for_device_keys( u1, {u1: {"D1": d1_json, "D2": d2_json}}, ) ) self.assertEqual(ret["failures"], {}) # expect two edus, in one or two transactions. We don't know what order the # devices will be updated. self.assertEqual(len(self.edus), 2) stream_id = None # FIXME: there is a discontinuity in the stream IDs: see #7142 for edu in self.edus: self.assertEqual(edu["edu_type"], "m.device_list_update") c = edu["content"] if stream_id is not None: self.assertEqual(c["prev_id"], [stream_id]) self.assertGreaterEqual(c["stream_id"], stream_id) stream_id = c["stream_id"] devices = {edu["content"]["device_id"] for edu in self.edus} self.assertEqual({"D1", "D2"}, devices) def test_delete_devices(self): """If devices are deleted, that should result in EDUs too""" # create devices u1 = self.register_user("user", "pass") self.login("user", "pass", device_id="D1") self.login("user", "pass", device_id="D2") self.login("user", "pass", device_id="D3") # expect three edus self.assertEqual(len(self.edus), 3) stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", None) stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id) stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D3", stream_id) # delete them again self.get_success( self.hs.get_device_handler().delete_devices(u1, ["D1", "D2", "D3"]) ) # expect three edus, in an unknown order self.assertEqual(len(self.edus), 3) for edu in self.edus: self.assertEqual(edu["edu_type"], "m.device_list_update") c = edu["content"] self.assertGreaterEqual( c.items(), {"user_id": u1, "prev_id": [stream_id], "deleted": True}.items(), ) self.assertGreaterEqual(c["stream_id"], stream_id) stream_id = c["stream_id"] devices = {edu["content"]["device_id"] for edu in self.edus} self.assertEqual({"D1", "D2", "D3"}, devices) def test_unreachable_server(self): """If the destination server is unreachable, all the updates should get sent on recovery """ mock_send_txn = self.hs.get_federation_transport_client().send_transaction mock_send_txn.side_effect = lambda t, cb: defer.fail("fail") # create devices u1 = self.register_user("user", "pass") self.login("user", "pass", device_id="D1") self.login("user", "pass", device_id="D2") self.login("user", "pass", device_id="D3") # delete them again self.get_success( self.hs.get_device_handler().delete_devices(u1, ["D1", "D2", "D3"]) ) self.assertGreaterEqual(mock_send_txn.call_count, 4) # recover the server mock_send_txn.side_effect = self.record_transaction self.hs.get_federation_sender().send_device_messages("host2") self.pump() # for each device, there should be a single update self.assertEqual(len(self.edus), 3) stream_id = None for edu in self.edus: self.assertEqual(edu["edu_type"], "m.device_list_update") c = edu["content"] self.assertEqual(c["prev_id"], [stream_id] if stream_id is not None else []) if stream_id is not None: self.assertGreaterEqual(c["stream_id"], stream_id) stream_id = c["stream_id"] devices = {edu["content"]["device_id"] for edu in self.edus} self.assertEqual({"D1", "D2", "D3"}, devices) def test_prune_outbound_device_pokes1(self): """If a destination is unreachable, and the updates are pruned, we should get a single update. This case tests the behaviour when the server has never been reachable. """ mock_send_txn = self.hs.get_federation_transport_client().send_transaction mock_send_txn.side_effect = lambda t, cb: defer.fail("fail") # create devices u1 = self.register_user("user", "pass") self.login("user", "pass", device_id="D1") self.login("user", "pass", device_id="D2") self.login("user", "pass", device_id="D3") # delete them again self.get_success( self.hs.get_device_handler().delete_devices(u1, ["D1", "D2", "D3"]) ) self.assertGreaterEqual(mock_send_txn.call_count, 4) # run the prune job self.reactor.advance(10) self.get_success( self.hs.get_datastore()._prune_old_outbound_device_pokes(prune_age=1) ) # recover the server mock_send_txn.side_effect = self.record_transaction self.hs.get_federation_sender().send_device_messages("host2") self.pump() # there should be a single update for this user. self.assertEqual(len(self.edus), 1) edu = self.edus.pop(0) self.assertEqual(edu["edu_type"], "m.device_list_update") c = edu["content"] # synapse uses an empty prev_id list to indicate "needs a full resync". self.assertEqual(c["prev_id"], []) def test_prune_outbound_device_pokes2(self): """If a destination is unreachable, and the updates are pruned, we should get a single update. This case tests the behaviour when the server was reachable, but then goes offline. """ # create first device u1 = self.register_user("user", "pass") self.login("user", "pass", device_id="D1") # expect the update EDU self.assertEqual(len(self.edus), 1) self.check_device_update_edu(self.edus.pop(0), u1, "D1", None) # now the server goes offline mock_send_txn = self.hs.get_federation_transport_client().send_transaction mock_send_txn.side_effect = lambda t, cb: defer.fail("fail") self.login("user", "pass", device_id="D2") self.login("user", "pass", device_id="D3") # delete them again self.get_success( self.hs.get_device_handler().delete_devices(u1, ["D1", "D2", "D3"]) ) self.assertGreaterEqual(mock_send_txn.call_count, 3) # run the prune job self.reactor.advance(10) self.get_success( self.hs.get_datastore()._prune_old_outbound_device_pokes(prune_age=1) ) # recover the server mock_send_txn.side_effect = self.record_transaction self.hs.get_federation_sender().send_device_messages("host2") self.pump() # ... and we should get a single update for this user. self.assertEqual(len(self.edus), 1) edu = self.edus.pop(0) self.assertEqual(edu["edu_type"], "m.device_list_update") c = edu["content"] # synapse uses an empty prev_id list to indicate "needs a full resync". self.assertEqual(c["prev_id"], []) def check_device_update_edu( self, edu: JsonDict, user_id: str, device_id: str, prev_stream_id: Optional[int], ) -> int: """Check that the given EDU is an update for the given device Returns the stream_id. """ self.assertEqual(edu["edu_type"], "m.device_list_update") content = edu["content"] expected = { "user_id": user_id, "device_id": device_id, "prev_id": [prev_stream_id] if prev_stream_id is not None else [], } self.assertLessEqual(expected.items(), content.items()) if prev_stream_id is not None: self.assertGreaterEqual(content["stream_id"], prev_stream_id) return content["stream_id"] def check_signing_key_update_txn( self, txn: JsonDict, ) -> None: """Check that the txn has an EDU with a signing key update.""" edus = txn["edus"] self.assertEqual(len(edus), 1) def generate_and_upload_device_signing_key( self, user_id: str, device_id: str ) -> SigningKey: """Generate a signing keypair for the given device, and upload it""" sk = key.generate_signing_key(device_id) device_dict = build_device_dict(user_id, device_id, sk) self.get_success( self.hs.get_e2e_keys_handler().upload_keys_for_user( user_id, device_id, {"device_keys": device_dict}, ) ) return sk def generate_self_id_key() -> SigningKey: """generate a signing key whose version is its public key ... as used by the cross-signing-keys. """ k = key.generate_signing_key("x") k.version = encode_pubkey(k) return k def key_id(k: BaseKey) -> str: return "%s:%s" % (k.alg, k.version) def encode_pubkey(sk: SigningKey) -> str: """Encode the public key corresponding to the given signing key as base64""" return key.encode_verify_key_base64(key.get_verify_key(sk)) def build_device_dict(user_id: str, device_id: str, sk: SigningKey): """Build a dict representing the given device""" return { "user_id": user_id, "device_id": device_id, "algorithms": [ "m.olm.curve25519-aes-sha2", RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2, ], "keys": { "curve25519:" + device_id: "curve25519+key", key_id(sk): encode_pubkey(sk), }, }
#pragma once #include "VaisseauLogique.h" #include <vector> #include <iostream> #include "Bonus.h" #include "Weapon.h" #include "BonusScatter.h" #include "BonusShield.h" #include "BonusLaserBeam.h" #include "BonusMissile.h" #include "Bombe.h" #include "BombeElectro.h" #include "Shield.h" #include "list.h" #include "Pile.h" #include "IObservateur.h" namespace tp3 { class Vaisseau : public VaisseauLogique , public IObservateur { public: Vaisseau(); virtual ~Vaisseau(); virtual void mouvement(int thrust); virtual void mouvementJoueur(Vector2i& mouvement); void notifier(Sujet* sujet); void monter(); void descendre(); void centrer(); void pivoter(); virtual void initGraphiques(); int direction = 1; int ptsVie = 10; Texture shield; Pile<Shield*> shields; bool canShoot = true; bool haveLaser = false; bool haveScatter = false; bool haveMissile = false; bool isPivoting; int munitionMissile = 0; int munitionScatter = 0; int munitionLaserbeam = 0; std::vector<Weapon*> weapons; int positionWeapon = 0; Weapon weapon; private: static const int OFFSET = 0; static const int CENTRE = 24; static const int LIMITE_DROITE_PIVOT = 74; static const int LIMITE_GAUCHE_PIVOT = 54; static const int LIMITE_BAS = 49; static const int LIMITE_HAUT = 0; static const int RHYTME_ANIM = 10; int image; IntRect rectangleAnimation; }; }
const Music = require('../../modules/music.js'); let { searchYoutube } = require('../../modules/youtube.js'); let dispatcher, videoUrl, youtube; module.exports = { name: 'playtop', description: 'Request the bot to play a song as the next song in the voice channel.', usage: '<song name or youtube video link>\n' + '**Examples**:\n' + 'IZ*ONE Violeta\n' + 'https://www.youtube.com/watch?v=6eEZ7DJMzuk\n', async execute(message, args) { if (!message.member.voiceChannel) { return message.reply('You need to join a voice channel first!'); } if (!args) { return message.reply('You need to provide the youtube link or music name that you want to play!'); } const permissions = message.member.voiceChannel.permissionsFor(message.client.user); if (!permissions.has('CONNECT')) { return message.reply('I cannot connect to your voice channel, make sure I have the proper permissions!'); } if (!permissions.has('SPEAK')) { return message.reply('I cannot speak in this voice channel, make sure I have the proper permissions!'); } connection = message.guild.voiceConnection; let guild_id = message.guild.id; let guild = global.guilds.get(guild_id) var queryString = args.join(' '); if (!connection) { connection = await message.member.voiceChannel.join(); message.reply('I have successfully connected to the channel!'); } dispatcher = message.guild.voiceConnection.dispatcher; if (!guild.playlist) { guild.playlist = new Array(); } videoUrl = queryString; youtube = Music.youtube; if (!queryString.match(/^https?:\/\/(www.youtube.com|youtube.com)/)) { return searchYoutube(queryString, message, "play"); } if (!dispatcher) { return Music.play(videoUrl, message); } if (dispatcher.paused) { dispatcher.resume(); return message.reply('Music Resumed!'); } Music.queueTop(videoUrl, message); } }
// Cannot implicitly shard accessed collections because of extra shard key index in sharded // collection. // @tags: [assumes_no_implicit_index_creation] t = db.text_blogwild; t.drop(); t.save({_id: 1, title: "my blog post", text: "this is a new blog i am writing. yay eliot"}); t.save({_id: 2, title: "my 2nd post", text: "this is a new blog i am writing. yay"}); t.save({ _id: 3, title: "knives are Fun for writing eliot", text: "this is a new blog i am writing. yay" }); // default weight is 1 // specify weights if you want a field to be more meaningull t.ensureIndex({dummy: "text"}, {weights: "$**"}); res = t.find({"$text": {"$search": "blog"}}); assert.eq(3, res.length(), "A1"); res = t.find({"$text": {"$search": "write"}}); assert.eq(3, res.length(), "B1"); // mixing t.dropIndex("dummy_text"); assert.eq(1, t.getIndexKeys().length, "C1"); t.ensureIndex({dummy: "text"}, {weights: {"$**": 1, title: 2}}); res = t.find({"$text": {"$search": "write"}}, {score: {"$meta": "textScore"}}).sort({ score: {"$meta": "textScore"} }); assert.eq(3, res.length(), "C2"); assert.eq(3, res[0]._id, "C3"); res = t.find({"$text": {"$search": "blog"}}, {score: {"$meta": "textScore"}}).sort({ score: {"$meta": "textScore"} }); assert.eq(3, res.length(), "D1"); assert.eq(1, res[0]._id, "D2"); res = t.find({"$text": {"$search": "eliot"}}, {score: {"$meta": "textScore"}}).sort({ score: {"$meta": "textScore"} }); assert.eq(2, res.length(), "E1"); assert.eq(3, res[0]._id, "E2");
import sqlite3 from datetime import datetime class DbApi: conn = None @staticmethod def connect(db_path): DbApi.conn = sqlite3.connect(db_path) @staticmethod def get_cursor(): return DbApi.conn.cursor() @staticmethod def close(): DbApi.conn.close() @staticmethod def add_new_call(_date, _phone_number, _talk_time, _call_status): query = f""" insert into Call_table(date, phone_number, talk_time, status) values ({_date}, {_phone_number}, {_talk_time}, {_call_status}) """ DbApi.get_cursor().execute(query) @staticmethod def get_calls_info_by_date(_date_start, _date_end): """_date_* - datetime object""" cursor = DbApi.get_cursor() date_start = _date_start.strftime('%Y-%m-%d') date_end = _date_end.strftime('%Y-%m-%d') last_date = DbApi.get_last_date() first_date = DbApi.get_first_date() if datetime.combine(_date_end, datetime.min.time()) < last_date: last_date = datetime.combine(_date_end, datetime.min.time()) if datetime.combine(_date_start, datetime.min.time()) > first_date: first_date = datetime.combine(_date_start, datetime.min.time()) day_count = last_date - first_date week_count = day_count.days // 7 if not day_count.days % 7 else day_count.days // 7 + 1 # strftime - первый день недели - воскресенье query = f""" select strftime('%w', date) WeekDayNumber, strftime('%H', date) HourNumber, count(id)/{week_count} from Call_table where (date BETWEEN '{date_start}' AND '{date_end}') group by WeekDayNumber, HourNumber """ cursor.execute(query) return cursor.fetchall() @staticmethod def get_first_date(): cursor = DbApi.get_cursor() query = f""" select date from Call_table order by id limit 1 """ cursor.execute(query) return datetime.strptime(cursor.fetchall()[0][0][:-10], '%Y-%m-%d %H:%M:%S') # [:-10] - срез точки и миллисекунд @staticmethod def get_last_date(): cursor = DbApi.get_cursor() query = f""" select date from Call_table order by id desc limit 1 """ cursor.execute(query) return datetime.strptime(cursor.fetchall()[0][0][:-10], '%Y-%m-%d %H:%M:%S') # [:-10] - срез точки и миллисекунд
/** * DO NOT EDIT THIS FILE as it will be overwritten by the Pbj compiler. * @link https://github.com/gdbots/pbjc-php * * Returns an array of curies using mixin "gdbots:pbjx:mixin:command:v1" * @link http://acme-schemas.gdbots.io/json-schema/gdbots/pbjx/mixin/command/1-0-3.json# */ export default [ 'acme:forms:command:send-submission:v1', 'acme:iam:command:patch-user:v1', 'acme:iam:command:patch-users:v1', 'gdbots:iam:command:grant-roles-to-app:v1', 'gdbots:iam:command:grant-roles-to-user:v1', 'gdbots:iam:command:revoke-roles-from-app:v1', 'gdbots:iam:command:revoke-roles-from-user:v1', 'gdbots:ncr:command:create-edge:v1', 'gdbots:ncr:command:create-node:v1', 'gdbots:ncr:command:delete-edge:v1', 'gdbots:ncr:command:delete-node:v1', 'gdbots:ncr:command:expire-node:v1', 'gdbots:ncr:command:lock-node:v1', 'gdbots:ncr:command:mark-node-as-draft:v1', 'gdbots:ncr:command:mark-node-as-pending:v1', 'gdbots:ncr:command:publish-node:v1', 'gdbots:ncr:command:rename-node:v1', 'gdbots:ncr:command:unlock-node:v1', 'gdbots:ncr:command:unpublish-node:v1', 'gdbots:ncr:command:update-node-labels:v1', 'gdbots:ncr:command:update-node-tags:v1', 'gdbots:ncr:command:update-node:v1', 'gdbots:pbjx:command:check-health:v1', ];
/** * Kendo UI v2020.2.617 (http://www.telerik.com/kendo-ui) * Copyright 2020 Progress Software Corporation and/or one of its subsidiaries or affiliates. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ !function(e){"function"==typeof define&&define.amd?define(["kendo.core.min"],e):e()}(function(){!function(e,d){kendo.cultures["es-HN"]={name:"es-HN",numberFormat:{pattern:["-n"],decimals:2,",":",",".":".",groupSize:[3],percent:{pattern:["-n %","n %"],decimals:2,",":",",".":".",groupSize:[3],symbol:"%"},currency:{name:"Honduran Lempira",abbr:"HNL",pattern:["-$n","$n"],decimals:2,",":",",".":".",groupSize:[3],symbol:"L"}},calendars:{standard:{days:{names:["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],namesAbbr:["dom.","lun.","mar.","mié.","jue.","vie.","sáb."],namesShort:["DO","LU","MA","MI","JU","VI","SA"]},months:{names:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],namesAbbr:["ene.","feb.","mar.","abr.","may.","jun.","jul.","ago.","sep.","oct.","nov.","dic."]},AM:["a.m.","a.m.","A.M."],PM:["p.m.","p.m.","P.M."],patterns:{d:"d/M/yyyy",D:"dddd dd 'de' MMMM 'de' yyyy",F:"dddd dd 'de' MMMM 'de' yyyy HH:mm:ss",g:"d/M/yyyy HH:mm",G:"d/M/yyyy HH:mm:ss",m:"d 'de' MMMM",M:"d 'de' MMMM",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"HH:mm",T:"HH:mm:ss",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"MMMM 'de' yyyy",Y:"MMMM 'de' yyyy"},"/":"/",":":":",firstDay:0}}}}(this)}); //# sourceMappingURL=kendo.culture.es-HN.min.js.map
'use strict'; var currCSSKey = 0; var allowedCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; /** * Get an unique CSS key for the className in a file. It supports up * to 140608 classNames. * * @return {string} */ function generateUniqueCSSClassName() { var allowedCharactersLength = allowedCharacters.length; var key1unit = allowedCharactersLength * allowedCharactersLength; var key1pos = Math.floor(currCSSKey / key1unit); var key1 = allowedCharacters[key1pos - 1]; var key2pos = Math.floor((currCSSKey - (key1 ? key1pos * key1unit : 0)) / allowedCharactersLength); var key2 = allowedCharacters[key2pos - 1]; var key3 = allowedCharacters[(currCSSKey - (key1 ? (key1pos * key1unit) : 0) - (key2 ? key2pos * allowedCharactersLength : 0))]; var key = ''; if (key1) { key += key1; } if (key2) { key += key2; } if (key3) { key += key3; } currCSSKey++; return key; } module.exports = generateUniqueCSSClassName;
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ """ Case Type : GUC Case Name : 修改block_size,观察预期结果; Description : 1、查询block_size默认值,show block_size; 2、修改block_size为4096,gs_guc set -D {cluster/dn1} -c "block_size=4096" 3、恢复默认值; Expect : 1、显示默认值 2、参数修改失败,固定参数,用户无法修改此参数; 3、恢复默认值成功 History : """ import unittest from testcase.utils.Logger import Logger from testcase.utils.Constant import Constant from testcase.utils.CommonSH import CommonSH logger = Logger() class GucTestCase(unittest.TestCase): def setUp(self): logger.info("===Opengauss_Function_Guc_Otheroptions_Case0006开始执行===") self.constant = Constant() self.commonsh = CommonSH('PrimaryDbUser') status = self.commonsh.get_db_cluster_status() self.assertTrue("Degraded" in status or "Normal" in status) def test_guc(self): logger.info("======查询block_size,默认值为8192======") sql_cmd = self.commonsh.execut_db_sql('''show block_size;''') logger.info(sql_cmd) self.assertEqual("8192", sql_cmd.split("\n")[-2].strip()) logger.info("======修改block_size为4096,期望:修改失败======") result = self.commonsh.execute_gsguc('set', self.constant.GSGUC_SUCCESS_MSG, "block_size=4096") self.assertFalse(result) def tearDown(self): logger.info("======No Need Clean && No Need Recovery======") logger.info("===Opengauss_Function_Guc_Otheroptions_Case0006执行结束===")
/** * \file rbtree_test.c * Tests for red-black tree. **/ #include "syscx.h" #include "alphatab.h" #include "associa.h" #include "lgtable.h" #include "rbtree.h" typedef struct TNode TNode; struct TNode { RBTNode rbt; const char* key; uint val; }; void lose_TNode (BSTNode* x) { TNode* a = CastUp( TNode, rbt, CastUp( RBTNode, bst, x ) ); a->key = 0; } static uint countup_black_RBTNode (const RBTNode* x) { uint n = 0; Claim( x->bst.joint ); do { n += (x->red ? 0 : 1); x = CastUp( RBTNode, bst, x->bst.joint ); } while (x->bst.joint); return n; } static void claim_TNode (BSTNode* x, void* args) { RBTNode* b = CastUp( RBTNode, bst, x ); uint* n = (uint*)((void**)args)[0]; uint* nblack = (uint*)((void**)args)[1]; *n += 1; Claim( x->joint ); Claim( x->joint ); Claim2( x ,==, x->joint->split[side_of_BSTNode (x)]); if (x->split[0]) Claim2( x ,==, x->split[0]->joint ); if (x->split[1]) Claim2( x ,==, x->split[1]->joint ); if (b->red) { b = CastUp( RBTNode, bst, x->joint ); Claim( !b->red ); } if (!x->split[0] || !x->split[1]) { uint c = countup_black_RBTNode (b); if (*nblack == UINT_MAX) *nblack = c; else Claim2( *nblack ,==, c ); } } static void claim_BSTree (BSTree* t, uint n_expect) { uint n_result; uint nblack = UINT_MAX; void* args[2]; args[0] = &n_result; args[1] = &nblack; n_result = 0; walk_BSTree (t, Yes, claim_TNode, args); Claim2( n_expect ,==, n_result ); n_result = 0; walk_BSTree (t, Nil, claim_TNode, args); Claim2( n_expect ,==, n_result ); n_result = 0; walk_BSTree (t, May, claim_TNode, args); Claim2( n_expect ,==, n_result ); } static void insert_TNode (RBTree* t, LgTable* lgt, const char* key, uint val, uint* n_expect) { TNode* a = (TNode*) take_LgTable (lgt); a->key = key; a->val = val; insert_RBTree (t, &a->rbt); *n_expect += 1; claim_BSTree (&t->bst, *n_expect); } void output_dot_fn (BSTNode* x, void* args) { TNode* a = CastUp( TNode, rbt, CastUp( RBTNode, bst, x ) ); FILE* out = (FILE*) ((void**)args)[0]; fprintf( out, "q%u [label = \"%s\", color = \"%s\"];\n", a->val, a->key, (a->rbt.red) ? "red" : "black"); if (x->joint) { TNode* b = CastUp( TNode, rbt, CastUp( RBTNode, bst, x->joint ) ); fprintf(out, "q%u -> q%u;\n", b->val, a->val); } fflush(out); } void output_dot (BSTree* t) { void* args[1]; FILE* out; out = fopen("out.dot", "wb"); if (!out) { fildesh_log_error("Cannot open out.dot for writing"); } args[0] = out; fputs("digraph tree {\n", out); output_dot_fn (t->sentinel, args); walk_BSTree (t, Yes, output_dot_fn, args); fputs("}\n", out); fclose(out); } static TNode* find_TNode (RBTree* t, const char* s) { BSTNode* x = find_BSTree (&t->bst, &s); if (!x) return 0; return CastUp( TNode, rbt, CastUp( RBTNode, bst, x ) ); } static void remove_TNode (RBTree* t, LgTable* lgt, const char* key, uint* n_expect) { TNode* a = find_TNode (t, key); Claim( a ); remove_RBTree (t, &a->rbt); lose_TNode (&a->rbt.bst); give_LgTable (lgt, a); *n_expect -= 1; claim_BSTree (&t->bst, *n_expect); } /** \test * Rigorously test red-black tree with different combinations of insert * and remove operations. * Set up and tear down a tree of 26 strings (ascii letters) in many different * orders. To ensure many orders, use sequential multiples of coprimes with 26 * to index the array of keys. * * Ex: The following sequence is generated from the first 26 multiples of 3.\n * 0 3 6 9 12 15 18 21 24 1 4 7 10 13 16 19 22 25 2 5 8 11 14 17 20 23 **/ void testfn_RBTree () { static const char* const keys[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; static const uint muls[] = { 1, 3, 5, 7, 9, 11, 15, 17, 19, 21 }; const uint nkeys = ArraySz( keys ); const uint nmuls = ArraySz( muls ); TNode sentinel; PosetCmp cmp = dflt3_PosetCmp (offsetof( TNode, rbt ), offsetof( TNode, key ), (PosetCmpFn) cmp_cstr_loc); DecloStack1( RBTree, t, dflt2_RBTree (&sentinel.rbt, cmp) ); DecloStack1( LgTable, lgt, dflt1_LgTable (sizeof(TNode)) ); uint n_expect = 0; uint mi, mj, i; sentinel.key = "sentinel"; sentinel.val = nkeys; UFor( mi, nmuls ) { UFor( mj, nmuls ) { UFor( i, nkeys ) { const uint idx = (muls[mi] * i) % nkeys; insert_TNode (t, lgt, keys[idx], idx, &n_expect); } #if 0 output_dot (&t->bst); #endif UFor( i, nkeys ) { const uint idx = (muls[mj] * i) % nkeys; remove_TNode (t, lgt, keys[idx], &n_expect); } } } lose_BSTree (&t->bst, lose_TNode); lose_LgTable (lgt); } /** \test * Test Associa structure. * \sa testfn_RBTree() **/ static void testfn_Associa () { static const char* const keys[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; static const uint muls[] = { 1, 3, 5, 7, 9, 11, 15, 17, 19, 21 }; const uint nkeys = ArraySz( keys ); const uint nmuls = ArraySz( muls ); Associa map[1]; uint n_expect = 1; /* Sentinel node.*/ uint mi, mj, i; InitAssocia( AlphaTab, uint, *map, cmp_AlphaTab ); Claim2( map->nodes.sz ,==, n_expect ); UFor( mi, nmuls ) { UFor( mj, nmuls ) { UFor( i, nkeys ) { const uint idx = (muls[mi] * i) % nkeys; const AlphaTab key = dflt1_AlphaTab (keys[idx]); if (mj % 2 == 0) { insert_Associa (map, &key, &idx); } else { bool added = false; Assoc* assoc = ensure1_Associa (map, &key, &added); Claim( added ); val_fo_Assoc (map, assoc, &idx); } ++ n_expect; Claim2( map->nodes.sz ,==, n_expect ); } UFor( i, nkeys ) { const uint idx = (muls[mj] * i) % nkeys; const AlphaTab key = dflt1_AlphaTab (keys[idx]); Assoc* a; if (mj % 2 == 0) { a = lookup_Associa (map, &key); } else { bool added = true; a = ensure1_Associa (map, &key, &added); Claim( !added ); } Claim( a ); { uint val = *(uint*) val_of_Assoc (map, a); Claim2( idx ,==, val ); } give_Associa (map, a); -- n_expect; Claim2( map->nodes.sz ,==, n_expect ); } } } /* Claim the sentinel still exists.*/ Claim2( map->nodes.sz ,==, 1 ); Claim2( n_expect ,==, 1 ); lose_Associa (map); } int main(int argc, char** argv) { (void) argc; (void) argv; init_sysCx(); testfn_RBTree(); testfn_Associa(); lose_sysCx (); return 0; }
'use strict'; import Search from '../Search'; const LIMIT_START_DEF_VALUE = 1; const LIMIT_SIZE_DEF_VALUE = 1000; /** * This is a abstract class. It is a base to make all kind of search request to OpenGate North API. */ export default class SearchBuilder { /** * @param {!InternalOpenGateAPI} parent - this is ogapi instance * @param {!object} routes - this defined the routes. One of those routes must be called on Builder before call build method. */ constructor(parent, routes, fieldFinder) { if (this.constructor === SearchBuilder) { throw new Error("Cannot construct Abstract instances directly"); } this._url = ''; this._fieldFinder = fieldFinder; this._parent = parent; this._routes = routes; this._routesName = []; this._builderParams = { summary: false, sort: [], filter: {}, limit: undefined, group: undefined, select: undefined }; for (let route in this._routes) { this._routesName.push(route); this._builderParams[route] = false; this[route] = (_route = route) => { this._builderParams[_route] = true; return this; }; } this._urlParams = {}; } /** * Return a promise which it will contains an array with fields recommended with only identifier * @return {Promise} */ findFields(input) { return this._fieldFinder.find(input); } /** * Return a promise which it will contains an array with fields recommended with complete structure * @return {Promise} */ findAllFields(input) { return this._fieldFinder.findAll(input); } /** * Return a promise which it will contains an string with the path of a field * @return {Promise} */ findFieldPath(field) { return this._fieldFinder.findFieldPath(field); } /** * The request will have a specific time out if it will be exceeded then the promise throw an exception * @example * ogapi.subscriptionsSearchBuilder().withTimeout(2000) * @param {number} ms - timeout in milliseconds * @return {SearchBuilder} */ withTimeout(ms = 2000) { if (typeof ms !== "number") throw new Error('Parameter ms must be a number'); this._builderParams.timeout = ms; return this; } /** * The search request will have this filter * @example * ogapi.subscriptionsSearchBuilder().filter( * ogapi.newFilterBuilder().and(Ex.like('prov.customid', 'SN32'), Ex.neq('entityId', '1124')) * ) // Setting FilterBuilder * ogapi.subscriptionsSearchBuilder().filter( * {"and": [{"like": {"entityId": "0000000000000001"}}]} * ) // Custom filter * @param {!(FilterBuilder|object)} filter * @return {SearchBuilder} */ filter(filter) { this._builderParams.filter = (filter || {}); return this; } /** * Add ascending param into the sort search object * @example * ogapi.subscriptionsSearchBuilder().addSortAscendingBy('prov.customid') // Order by prov.customid Ascending * @param {!string} filterField - This field must be allowed into the specific resource * @return {SearchBuilder} */ addSortAscendingBy(filterField) { const ASC = 'ASCENDING'; return this.addSortBy(filterField, ASC); } /** * Add descending param into the sort search object * @example * ogapi.communicationsModulesSearchBuilder().addSortDescendingBy('prov.customid') // Order by prov.customid Descending * @param {!string} filterField - This field must be allowed into the specific resource * @return {SearchBuilder} */ addSortDescendingBy(filterField) { const DESC = 'DESCENDING'; return this.addSortBy(filterField, DESC); } /** * Add ascending/descending param into the sort search object * @example * ogapi.subscriptionsSearchBuilder().addSortBy('prov.customid','ASCENDING') // Order by prov.customid Ascending * ogapi.communicationsModulesSearchBuilder().addSortBy('prov.customid','DESCENDING') // Order by prov.customid Descending * @param {!string} filterField - This field must be allowed into the specific resource * @param {!string} typeSort * @return {SearchBuilder} */ addSortBy(filterField, typeSort) { if (filterField && typeSort) { if (this._builderParams.sort.length > 0) { let ele = 0; let found = false; for (ele = 0; ele < this._builderParams.sort.length; ele++) { if (this._builderParams.sort[ele].name === filterField) { this._builderParams.sort[ele].type = typeSort; found = true; } } if (!found) this._builderParams.sort.push({ name: filterField, type: typeSort }); } else { this._builderParams.sort.push({ name: filterField, type: typeSort }); } } return this; } /** * Remove sort param from the search object * @example * ogapi.subscriptionsSearchBuilder().removeSortBy('prov.customid') // Remove order by prov.customid * ogapi.subscriptionsSearchBuilder().removeSortBy() // Remove all order by parameters * @param {string} filterField - This field must be allowed into the specific resource * @return {SearchBuilder} */ removeSortBy(filterField) { if (!filterField) { this._builderParams.sort = []; } else { if (this._builderParams.sort.length > 0) { let ele = 0; for (ele = 0; ele < this._builderParams.sort.length; ele++) { if (this._builderParams.sort[ele].name === filterField) { this._builderParams.sort.splice(ele, ele + 1); ele--; } } } } return this; } /** * Set reponse pagination. * @example * ogapi.subscribersSearchBuilder().limit(10) // Without offset * ogapi.subscribersSearchBuilder().limit(25,50) //With offset value 50 * @param {!number} size - Defined the number of elements on response * @param {number} [start=0] - Defined the offset on response * @return {SearchBuilder} */ limit(size, start = LIMIT_START_DEF_VALUE) { if (typeof size !== "number") throw new Error('size parameter must be a number'); if (typeof start !== "number" || start < 1) start = LIMIT_START_DEF_VALUE; this._builderParams.limit = { size: size, start: start }; return this; } /** * Build a instance of Search * * @example * ogapi.devicesSearchBuilder().onProvisioned().build() * @throws {SearchBuilderError} Throw error on url build * @return {Search} */ build() { return new Search(this._parent, this._buildUrl(), this._buildFilter(), this._buildLimit(), this._buildSort(), this._buildGroup(), this._buildSelect(), this._builderParams.timeout, this._urlParams); } _buildFilter() { let filter = this._builderParams.filter; if (typeof filter._filterTemplate !== "undefined") return filter._filterTemplate; return { filter: filter }; } _buildSelect() { let select = this._builderParams.select; if (typeof select !== "undefined" && typeof select._selectTemplate !== "undefined") return select._selectTemplate; return { select: select }; } _buildGroup() { let group = this._builderParams.group; if (typeof group !== "undefined" && typeof group._groupTemplate !== "undefined") return group._groupTemplate; return { group: group }; } _buildLimit() { if (typeof this._builderParams.limit === "undefined") return { limit: { size: LIMIT_SIZE_DEF_VALUE, start: LIMIT_START_DEF_VALUE } }; return { limit: this._builderParams.limit }; } _buildSort() { if (this._builderParams.sort.length === 0) return undefined; return { sort: { parameters: this._builderParams.sort } }; } _buildUrl() { if (typeof this._url !== "string" || this._url.trim().length === 0) throw new Error('Error on extends SearchBuilder, this._url is not defined.'); return this._url; } _checkConstraintRoutes(isMultipleRouteEnabled = false) { let atLeastOneTrue = false; for (let route in this._routes) { if (atLeastOneTrue && this._builderParams[route] && !isMultipleRouteEnabled) { throw new Error("Must select only one of this:" + JSON.stringify(this._routesName)); } atLeastOneTrue = atLeastOneTrue || this._builderParams[route]; } if (!atLeastOneTrue) throw new Error('Must select one at least: ' + JSON.stringify(this._routesName)); } }
def large_sum(): nums = [37107287533902102798797998220837590246510135740250, 46376937677490009712648124896970078050417018260538, 74324986199524741059474233309513058123726617309629, 91942213363574161572522430563301811072406154908250, 23067588207539346171171980310421047513778063246676, 89261670696623633820136378418383684178734361726757, 28112879812849979408065481931592621691275889832738, 44274228917432520321923589422876796487670272189318, 47451445736001306439091167216856844588711603153276, 70386486105843025439939619828917593665686757934951, 62176457141856560629502157223196586755079324193331, 64906352462741904929101432445813822663347944758178, 92575867718337217661963751590579239728245598838407, 58203565325359399008402633568948830189458628227828, 80181199384826282014278194139940567587151170094390, 35398664372827112653829987240784473053190104293586, 86515506006295864861532075273371959191420517255829, 71693888707715466499115593487603532921714970056938, 54370070576826684624621495650076471787294438377604, 53282654108756828443191190634694037855217779295145, 36123272525000296071075082563815656710885258350721, 45876576172410976447339110607218265236877223636045, 17423706905851860660448207621209813287860733969412, 81142660418086830619328460811191061556940512689692, 51934325451728388641918047049293215058642563049483, 62467221648435076201727918039944693004732956340691, 15732444386908125794514089057706229429197107928209, 55037687525678773091862540744969844508330393682126, 18336384825330154686196124348767681297534375946515, 80386287592878490201521685554828717201219257766954, 78182833757993103614740356856449095527097864797581, 16726320100436897842553539920931837441497806860984, 48403098129077791799088218795327364475675590848030, 87086987551392711854517078544161852424320693150332, 59959406895756536782107074926966537676326235447210, 69793950679652694742597709739166693763042633987085, 41052684708299085211399427365734116182760315001271, 65378607361501080857009149939512557028198746004375, 35829035317434717326932123578154982629742552737307, 94953759765105305946966067683156574377167401875275, 88902802571733229619176668713819931811048770190271, 25267680276078003013678680992525463401061632866526, 36270218540497705585629946580636237993140746255962, 24074486908231174977792365466257246923322810917141, 91430288197103288597806669760892938638285025333403, 34413065578016127815921815005561868836468420090470, 23053081172816430487623791969842487255036638784583, 11487696932154902810424020138335124462181441773470, 63783299490636259666498587618221225225512486764533, 67720186971698544312419572409913959008952310058822, 95548255300263520781532296796249481641953868218774, 76085327132285723110424803456124867697064507995236, 37774242535411291684276865538926205024910326572967, 23701913275725675285653248258265463092207058596522, 29798860272258331913126375147341994889534765745501, 18495701454879288984856827726077713721403798879715, 38298203783031473527721580348144513491373226651381, 34829543829199918180278916522431027392251122869539, 40957953066405232632538044100059654939159879593635, 29746152185502371307642255121183693803580388584903, 41698116222072977186158236678424689157993532961922, 62467957194401269043877107275048102390895523597457, 23189706772547915061505504953922979530901129967519, 86188088225875314529584099251203829009407770775672, 11306739708304724483816533873502340845647058077308, 82959174767140363198008187129011875491310547126581, 97623331044818386269515456334926366572897563400500, 42846280183517070527831839425882145521227251250327, 55121603546981200581762165212827652751691296897789, 32238195734329339946437501907836945765883352399886, 75506164965184775180738168837861091527357929701337, 62177842752192623401942399639168044983993173312731, 32924185707147349566916674687634660915035914677504, 99518671430235219628894890102423325116913619626622, 73267460800591547471830798392868535206946944540724, 76841822524674417161514036427982273348055556214818, 97142617910342598647204516893989422179826088076852, 87783646182799346313767754307809363333018982642090, 10848802521674670883215120185883543223812876952786, 71329612474782464538636993009049310363619763878039, 62184073572399794223406235393808339651327408011116, 66627891981488087797941876876144230030984490851411, 60661826293682836764744779239180335110989069790714, 85786944089552990653640447425576083659976645795096, 66024396409905389607120198219976047599490197230297, 64913982680032973156037120041377903785566085089252, 16730939319872750275468906903707539413042652315011, 94809377245048795150954100921645863754710598436791, 78639167021187492431995700641917969777599028300699, 15368713711936614952811305876380278410754449733078, 40789923115535562561142322423255033685442488917353, 44889911501440648020369068063960672322193204149535, 41503128880339536053299340368006977710650566631954, 81234880673210146739058568557934581403627822703280, 82616570773948327592232845941706525094512325230608, 22918802058777319719839450180888072429661980811197, 77158542502016545090413245809786882778948721859617, 72107838435069186155435662884062257473692284509516, 20849603980134001723930671666823555245252804609722, 53503534226472524250874054075591789781264330331690] temp = 0 result = [] for _ in range(50): for i in range(100): temp += nums[i] % 10 nums[i] = nums[i] // 10 result.insert(0, str(temp % 10)) temp = temp // 10 result.insert(0, str(temp)) return ''.join(result)[:10]
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for testing `LinearOperator` and sub-classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import itertools import numpy as np import six from tensorflow.python.eager import backprop from tensorflow.python.eager import context from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import linalg_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops.linalg import linalg_impl as linalg from tensorflow.python.ops.linalg import linear_operator_util from tensorflow.python.platform import test class OperatorShapesInfo(object): """Object encoding expected shape for a test. Encodes the expected shape of a matrix for a test. Also allows additional metadata for the test harness. """ def __init__(self, shape, **kwargs): self.shape = shape self.__dict__.update(kwargs) class CheckTapeSafeSkipOptions(object): # Skip checking this particular method. DETERMINANT = "determinant" DIAG_PART = "diag_part" LOG_ABS_DETERMINANT = "log_abs_determinant" TRACE = "trace" @six.add_metaclass(abc.ABCMeta) # pylint: disable=no-init class LinearOperatorDerivedClassTest(test.TestCase): """Tests for derived classes. Subclasses should implement every abstractmethod, and this will enable all test methods to work. """ # Absolute/relative tolerance for tests. # Raised float32 tolerances to 1e-5 to allow cholesky tests to pass on ARM. # See nvbug 3460814. _atol = { dtypes.float16: 1e-3, dtypes.float32: 1e-5, dtypes.float64: 1e-12, dtypes.complex64: 1e-6, dtypes.complex128: 1e-12 } _rtol = { dtypes.float16: 1e-3, dtypes.float32: 1e-5, dtypes.float64: 1e-12, dtypes.complex64: 1e-6, dtypes.complex128: 1e-12 } def assertAC(self, x, y): """Derived classes can set _atol, _rtol to get different tolerance.""" dtype = dtypes.as_dtype(x.dtype) atol = self._atol[dtype] rtol = self._rtol[dtype] self.assertAllClose(x, y, atol=atol, rtol=rtol) @staticmethod def adjoint_options(): return [False, True] @staticmethod def adjoint_arg_options(): return [False, True] @staticmethod def dtypes_to_test(): # TODO(langmore) Test tf.float16 once tf.linalg.solve works in 16bit. return [dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128] @staticmethod def use_placeholder_options(): return [False, True] @staticmethod def operator_shapes_infos(): """Returns list of OperatorShapesInfo, encapsulating the shape to test.""" raise NotImplementedError("operator_shapes_infos has not been implemented.") @abc.abstractmethod def operator_and_matrix( self, shapes_info, dtype, use_placeholder, ensure_self_adjoint_and_pd=False): """Build a batch matrix and an Operator that should have similar behavior. Every operator acts like a (batch) matrix. This method returns both together, and is used by tests. Args: shapes_info: `OperatorShapesInfo`, encoding shape information about the operator. dtype: Numpy dtype. Data type of returned array/operator. use_placeholder: Python bool. If True, initialize the operator with a placeholder of undefined shape and correct dtype. ensure_self_adjoint_and_pd: If `True`, construct this operator to be Hermitian Positive Definite, as well as ensuring the hints `is_positive_definite` and `is_self_adjoint` are set. This is useful for testing methods such as `cholesky`. Returns: operator: `LinearOperator` subclass instance. mat: `Tensor` representing operator. """ # Create a matrix as a numpy array with desired shape/dtype. # Create a LinearOperator that should have the same behavior as the matrix. raise NotImplementedError("Not implemented yet.") @abc.abstractmethod def make_rhs(self, operator, adjoint, with_batch=True): """Make a rhs appropriate for calling operator.solve(rhs). Args: operator: A `LinearOperator` adjoint: Python `bool`. If `True`, we are making a 'rhs' value for the adjoint operator. with_batch: Python `bool`. If `True`, create `rhs` with the same batch shape as operator, and otherwise create a matrix without any batch shape. Returns: A `Tensor` """ raise NotImplementedError("make_rhs is not defined.") @abc.abstractmethod def make_x(self, operator, adjoint, with_batch=True): """Make an 'x' appropriate for calling operator.matmul(x). Args: operator: A `LinearOperator` adjoint: Python `bool`. If `True`, we are making an 'x' value for the adjoint operator. with_batch: Python `bool`. If `True`, create `x` with the same batch shape as operator, and otherwise create a matrix without any batch shape. Returns: A `Tensor` """ raise NotImplementedError("make_x is not defined.") @staticmethod def skip_these_tests(): """List of test names to skip.""" # Subclasses should over-ride if they want to skip some tests. # To skip "test_foo", add "foo" to this list. return [] def assertRaisesError(self, msg): """assertRaisesRegexp or OpError, depending on context.executing_eagerly.""" if context.executing_eagerly(): return self.assertRaisesRegexp(Exception, msg) return self.assertRaisesOpError(msg) def check_tape_safe(self, operator, skip_options=None): """Check gradients are not None w.r.t. operator.variables. Meant to be called from the derived class. This ensures grads are not w.r.t every variable in operator.variables. If more fine-grained testing is needed, a custom test should be written. Args: operator: LinearOperator. Exact checks done will depend on hints. skip_options: Optional list of CheckTapeSafeSkipOptions. Makes this test skip particular checks. """ skip_options = skip_options or [] if not operator.variables: raise AssertionError("`operator.variables` was empty") def _assert_not_none(iterable): for item in iterable: self.assertIsNotNone(item) # Tape tests that can be run on every operator below. with backprop.GradientTape() as tape: _assert_not_none(tape.gradient(operator.to_dense(), operator.variables)) with backprop.GradientTape() as tape: _assert_not_none( tape.gradient(operator.adjoint().to_dense(), operator.variables)) x = math_ops.cast( array_ops.ones(shape=operator.H.shape_tensor()[:-1]), operator.dtype) with backprop.GradientTape() as tape: _assert_not_none(tape.gradient(operator.matvec(x), operator.variables)) # Tests for square, but possibly non-singular operators below. if not operator.is_square: return for option in [ CheckTapeSafeSkipOptions.DETERMINANT, CheckTapeSafeSkipOptions.LOG_ABS_DETERMINANT, CheckTapeSafeSkipOptions.DIAG_PART, CheckTapeSafeSkipOptions.TRACE, ]: with backprop.GradientTape() as tape: if option not in skip_options: _assert_not_none( tape.gradient(getattr(operator, option)(), operator.variables)) # Tests for non-singular operators below. if operator.is_non_singular is False: # pylint: disable=g-bool-id-comparison return with backprop.GradientTape() as tape: _assert_not_none( tape.gradient(operator.inverse().to_dense(), operator.variables)) with backprop.GradientTape() as tape: _assert_not_none(tape.gradient(operator.solvevec(x), operator.variables)) # Tests for SPD operators below. if not (operator.is_self_adjoint and operator.is_positive_definite): return with backprop.GradientTape() as tape: _assert_not_none( tape.gradient(operator.cholesky().to_dense(), operator.variables)) # pylint:disable=missing-docstring def _test_to_dense(use_placeholder, shapes_info, dtype): def test_to_dense(self): with self.session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder) op_dense = operator.to_dense() if not use_placeholder: self.assertAllEqual(shapes_info.shape, op_dense.shape) op_dense_v, mat_v = sess.run([op_dense, mat]) self.assertAC(op_dense_v, mat_v) return test_to_dense def _test_det(use_placeholder, shapes_info, dtype): def test_det(self): with self.session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder) op_det = operator.determinant() if not use_placeholder: self.assertAllEqual(shapes_info.shape[:-2], op_det.shape) op_det_v, mat_det_v = sess.run( [op_det, linalg_ops.matrix_determinant(mat)]) self.assertAC(op_det_v, mat_det_v) return test_det def _test_log_abs_det(use_placeholder, shapes_info, dtype): def test_log_abs_det(self): with self.session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder) op_log_abs_det = operator.log_abs_determinant() _, mat_log_abs_det = linalg.slogdet(mat) if not use_placeholder: self.assertAllEqual( shapes_info.shape[:-2], op_log_abs_det.shape) op_log_abs_det_v, mat_log_abs_det_v = sess.run( [op_log_abs_det, mat_log_abs_det]) self.assertAC(op_log_abs_det_v, mat_log_abs_det_v) return test_log_abs_det def _test_matmul_base( self, use_placeholder, shapes_info, dtype, adjoint, adjoint_arg, with_batch): # If batch dimensions are omitted, but there are # no batch dimensions for the linear operator, then # skip the test case. This is already checked with # with_batch=True. if not with_batch and len(shapes_info.shape) <= 2: return with self.session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder) x = self.make_x( operator, adjoint=adjoint, with_batch=with_batch) # If adjoint_arg, compute A X^H^H = A X. if adjoint_arg: op_matmul = operator.matmul( linalg.adjoint(x), adjoint=adjoint, adjoint_arg=adjoint_arg) else: op_matmul = operator.matmul(x, adjoint=adjoint) mat_matmul = math_ops.matmul(mat, x, adjoint_a=adjoint) if not use_placeholder: self.assertAllEqual(op_matmul.shape, mat_matmul.shape) op_matmul_v, mat_matmul_v = sess.run( [op_matmul, mat_matmul]) self.assertAC(op_matmul_v, mat_matmul_v) def _test_matmul( use_placeholder, shapes_info, dtype, adjoint, adjoint_arg): def test_matmul(self): _test_matmul_base( self, use_placeholder, shapes_info, dtype, adjoint, adjoint_arg, with_batch=True) return test_matmul def _test_matmul_with_broadcast( use_placeholder, shapes_info, dtype, adjoint, adjoint_arg): def test_matmul_with_broadcast(self): _test_matmul_base( self, use_placeholder, shapes_info, dtype, adjoint, adjoint_arg, with_batch=True) return test_matmul_with_broadcast def _test_adjoint(use_placeholder, shapes_info, dtype): def test_adjoint(self): with self.test_session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder) op_adjoint = operator.adjoint().to_dense() op_adjoint_h = operator.H.to_dense() mat_adjoint = linalg.adjoint(mat) op_adjoint_v, op_adjoint_h_v, mat_adjoint_v = sess.run( [op_adjoint, op_adjoint_h, mat_adjoint]) self.assertAC(mat_adjoint_v, op_adjoint_v) self.assertAC(mat_adjoint_v, op_adjoint_h_v) return test_adjoint def _test_cholesky(use_placeholder, shapes_info, dtype): def test_cholesky(self): with self.test_session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder, ensure_self_adjoint_and_pd=True) op_chol = operator.cholesky().to_dense() mat_chol = linalg_ops.cholesky(mat) op_chol_v, mat_chol_v = sess.run([op_chol, mat_chol]) self.assertAC(mat_chol_v, op_chol_v) return test_cholesky def _test_solve_base( self, use_placeholder, shapes_info, dtype, adjoint, adjoint_arg, with_batch): # If batch dimensions are omitted, but there are # no batch dimensions for the linear operator, then # skip the test case. This is already checked with # with_batch=True. if not with_batch and len(shapes_info.shape) <= 2: return with self.session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder) rhs = self.make_rhs( operator, adjoint=adjoint, with_batch=with_batch) # If adjoint_arg, solve A X = (rhs^H)^H = rhs. if adjoint_arg: op_solve = operator.solve( linalg.adjoint(rhs), adjoint=adjoint, adjoint_arg=adjoint_arg) else: op_solve = operator.solve( rhs, adjoint=adjoint, adjoint_arg=adjoint_arg) mat_solve = linear_operator_util.matrix_solve_with_broadcast( mat, rhs, adjoint=adjoint) if not use_placeholder: self.assertAllEqual(op_solve.shape, mat_solve.shape) op_solve_v, mat_solve_v = sess.run([op_solve, mat_solve]) self.assertAC(op_solve_v, mat_solve_v) def _test_solve( use_placeholder, shapes_info, dtype, adjoint, adjoint_arg): def test_solve(self): _test_solve_base( self, use_placeholder, shapes_info, dtype, adjoint, adjoint_arg, with_batch=True) return test_solve def _test_solve_with_broadcast( use_placeholder, shapes_info, dtype, adjoint, adjoint_arg): def test_solve_with_broadcast(self): _test_solve_base( self, use_placeholder, shapes_info, dtype, adjoint, adjoint_arg, with_batch=False) return test_solve_with_broadcast def _test_inverse(use_placeholder, shapes_info, dtype): def test_inverse(self): with self.session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder) op_inverse_v, mat_inverse_v = sess.run([ operator.inverse().to_dense(), linalg.inv(mat)]) self.assertAC(op_inverse_v, mat_inverse_v) return test_inverse def _test_trace(use_placeholder, shapes_info, dtype): def test_trace(self): with self.session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder) op_trace = operator.trace() mat_trace = math_ops.trace(mat) if not use_placeholder: self.assertAllEqual(op_trace.shape, mat_trace.shape) op_trace_v, mat_trace_v = sess.run([op_trace, mat_trace]) self.assertAC(op_trace_v, mat_trace_v) return test_trace def _test_add_to_tensor(use_placeholder, shapes_info, dtype): def test_add_to_tensor(self): with self.session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder) op_plus_2mat = operator.add_to_tensor(2 * mat) if not use_placeholder: self.assertAllEqual(shapes_info.shape, op_plus_2mat.shape) op_plus_2mat_v, mat_v = sess.run([op_plus_2mat, mat]) self.assertAC(op_plus_2mat_v, 3 * mat_v) return test_add_to_tensor def _test_diag_part(use_placeholder, shapes_info, dtype): def test_diag_part(self): with self.session(graph=ops.Graph()) as sess: sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED operator, mat = self.operator_and_matrix( shapes_info, dtype, use_placeholder=use_placeholder) op_diag_part = operator.diag_part() mat_diag_part = array_ops.matrix_diag_part(mat) if not use_placeholder: self.assertAllEqual(mat_diag_part.shape, op_diag_part.shape) op_diag_part_, mat_diag_part_ = sess.run( [op_diag_part, mat_diag_part]) self.assertAC(op_diag_part_, mat_diag_part_) return test_diag_part # pylint:enable=missing-docstring def add_tests(test_cls): """Add tests for LinearOperator methods.""" test_name_dict = { "add_to_tensor": _test_add_to_tensor, "cholesky": _test_cholesky, "det": _test_det, "diag_part": _test_diag_part, "inverse": _test_inverse, "log_abs_det": _test_log_abs_det, "matmul": _test_matmul, "matmul_with_broadcast": _test_matmul_with_broadcast, "solve": _test_solve, "solve_with_broadcast": _test_solve_with_broadcast, "to_dense": _test_to_dense, "trace": _test_trace, } tests_with_adjoint_args = [ "matmul", "matmul_with_broadcast", "solve", "solve_with_broadcast", ] for name, test_template_fn in test_name_dict.items(): if name in test_cls.skip_these_tests(): continue for dtype, use_placeholder, shape_info in itertools.product( test_cls.dtypes_to_test(), test_cls.use_placeholder_options(), test_cls.operator_shapes_infos()): base_test_name = "_".join([ "test", name, "_shape={},dtype={},use_placeholder={}".format( shape_info.shape, dtype, use_placeholder)]) if name in tests_with_adjoint_args: for adjoint in test_cls.adjoint_options(): for adjoint_arg in test_cls.adjoint_arg_options(): test_name = base_test_name + ",adjoint={},adjoint_arg={}".format( adjoint, adjoint_arg) if hasattr(test_cls, test_name): raise RuntimeError("Test %s defined more than once" % test_name) setattr( test_cls, test_name, test_util.run_deprecated_v1(test_template_fn( use_placeholder, shape_info, dtype, adjoint, adjoint_arg))) else: if hasattr(test_cls, base_test_name): raise RuntimeError("Test %s defined more than once" % base_test_name) setattr( test_cls, base_test_name, test_util.run_deprecated_v1(test_template_fn( use_placeholder, shape_info, dtype))) @six.add_metaclass(abc.ABCMeta) class SquareLinearOperatorDerivedClassTest(LinearOperatorDerivedClassTest): """Base test class appropriate for square operators. Sub-classes must still define all abstractmethods from LinearOperatorDerivedClassTest that are not defined here. """ @staticmethod def operator_shapes_infos(): shapes_info = OperatorShapesInfo # non-batch operators (n, n) and batch operators. return [ shapes_info((0, 0)), shapes_info((1, 1)), shapes_info((1, 3, 3)), shapes_info((3, 4, 4)), shapes_info((2, 1, 4, 4))] def make_rhs(self, operator, adjoint, with_batch=True): # This operator is square, so rhs and x will have same shape. # adjoint value makes no difference because the operator shape doesn't # change since it is square, but be pedantic. return self.make_x(operator, adjoint=not adjoint, with_batch=with_batch) def make_x(self, operator, adjoint, with_batch=True): # Value of adjoint makes no difference because the operator is square. # Return the number of systems to solve, R, equal to 1 or 2. r = self._get_num_systems(operator) # If operator.shape = [B1,...,Bb, N, N] this returns a random matrix of # shape [B1,...,Bb, N, R], R = 1 or 2. if operator.shape.is_fully_defined(): batch_shape = operator.batch_shape.as_list() n = operator.domain_dimension.value if with_batch: x_shape = batch_shape + [n, r] else: x_shape = [n, r] else: batch_shape = operator.batch_shape_tensor() n = operator.domain_dimension_tensor() if with_batch: x_shape = array_ops.concat((batch_shape, [n, r]), 0) else: x_shape = [n, r] return random_normal(x_shape, dtype=operator.dtype) def _get_num_systems(self, operator): """Get some number, either 1 or 2, depending on operator.""" if operator.tensor_rank is None or operator.tensor_rank % 2: return 1 else: return 2 @six.add_metaclass(abc.ABCMeta) class NonSquareLinearOperatorDerivedClassTest(LinearOperatorDerivedClassTest): """Base test class appropriate for generic rectangular operators. Square shapes are never tested by this class, so if you want to test your operator with a square shape, create two test classes, the other subclassing SquareLinearOperatorFullMatrixTest. Sub-classes must still define all abstractmethods from LinearOperatorDerivedClassTest that are not defined here. """ @staticmethod def skip_these_tests(): """List of test names to skip.""" return [ "cholesky", "inverse", "solve", "solve_with_broadcast", "det", "log_abs_det" ] @staticmethod def operator_shapes_infos(): shapes_info = OperatorShapesInfo # non-batch operators (n, n) and batch operators. return [ shapes_info((2, 1)), shapes_info((1, 2)), shapes_info((1, 3, 2)), shapes_info((3, 3, 4)), shapes_info((2, 1, 2, 4))] def make_rhs(self, operator, adjoint, with_batch=True): # TODO(langmore) Add once we're testing solve_ls. raise NotImplementedError( "make_rhs not implemented because we don't test solve") def make_x(self, operator, adjoint, with_batch=True): # Return the number of systems for the argument 'x' for .matmul(x) r = self._get_num_systems(operator) # If operator.shape = [B1,...,Bb, M, N] this returns a random matrix of # shape [B1,...,Bb, N, R], R = 1 or 2. if operator.shape.is_fully_defined(): batch_shape = operator.batch_shape.as_list() if adjoint: n = operator.range_dimension.value else: n = operator.domain_dimension.value if with_batch: x_shape = batch_shape + [n, r] else: x_shape = [n, r] else: batch_shape = operator.batch_shape_tensor() if adjoint: n = operator.range_dimension_tensor() else: n = operator.domain_dimension_tensor() if with_batch: x_shape = array_ops.concat((batch_shape, [n, r]), 0) else: x_shape = [n, r] return random_normal(x_shape, dtype=operator.dtype) def _get_num_systems(self, operator): """Get some number, either 1 or 2, depending on operator.""" if operator.tensor_rank is None or operator.tensor_rank % 2: return 1 else: return 2 def random_positive_definite_matrix(shape, dtype, force_well_conditioned=False): """[batch] positive definite matrix. Args: shape: `TensorShape` or Python list. Shape of the returned matrix. dtype: `TensorFlow` `dtype` or Python dtype. force_well_conditioned: Python bool. If `True`, returned matrix has eigenvalues with modulus in `(1, 4)`. Otherwise, eigenvalues are chi-squared random variables. Returns: `Tensor` with desired shape and dtype. """ dtype = dtypes.as_dtype(dtype) if not tensor_util.is_tensor(shape): shape = tensor_shape.TensorShape(shape) # Matrix must be square. shape.dims[-1].assert_is_compatible_with(shape.dims[-2]) with ops.name_scope("random_positive_definite_matrix"): tril = random_tril_matrix( shape, dtype, force_well_conditioned=force_well_conditioned) return math_ops.matmul(tril, tril, adjoint_b=True) def random_tril_matrix(shape, dtype, force_well_conditioned=False, remove_upper=True): """[batch] lower triangular matrix. Args: shape: `TensorShape` or Python `list`. Shape of the returned matrix. dtype: `TensorFlow` `dtype` or Python dtype force_well_conditioned: Python `bool`. If `True`, returned matrix will have eigenvalues with modulus in `(1, 2)`. Otherwise, eigenvalues are unit normal random variables. remove_upper: Python `bool`. If `True`, zero out the strictly upper triangle. If `False`, the lower triangle of returned matrix will have desired properties, but will not have the strictly upper triangle zero'd out. Returns: `Tensor` with desired shape and dtype. """ with ops.name_scope("random_tril_matrix"): # Totally random matrix. Has no nice properties. tril = random_normal(shape, dtype=dtype) if remove_upper: tril = array_ops.matrix_band_part(tril, -1, 0) # Create a diagonal with entries having modulus in [1, 2]. if force_well_conditioned: maxval = ops.convert_to_tensor(np.sqrt(2.), dtype=dtype.real_dtype) diag = random_sign_uniform( shape[:-1], dtype=dtype, minval=1., maxval=maxval) tril = array_ops.matrix_set_diag(tril, diag) return tril def random_normal(shape, mean=0.0, stddev=1.0, dtype=dtypes.float32, seed=None): """Tensor with (possibly complex) Gaussian entries. Samples are distributed like ``` N(mean, stddev^2), if dtype is real, X + iY, where X, Y ~ N(mean, stddev^2) if dtype is complex. ``` Args: shape: `TensorShape` or Python list. Shape of the returned tensor. mean: `Tensor` giving mean of normal to sample from. stddev: `Tensor` giving stdev of normal to sample from. dtype: `TensorFlow` `dtype` or numpy dtype seed: Python integer seed for the RNG. Returns: `Tensor` with desired shape and dtype. """ dtype = dtypes.as_dtype(dtype) with ops.name_scope("random_normal"): samples = random_ops.random_normal( shape, mean=mean, stddev=stddev, dtype=dtype.real_dtype, seed=seed) if dtype.is_complex: if seed is not None: seed += 1234 more_samples = random_ops.random_normal( shape, mean=mean, stddev=stddev, dtype=dtype.real_dtype, seed=seed) samples = math_ops.complex(samples, more_samples) return samples def random_uniform(shape, minval=None, maxval=None, dtype=dtypes.float32, seed=None): """Tensor with (possibly complex) Uniform entries. Samples are distributed like ``` Uniform[minval, maxval], if dtype is real, X + iY, where X, Y ~ Uniform[minval, maxval], if dtype is complex. ``` Args: shape: `TensorShape` or Python list. Shape of the returned tensor. minval: `0-D` `Tensor` giving the minimum values. maxval: `0-D` `Tensor` giving the maximum values. dtype: `TensorFlow` `dtype` or Python dtype seed: Python integer seed for the RNG. Returns: `Tensor` with desired shape and dtype. """ dtype = dtypes.as_dtype(dtype) with ops.name_scope("random_uniform"): samples = random_ops.random_uniform( shape, dtype=dtype.real_dtype, minval=minval, maxval=maxval, seed=seed) if dtype.is_complex: if seed is not None: seed += 12345 more_samples = random_ops.random_uniform( shape, dtype=dtype.real_dtype, minval=minval, maxval=maxval, seed=seed) samples = math_ops.complex(samples, more_samples) return samples def random_sign_uniform(shape, minval=None, maxval=None, dtype=dtypes.float32, seed=None): """Tensor with (possibly complex) random entries from a "sign Uniform". Letting `Z` be a random variable equal to `-1` and `1` with equal probability, Samples from this `Op` are distributed like ``` Z * X, where X ~ Uniform[minval, maxval], if dtype is real, Z * (X + iY), where X, Y ~ Uniform[minval, maxval], if dtype is complex. ``` Args: shape: `TensorShape` or Python list. Shape of the returned tensor. minval: `0-D` `Tensor` giving the minimum values. maxval: `0-D` `Tensor` giving the maximum values. dtype: `TensorFlow` `dtype` or Python dtype seed: Python integer seed for the RNG. Returns: `Tensor` with desired shape and dtype. """ dtype = dtypes.as_dtype(dtype) with ops.name_scope("random_sign_uniform"): unsigned_samples = random_uniform( shape, minval=minval, maxval=maxval, dtype=dtype, seed=seed) if seed is not None: seed += 12 signs = math_ops.sign( random_ops.random_uniform(shape, minval=-1., maxval=1., seed=seed)) return unsigned_samples * math_ops.cast(signs, unsigned_samples.dtype) def random_normal_correlated_columns(shape, mean=0.0, stddev=1.0, dtype=dtypes.float32, eps=1e-4, seed=None): """Batch matrix with (possibly complex) Gaussian entries and correlated cols. Returns random batch matrix `A` with specified element-wise `mean`, `stddev`, living close to an embedded hyperplane. Suppose `shape[-2:] = (M, N)`. If `M < N`, `A` is a random `M x N` [batch] matrix with iid Gaussian entries. If `M >= N`, then the colums of `A` will be made almost dependent as follows: ``` L = random normal N x N-1 matrix, mean = 0, stddev = 1 / sqrt(N - 1) B = random normal M x N-1 matrix, mean = 0, stddev = stddev. G = (L B^H)^H, a random normal M x N matrix, living on N-1 dim hyperplane E = a random normal M x N matrix, mean = 0, stddev = eps mu = a constant M x N matrix, equal to the argument "mean" A = G + E + mu ``` Args: shape: Python list of integers. Shape of the returned tensor. Must be at least length two. mean: `Tensor` giving mean of normal to sample from. stddev: `Tensor` giving stdev of normal to sample from. dtype: `TensorFlow` `dtype` or numpy dtype eps: Distance each column is perturbed from the low-dimensional subspace. seed: Python integer seed for the RNG. Returns: `Tensor` with desired shape and dtype. Raises: ValueError: If `shape` is not at least length 2. """ dtype = dtypes.as_dtype(dtype) if len(shape) < 2: raise ValueError( "Argument shape must be at least length 2. Found: %s" % shape) # Shape is the final shape, e.g. [..., M, N] shape = list(shape) batch_shape = shape[:-2] m, n = shape[-2:] # If there is only one column, "they" are by definition correlated. if n < 2 or n < m: return random_normal( shape, mean=mean, stddev=stddev, dtype=dtype, seed=seed) # Shape of the matrix with only n - 1 columns that we will embed in higher # dimensional space. smaller_shape = batch_shape + [m, n - 1] # Shape of the embedding matrix, mapping batch matrices # from [..., N-1, M] to [..., N, M] embedding_mat_shape = batch_shape + [n, n - 1] # This stddev for the embedding_mat ensures final result has correct stddev. stddev_mat = 1 / np.sqrt(n - 1) with ops.name_scope("random_normal_correlated_columns"): smaller_mat = random_normal( smaller_shape, mean=0.0, stddev=stddev_mat, dtype=dtype, seed=seed) if seed is not None: seed += 1287 embedding_mat = random_normal(embedding_mat_shape, dtype=dtype, seed=seed) embedded_t = math_ops.matmul(embedding_mat, smaller_mat, transpose_b=True) embedded = array_ops.matrix_transpose(embedded_t) mean_mat = array_ops.ones_like(embedded) * mean return embedded + random_normal(shape, stddev=eps, dtype=dtype) + mean_mat
import sys import numpy as np from triarray import TriMatrix from .utils import set_doc two_sample_stats_doc = """ Test Statistics for the Two-Sample Problem This is a collection of functions that provide test statistics to be used into the permutation scheme for performing two-sample testing. These test statistics can be divided into two categories: traditional statistics that use empirical moments and inter-point statistics that only rely on pairwise dissimilarities between data points. Parameters: data (list or triarray.TriMatrix): Either a list of the `n1 + n2` concatenated observations with the original `n1` observations from the first sample on top and the original `n2` observations from the second sample below. Or a dissimilarity matrix stored as a `triarray.TriMatrix` object for all inter-point statistics whose function name should end with `_ip()`. indices1 (range or list of integers): An integer vector specifying the indices in `data` that are considered to belong to the first sample. alpha (double): A scalar value in (0, 2] specifying the power to which the dissimilarities should be elevated in the computation of the `stat_energy_ip()` statistic. Default is `1`. standardize (bool): A boolean specifying whether the distance between medoids in the `stat_dom_ip()` function should be normalized by the pooled corresponding variances. Default is `True`. **kwargs: Extra parameters specific to some statistics. Value: A real scalar giving the value of test statistic for the permutation specified by the integer vector `indices`. Traditional Test Statistics: `stat_hotelling()` implements Hotelling's \eqn{T^2} statistic for multivariate data with \eqn{p < n}. `stat_student()` or `stat_t()` implements Student's statistic (originally assuming equal variances and thus using the pooled empirical variance estimator). `stat_welch()` implements Student-Welch statistic which is essentially a modification of Student's statistic accounting for unequal variances. `stat_fisher()` or `stat_f()` implements Fisher's variance ratio statistic. `stat_mean()` implements a statistic that computes the difference between the means. `stat_bs()` implements the statistic proposed by Bai & Saranadasa (1996) for high-dimensional multivariate data. Inter-Point Test Statistics: `stat_student_ip()` or `stat_t_ip()` implements a Student-like test statistic based on inter-point distances only as described in Lovato et al. (2020). `stat_fisher_ip()` or `stat_f_ip()` implements a Fisher-like test statistic based on inter-point distances only as described in Lovato et al. (2020). `stat_bg_ip()` implements the statistic proposed by Biswas & Ghosh (2014). `stat_energy_ip()` implements the class of energy-based statistics as described in Székely & Rizzo (2013); `stat_cq_ip()` implements the statistic proposed by Chen & Qin (2010). `stat_mod_ip()` implements a statistic that computes the mean of inter-point distances. `stat_dom_ip()` implements a statistic that computes the distance between the medoids of the two samples, possibly standardized by the pooled corresponding variances. References: Bai, Z., & Saranadasa, H. (1996). Effect of high dimension: by an example of a two sample problem. Statistica Sinica, 311-329. Lovato, I., Pini, A., Stamm, A., & Vantini, S. (2020). Model-free two-sample test for network-valued data. Computational Statistics & Data Analysis, 144, 106896. Biswas, M., & Ghosh, A. K. (2014). A nonparametric two-sample test applicable to high dimensional data. Journal of Multivariate Analysis, 123, 160-171. Székely, G. J., & Rizzo, M. L. (2013). Energy statistics: A class of statistics based on distances. Journal of statistical planning and inference, 143(8), 1249-1272. Chen, S. X., & Qin, Y. L. (2010). A two-sample test for high-dimensional data with applications to gene-set testing. The Annals of Statistics, 38(2), 808-835. Examples: import numpy as np from scipy.spatial.distance import pdist from triarray import TriMatrix n = 10 x = np.random.rand(n, 1) y = np.random.rand(n, 1) dists = pdist(np.vstack([x, y])) D = TriMatrix(dists, upper = True, diag_val = 0) x = list(x) y = list(y) stat_welch(x + y, range(n)) stat_t(x + y, range(n)) stat_f(x + y, range(n)) stat_mean(x + y, range(n)) stat_hotelling(x + y, range(n)) stat_bs(x + y, range(n)) stat_t_ip(D, range(n)) stat_f_ip(D, range(n)) stat_bg_ip(D, range(n)) stat_energy_ip(D, range(n)) stat_cq_ip(D, range(n)) stat_mod_ip(D, range(n)) stat_dom_ip(D, range(n)) """ @set_doc(two_sample_stats_doc) def stat_welch(data, indices1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) x1 = [data[i] for i in l["idx1"]] x2 = [data[i] for i in l["idx2"]] m1 = np.mean(x1) m2 = np.mean(x2) v1 = np.var(x1, ddof = 1) v2 = np.var(x2, ddof = 1) stderr = np.sqrt(v1 / n1 + v2 / n2) return (m1 - m2) / stderr @set_doc(two_sample_stats_doc) def stat_student(data, indices1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) x1 = [data[i] for i in l["idx1"]] x2 = [data[i] for i in l["idx2"]] m1 = np.mean(x1) m2 = np.mean(x2) v1 = np.var(x1) v2 = np.var(x2) sig2 = (n1 * v1 + n2 * v2) / (n1 + n2 - 2) stderr = np.sqrt(sig2 * (1 / n1 + 1 / n2)) return (m2 - m1) / stderr @set_doc(two_sample_stats_doc) def stat_t(data, indices1, **kwargs): return stat_student(data, indices1, **kwargs) @set_doc(two_sample_stats_doc) def stat_fisher(data, indices1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) x1 = [data[i] for i in l["idx1"]] x2 = [data[i] for i in l["idx2"]] v1 = np.var(x1, ddof = 1) v2 = np.var(x2, ddof = 1) return v2 / v1 @set_doc(two_sample_stats_doc) def stat_f(data, indices1, **kwargs): return stat_fisher(data, indices1, **kwargs) @set_doc(two_sample_stats_doc) def stat_mean(data, indices1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) x1 = [data[i] for i in l["idx1"]] x2 = [data[i] for i in l["idx2"]] m1 = np.mean(x1) m2 = np.mean(x2) return m1 - m2 @set_doc(two_sample_stats_doc) def stat_hotelling(data, indices1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) x1 = np.array([data[i] for i in l["idx1"]]) x2 = np.array([data[i] for i in l["idx2"]]) m1 = np.mean(x1, 0) m2 = np.mean(x2, 0) v1 = np.cov(x1.transpose(), ddof = 1) v2 = np.cov(x2.transpose(), ddof = 1) vp = ((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2) vinv = np.linalg.inv(vp) d = m1 - m2 return d.transpose() @ vinv @ d @set_doc(two_sample_stats_doc) def stat_bs(data, indices1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) x1 = np.array([data[i] for i in l["idx1"]]) x2 = np.array([data[i] for i in l["idx2"]]) m1 = np.mean(x1, 0) m2 = np.mean(x2, 0) v1 = np.cov(x1.transpose(), ddof = 1) v2 = np.cov(x2.transpose(), ddof = 1) vn = ((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2) d = m1 - m2 return d.transpose() @ d - (n1 + n2) / (n1 * n2) * sum(np.diag(vn)) @set_doc(two_sample_stats_doc) def stat_student_ip(data, indices1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) D11 = [[data.get_item(l["idx1"][i], l["idx1"][j]) for j in range(i + 1, n1)] for i in range(n1)] M11 = (np.array([item for sublist in D11 for item in sublist])**2).mean() D22 = [[data.get_item(l["idx2"][i], l["idx2"][j]) for j in range(i + 1, n2)] for i in range(n2)] M22 = (np.array([item for sublist in D22 for item in sublist])**2).mean() D12 = [[data.get_item(i, j) for j in l["idx2"]] for i in l["idx1"]] M12 = (np.array(D12)**2).mean() v1 = M11 / 2 v2 = M22 / 2 numerator = M12 - v1 - v2 vn = (v1 / n1 + v2 / n2) if vn < np.sqrt(np.finfo(float).eps): return numerator return numerator / vn @set_doc(two_sample_stats_doc) def stat_t_ip(data, indices1, **kwargs): return stat_student_ip(data, indices1, **kwargs) @set_doc(two_sample_stats_doc) def stat_fisher_ip(data, indices1, **kwarg): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) D11 = [[data.get_item(l["idx1"][i], l["idx1"][j]) for j in range(i + 1, n1)] for i in range(n1)] M11 = (np.array([item for sublist in D11 for item in sublist])**2).mean() D22 = [[data.get_item(l["idx2"][i], l["idx2"][j]) for j in range(i + 1, n2)] for i in range(n2)] M22 = (np.array([item for sublist in D22 for item in sublist])**2).mean() v1 = M11 / 2 v2 = M22 / 2 vmin = min(v1, v2) vmax = max(v1, v2) if vmin < np.sqrt(np.finfo(float).eps): return vmax return vmax / vmin @set_doc(two_sample_stats_doc) def stat_f_ip(data, indices1, **kwargs): return stat_fisher_ip(data, indices1, **kwargs) @set_doc(two_sample_stats_doc) def stat_bg_ip(data, indices1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) D11 = [[data.get_item(l["idx1"][i], l["idx1"][j]) for j in range(i + 1, n1)] for i in range(n1)] M11 = np.array([item for sublist in D11 for item in sublist]).mean() D22 = [[data.get_item(l["idx2"][i], l["idx2"][j]) for j in range(i + 1, n2)] for i in range(n2)] M22 = np.array([item for sublist in D22 for item in sublist]).mean() D12 = [[data.get_item(i, j) for j in l["idx2"]] for i in l["idx1"]] M12 = np.array(D12).mean() return (M11 - M12)**2 + (M22 - M12)**2 @set_doc(two_sample_stats_doc) def stat_energy_ip(data, indices1, alpha = 1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) D11 = [[data.get_item(i, j) for j in l["idx1"]] for i in l["idx1"]] M11 = (np.array(D11)**alpha).mean() D22 = [[data.get_item(i, j) for j in l["idx2"]] for i in l["idx2"]] M22 = (np.array(D22)**alpha).mean() D12 = [[data.get_item(i, j) for j in l["idx2"]] for i in l["idx1"]] M12 = (np.array(D12)**alpha).mean() return M12 - (M11 + M22) / 2 @set_doc(two_sample_stats_doc) def stat_cq_ip(data, indices1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) D11 = [[data.get_item(i, j) for j in l["idx1"] if j != i] for i in l["idx1"]] M11 = (np.array(D11)).mean() D22 = [[data.get_item(i, j) for j in l["idx2"] if j != i] for i in l["idx2"]] M22 = (np.array(D22)).mean() D12 = [[data.get_item(i, j) for j in l["idx2"]] for i in l["idx1"]] M12 = (np.array(D12)).mean() return M11 + M22 - 2 * M12 @set_doc(two_sample_stats_doc) def stat_mod_ip(data, indices1, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) D12 = [[data.get_item(i, j) for j in l["idx2"]] for i in l["idx1"]] M12 = (np.array(D12)).mean() return M12 @set_doc(two_sample_stats_doc) def stat_dom_ip(data, indices1, standardize = True, **kwargs): l = two_sample_prep(data, indices1) n1 = len(l["idx1"]) n2 = len(l["idx2"]) D11 = [[data.get_item(i, j) for j in l["idx1"]] for i in l["idx1"]] ssd1_vec = (np.array(D11)**2).sum(axis = 0) km1 = l["idx1"][ssd1_vec.argmin()] D22 = [[data.get_item(i, j) for j in l["idx2"]] for i in l["idx2"]] ssd2_vec = (np.array(D22)**2).sum(axis = 0) km2 = l["idx2"][ssd2_vec.argmin()] stat = data.get_item(km1, km2) if not standardize: return stat ssd1 = min(ssd1_vec) ssd2 = min(ssd2_vec) vp = (ssd1 + ssd2) / (n1 + n2 - 2) return stat / np.sqrt(vp) def two_sample_prep(data, indices1): if isinstance(data, list): n = len(data) elif isinstance(data, TriMatrix): n = data.size else: sys.exit("The `data` input should be of class either list or dist.") indices1 = list(indices1) indices1.sort() indices2 = list(set(range(n)) - set(indices1)) indices2.sort() return {"idx1": indices1, "idx2": indices2}
const resolveFrom = require('resolve-from') const { default: graphBrainzSchema, createSchema } = require('graphbrainz/lib/schema') const { schemaToJSON, diffSchema } = require('../../src/index') /** * Generate a "diff" schema in order to test `diffSchema`. */ async function generateDiff() { // Get the instance of `graphql` that `graphbrainz` sees. const graphql = require(resolveFrom( require.resolve('graphbrainz'), 'graphql' )) const extendedSchema = createSchema(graphBrainzSchema, { extensions: ['graphbrainz/extensions/cover-art-archive'] }) const schemaJSON = await schemaToJSON(graphBrainzSchema, { graphql }) const extendedSchemaJSON = await schemaToJSON(extendedSchema, { graphql }) return diffSchema(schemaJSON, extendedSchemaJSON) } module.exports = generateDiff()
import moment from 'moment'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Button from 'react-bootstrap/lib/Button'; import injectT from '../../i18n/injectT'; import { hasProducts } from '../../utils/resourceUtils'; import { getUnitRoleFromResource, getIsUnitStaff } from '../../../src/domain/resource/permissions/utils'; class ReservationControls extends Component { get buttons() { return { cancel: ( <Button bsStyle="danger" key="cancelButton" onClick={this.props.onCancelClick} > {this.props.t('ReservationControls.cancel')} </Button> ), confirm: ( <Button bsStyle="success" key="confirmButton" onClick={this.props.onConfirmClick} > {this.props.t('ReservationControls.confirm')} </Button> ), deny: ( <Button bsStyle="danger" key="denyButton" onClick={this.props.onDenyClick} > {this.props.t('ReservationControls.deny')} </Button> ), edit: ( <Button bsStyle="primary" disabled={( !this.isStaff && !this.props.isAdmin && hasProducts(this.props.resource)) || this.props.resource === null } key="editButton" onClick={this.props.onEditClick} > {this.props.t('ReservationControls.edit')} </Button> ), info: ( <Button bsStyle="default" key="infoButton" onClick={this.props.onInfoClick} > {this.props.t('ReservationControls.info')} </Button> ), }; } get isStaff() { const { resource } = this.props; if (!resource) { return false; } return getIsUnitStaff(getUnitRoleFromResource(resource)); } renderButtons(buttons, isAdmin, isStaff, reservation) { if (!reservation.need_manual_confirmation) { if (reservation.state === 'cancelled') { return null; } return isAdmin ? [buttons.edit, buttons.cancel] : [buttons.edit, buttons.cancel]; } switch (reservation.state) { case 'cancelled': { return []; } case 'confirmed': { if (isAdmin) { return isStaff ? [buttons.cancel, buttons.edit] : [buttons.cancel]; } return [buttons.cancel]; } case 'denied': { return []; } case 'requested': { if (isAdmin) { return isStaff ? [buttons.confirm, buttons.deny, buttons.edit] : [buttons.edit]; } return [buttons.edit, buttons.cancel]; } default: { return null; } } } render() { const { isAdmin, reservation } = this.props; const reservationIsInThePast = !reservation || moment() > moment(reservation.end); return ( <div className="buttons"> <div className="app-ReservationControls__info-button-wrapper">{this.buttons.info}</div> {!reservationIsInThePast && this.renderButtons(this.buttons, isAdmin, this.isStaff, reservation)} </div> ); } } ReservationControls.propTypes = { isAdmin: PropTypes.bool.isRequired, onCancelClick: PropTypes.func.isRequired, onConfirmClick: PropTypes.func.isRequired, onDenyClick: PropTypes.func.isRequired, onEditClick: PropTypes.func.isRequired, onInfoClick: PropTypes.func.isRequired, reservation: PropTypes.object, resource: PropTypes.object, t: PropTypes.func.isRequired, }; export default injectT(ReservationControls);
from django.conf import settings from django.test import SimpleTestCase, override_settings from django.utils.six.moves.urllib.parse import urljoin from ..utils import setup @override_settings(INSTALLED_APPS=[], MEDIA_URL='/media/', STATIC_URL='/static/') class StaticTagTests(SimpleTestCase): libraries = {'static': 'django.templatetags.static'} @setup({'static-prefixtag01': '{% load static %}{% get_static_prefix %}'}) def test_static_prefixtag01(self): output = self.engine.render_to_string('static-prefixtag01') self.assertEqual(output, settings.STATIC_URL) @setup({'static-prefixtag02': '{% load static %}' '{% get_static_prefix as static_prefix %}{{ static_prefix }}'}) def test_static_prefixtag02(self): output = self.engine.render_to_string('static-prefixtag02') self.assertEqual(output, settings.STATIC_URL) @setup({'static-prefixtag03': '{% load static %}{% get_media_prefix %}'}) def test_static_prefixtag03(self): output = self.engine.render_to_string('static-prefixtag03') self.assertEqual(output, settings.MEDIA_URL) @setup({'static-prefixtag04': '{% load static %}' '{% get_media_prefix as media_prefix %}{{ media_prefix }}'}) def test_static_prefixtag04(self): output = self.engine.render_to_string('static-prefixtag04') self.assertEqual(output, settings.MEDIA_URL) @setup({'static-statictag01': '{% load static %}{% static "admin/base.css" %}'}) def test_static_statictag01(self): output = self.engine.render_to_string('static-statictag01') self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css')) @setup({'static-statictag02': '{% load static %}{% static base_css %}'}) def test_static_statictag02(self): output = self.engine.render_to_string('static-statictag02', {'base_css': 'admin/base.css'}) self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css')) @setup({'static-statictag03': '{% load static %}{% static "admin/base.css" as foo %}{{ foo }}'}) def test_static_statictag03(self): output = self.engine.render_to_string('static-statictag03') self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css')) @setup({'static-statictag04': '{% load static %}{% static base_css as foo %}{{ foo }}'}) def test_static_statictag04(self): output = self.engine.render_to_string('static-statictag04', {'base_css': 'admin/base.css'}) self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css')) @setup({'static-statictag05': '{% load static %}{% static "special?chars&quoted.html" %}'}) def test_static_quotes_urls(self): output = self.engine.render_to_string('static-statictag05') self.assertEqual(output, urljoin(settings.STATIC_URL, '/static/special%3Fchars%26quoted.html'))
var gulp = require('gulp'); var browserSync = require('browser-sync').create(); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); gulp.task('serve', function(){ browserSync.init({ server: { baseDir: './' } }); }); gulp.task('script', function(){ gulp.src('app/js/*.js') .pipe(concat('main.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')); }); gulp.task('watch', function(){ gulp.watch(['index.html', 'partials/*.html', 'dist/*.js']).on('change', browserSync.reload); gulp.watch('app/js/*.js', ['script']); }); gulp.task('default', ['serve', 'script', 'watch']);
'use strict'; const userNameInput = document.getElementById("user-name"); const assessmentButton = document.getElementById("assessment"); const resultDivided = document.getElementById("result-area"); const tweetDivided = document.getElementById("tweet-area"); /** * 指定した要素の子どもを全て削除する * @param {HTMLElement} element HTMLの要素 */ function removeAllChildren(element) { while (element.firstChild) { //result-area に、なにかタグがある限りループ element.removeChild(element.firstChild); } } /** * 診断処理を実行して、指定した要素に結果を表示する。 * @param {HTMLElement} element HTMLの要素 */ function createAssessmentResult(element) { // result-area に h3 タグで"診断結果"という文字を表示 const h3 = document.createElement('h3') // h3 タグを作る h3.innerText = '診断結果'; // h3 タグに診断結果の文字列を設定 element.appendChild(h3) // result-area に h3 変数を設定 } assessmentButton.onclick = function () { let userName = userNameInput.value; if (userName.length === 0) { // 名前の入力がなかった場合は処理を終了する return; } // すでにある診断結果を削除 removeAllChildren(resultDivided); // 診断結果の表示 createAssessmentResult(resultDivided); // 診断処理を実行 const result = assessment(userName); // tweet ボタンの表示 // a タグを作って属性を設定する removeAllChildren(tweetDivided) const a = document.createElement('a'); const hrefValue = 'https://twitter.com/intent/tweet?button_hashtag=' +encodeURIComponent('あなたのいいところ') +'&ref_src=twsrc%5Etfw'; a.setAttribute ('href', hrefValue); a.setAttribute ('class','twitter-hashtag-button'); a.setAttribute ('data-text' , result); a.innerText = 'Tweet #あなたのいいところ' // a タグをHTML に追加する tweetDivided.appendChild(a); // script タグを作る const script = document.createElement('script'); script.setAttribute('src','https://platform.twitter.com/widgets.js'); tweetDivided.appendChild(script); // result-area に p タグで診断結果を表示 const p = document.createElement('p'); p.innerText = result; resultDivided.appendChild(p); } userNameInput.onkeydown = event => { if(event.key === 'Enter') { assessmentButton.onclick(); } } const answers = [ '{userName}のいいところは声です。{userName}の特徴的な声は皆を惹きつけ、心に残ります。', '{userName}のいいところはまなざしです。{userName}に見つめられた人は、気になって仕方がないでしょう。', '{userName}のいいところは情熱です。{userName}の情熱に周りの人は感化されます。', '{userName}のいいところは厳しさです。{userName}の厳しさがものごとをいつも成功に導きます。', '{userName}のいいところは知識です。博識な{userName}を多くの人が頼りにしています。', '{userName}のいいところはユニークさです。{userName}だけのその特徴が皆を楽しくさせます。', '{userName}のいいところは用心深さです。{userName}の洞察に、多くの人が助けられます。', '{userName}のいいところは見た目です。内側から溢れ出る{userName}の良さに皆が気を惹かれます。', '{userName}のいいところは決断力です。{userName}がする決断にいつも助けられる人がいます。', '{userName}のいいところは思いやりです。{userName}に気をかけてもらった多くの人が感謝しています。', '{userName}のいいところは感受性です。{userName}が感じたことに皆が共感し、わかりあうことができます。', '{userName}のいいところは節度です。強引すぎない{userName}の考えに皆が感謝しています。', '{userName}のいいところは好奇心です。新しいことに向かっていく{userName}の心構えが多くの人に魅力的に映ります。', '{userName}のいいところは気配りです。{userName}の配慮が多くの人を救っています。', '{userName}のいいところはその全てです。ありのままの{userName}自身がいいところなのです。', '{userName}のいいところは自制心です。やばいと思ったときにしっかりと衝動を抑えられる{userName}が皆から評価されています。', '{userName}のいいところは優しさです。{userName}の優しい雰囲気や立ち振舞に多くの人が癒やされています。' ]; /** * 名前の文字列を渡すと診断結果を返す関数 * @param {string} userName ユーザーの名前 * @return {string} 診断結果 */ function assessment(userName) { // userName (文字列)を数値 (漢字だと5桁)に変換 // すべての文字を足し算する var userNameNumber = 0; for (let i = 0; i < userName.length; i++) { // userName (文字列)を数値 (漢字だと5桁)に変換 userNameNumber += userName.charCodeAt(i); } //回答結果の範囲(0~15) var answerNumber = userNameNumber % answers.length; //診断結果 var result = answers[answerNumber]; result.replace(/\{userName\}/g, userName); //置換 return result.replace(/\{userName\}/g, userName); //置換; //診断結果 } console.assert( assessment('太郎') === '太郎のいいところは決断力です。太郎がする決断にいつも助けられる人がいます。', '診断結果の文言の特定の部分を名前に置き換える処理が正しくありません。' ); console.assert( assessment('太郎') === assessment('太郎'), '入力が同じ名前なら同じ診断結果を出力する処理が正しくありません。' ) console.log(assessment('太郎')); console.log(assessment('次郎')); console.log(assessment('太郎'));
from libqtile.command import lazy # from libqtile.command_client import InteractiveCommandClient class Functions: ##### MOVE WINDOW IN GROUPS ##### @staticmethod def window_to_prev_group(): @lazy.function def __inner(qtile): i = qtile.groups.index(qtile.current_group) if qtile.current_window and i != 0: group = qtile.groups[i - 1].name qtile.current_window.togroup(group, switch_group=True) return __inner @staticmethod def window_to_next_group(): @lazy.function def __inner(qtile): i = qtile.groups.index(qtile.current_group) if qtile.current_window and i != len(qtile.groups): group = qtile.groups[i + 1].name qtile.current_window.togroup(group, switch_group=True) return __inner ##### KILL ALL WINDOWS ##### @staticmethod def kill_all_windows(): @lazy.function def __inner(qtile): for window in qtile.current_group.windows: window.kill() return __inner @staticmethod def kill_all_windows_minus_current(): @lazy.function def __inner(qtile): for window in qtile.current_group.windows: if window != qtile.current_window: window.kill() return __inner class PWA: def __init__(self): pass @staticmethod def notion(): return "brave --profile-directory=Default --app=https://notion.so" @staticmethod def music(): return "brave --profile-directory=Default --app=https://music.youtube.com/" @staticmethod def spotify(): return "brave --profile-directory=Default --app=https://open.spotify.com/" @staticmethod def youtube(): return "brave --user-data-dir=Default --app=https://www.youtube.com" @staticmethod def calendar(): return "brave --profile-directory=Default --app=https://calendar.google.com/calendar/" @staticmethod def habitica(): return "brave --profile-directory=Default --app=https://habitica.com/" if __name__ == "__main__": print("This is an utilities module")
from yolo_evm.memory import Memory, InvalidMemoryAccess, InvalidMemoryValue import pytest @pytest.fixture def memory() -> Memory: return Memory() def test_invalid_offset(memory): with pytest.raises(InvalidMemoryAccess) as excinfo: memory.store(-1, 1) assert excinfo.value.args[0]['offset'] == -1 def test_store_far_offset(memory): memory.store(100, 42) for i in range(0, 100): assert memory.load(i) == 0 assert memory.load(100) == 42 def test_store_max(memory): max_value = 2 ** 8 - 1 memory.store(0, max_value) assert memory.load(0) == max_value def test_invalid_value_negative(memory): with pytest.raises(InvalidMemoryValue) as excinfo: memory.store(1, -1) assert excinfo.value.args[0]['value'] == -1 def test_invalid_value_too_big(memory): with pytest.raises(InvalidMemoryValue) as excinfo: memory.store(1, 0x100) assert excinfo.value.args[0]['value'] == 0x100
//------------------------------------------------------------------------------ // GB_block: apply all pending computations if blocking mode enabled //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2018, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ #include "GB.h" GrB_Info GB_block // apply all pending computations if blocking mode enabled ( GrB_Matrix A ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (A != NULL) ; //-------------------------------------------------------------------------- // check for blocking mode //-------------------------------------------------------------------------- if (GB_Global.mode == GrB_BLOCKING) { // delete any lingering zombies and assemble any pending tuples APPLY_PENDING_UPDATES (A) ; } return (REPORT_SUCCESS) ; }
import json import threading import time import os import stat from decimal import Decimal from typing import Union, Optional from numbers import Real from copy import deepcopy from . import util from .util import (user_dir, make_dir, NoDynamicFeeEstimates, format_fee_satoshis, quantize_feerate) from .i18n import _ from .logging import get_logger, Logger FEE_ETA_TARGETS = [25, 10, 5, 2] FEE_DEPTH_TARGETS = [10000000, 5000000, 2000000, 1000000, 500000, 200000, 100000] # satoshi per kbyte FEERATE_MAX_DYNAMIC = 15000 FEERATE_WARNING_HIGH_FEE = 10000 FEERATE_FALLBACK_STATIC_FEE = 1000 FEERATE_DEFAULT_RELAY = 1000 FEERATE_STATIC_VALUES = [150, 300, 500, 1000, 1500, 2500, 3500, 5000, 7500, 10000] config = None _logger = get_logger(__name__) def get_config(): global config return config def set_config(c): global config config = c FINAL_CONFIG_VERSION = 3 class SimpleConfig(Logger): """ The SimpleConfig class is responsible for handling operations involving configuration files. There are two different sources of possible configuration values: 1. Command line options. 2. User configuration (in the user's config directory) They are taken in order (1. overrides config options set in 2.) """ def __init__(self, options=None, read_user_config_function=None, read_user_dir_function=None): if options is None: options = {} Logger.__init__(self) # This lock needs to be acquired for updating and reading the config in # a thread-safe way. self.lock = threading.RLock() self.mempool_fees = {} self.fee_estimates = {} self.fee_estimates_last_updated = {} self.last_time_fee_estimates_requested = 0 # zero ensures immediate fees # The following two functions are there for dependency injection when # testing. if read_user_config_function is None: read_user_config_function = read_user_config if read_user_dir_function is None: self.user_dir = user_dir else: self.user_dir = read_user_dir_function # The command line options self.cmdline_options = deepcopy(options) # don't allow to be set on CLI: self.cmdline_options.pop('config_version', None) # Set self.path and read the user config self.user_config = {} # for self.get in electrum_path() self.path = self.electrum_path() self.user_config = read_user_config_function(self.path) if not self.user_config: # avoid new config getting upgraded self.user_config = {'config_version': FINAL_CONFIG_VERSION} # config "upgrade" - CLI options self.rename_config_keys( self.cmdline_options, {'auto_cycle': 'auto_connect'}, True) # config upgrade - user config if self.requires_upgrade(): self.upgrade() # Make a singleton instance of 'self' set_config(self) def electrum_path(self): # Read electrum_path from command line # Otherwise use the user's default data directory. path = self.get('electrum_path') if path is None: path = self.user_dir() make_dir(path, allow_symlink=False) if self.get('testnet'): path = os.path.join(path, 'testnet') make_dir(path, allow_symlink=False) elif self.get('regtest'): path = os.path.join(path, 'regtest') make_dir(path, allow_symlink=False) self.logger.info(f"electrum-dash directory {path}") return path def rename_config_keys(self, config, keypairs, deprecation_warning=False): """Migrate old key names to new ones""" updated = False for old_key, new_key in keypairs.items(): if old_key in config: if new_key not in config: config[new_key] = config[old_key] if deprecation_warning: self.logger.warning('Note that the {} variable has been deprecated. ' 'You should use {} instead.'.format(old_key, new_key)) del config[old_key] updated = True return updated def set_key(self, key, value, save=True): if not self.is_modifiable(key): self.logger.warning(f"not changing config key '{key}' set on the command line") return try: json.dumps(key) json.dumps(value) except: self.logger.info(f"json error: cannot save {repr(key)} ({repr(value)})") return self._set_key_in_user_config(key, value, save) def _set_key_in_user_config(self, key, value, save=True): with self.lock: if value is not None: self.user_config[key] = value else: self.user_config.pop(key, None) if save: self.save_user_config() def get(self, key, default=None): with self.lock: out = self.cmdline_options.get(key) if out is None: out = self.user_config.get(key, default) return out def requires_upgrade(self): return self.get_config_version() < FINAL_CONFIG_VERSION def upgrade(self): with self.lock: self.logger.info('upgrading config') self.convert_version_2() self.convert_version_3() self.set_key('config_version', FINAL_CONFIG_VERSION, save=True) def convert_version_2(self): if not self._is_upgrade_method_needed(1, 1): return self.rename_config_keys(self.user_config, {'auto_cycle': 'auto_connect'}) try: # change server string FROM host:port:proto TO host:port:s server_str = self.user_config.get('server') host, port, protocol = str(server_str).rsplit(':', 2) assert protocol in ('s', 't') int(port) # Throw if cannot be converted to int server_str = '{}:{}:s'.format(host, port) self._set_key_in_user_config('server', server_str) except BaseException: self._set_key_in_user_config('server', None) self.set_key('config_version', 2) def convert_version_3(self): if not self._is_upgrade_method_needed(2, 2): return base_unit = self.user_config.get('base_unit') if isinstance(base_unit, str): self._set_key_in_user_config('base_unit', None) map_ = {'dash':8, 'mdash':5, 'udash':2, 'duffs':0, 'sat':0} decimal_point = map_.get(base_unit.lower()) self._set_key_in_user_config('decimal_point', decimal_point) self.set_key('config_version', 3) def _is_upgrade_method_needed(self, min_version, max_version): cur_version = self.get_config_version() if cur_version > max_version: return False elif cur_version < min_version: raise Exception( ('config upgrade: unexpected version %d (should be %d-%d)' % (cur_version, min_version, max_version))) else: return True def get_config_version(self): config_version = self.get('config_version', 1) if config_version > FINAL_CONFIG_VERSION: self.logger.warning('config version ({}) is higher than latest ({})' .format(config_version, FINAL_CONFIG_VERSION)) return config_version def is_modifiable(self, key): return key not in self.cmdline_options def save_user_config(self): if not self.path: return path = os.path.join(self.path, "config") s = json.dumps(self.user_config, indent=4, sort_keys=True) try: with open(path, "w", encoding='utf-8') as f: f.write(s) os.chmod(path, stat.S_IREAD | stat.S_IWRITE) except FileNotFoundError: # datadir probably deleted while running... if os.path.exists(self.path): # or maybe not? raise def get_wallet_path(self): """Set the path of the wallet.""" # command line -w option if self.get('wallet_path'): return os.path.join(self.get('cwd', ''), self.get('wallet_path')) # path in config file path = self.get('default_wallet_path') if path and os.path.exists(path): return path # default path util.assert_datadir_available(self.path) dirpath = os.path.join(self.path, "wallets") make_dir(dirpath, allow_symlink=False) new_path = os.path.join(self.path, "wallets", "default_wallet") # default path in pre 1.9 versions old_path = os.path.join(self.path, "electrum.dat") if os.path.exists(old_path) and not os.path.exists(new_path): os.rename(old_path, new_path) return new_path def remove_from_recently_open(self, filename): recent = self.get('recently_open', []) if filename in recent: recent.remove(filename) self.set_key('recently_open', recent) def set_session_timeout(self, seconds): self.logger.info(f"session timeout -> {seconds} seconds") self.set_key('session_timeout', seconds) def get_session_timeout(self): return self.get('session_timeout', 300) def open_last_wallet(self): if self.get('wallet_path') is None: last_wallet = self.get('gui_last_wallet') if last_wallet is not None and os.path.exists(last_wallet): self.cmdline_options['default_wallet_path'] = last_wallet def save_last_wallet(self, wallet): if self.get('wallet_path') is None: path = wallet.storage.path self.set_key('gui_last_wallet', path) def impose_hard_limits_on_fee(func): def get_fee_within_limits(self, *args, **kwargs): fee = func(self, *args, **kwargs) if fee is None: return fee fee = min(FEERATE_MAX_DYNAMIC, fee) fee = max(FEERATE_DEFAULT_RELAY, fee) return fee return get_fee_within_limits def eta_to_fee(self, slider_pos) -> Optional[int]: """Returns fee in sat/kbyte.""" slider_pos = max(slider_pos, 0) slider_pos = min(slider_pos, len(FEE_ETA_TARGETS)) if slider_pos < len(FEE_ETA_TARGETS): num_blocks = FEE_ETA_TARGETS[slider_pos] fee = self.eta_target_to_fee(num_blocks) else: fee = self.eta_target_to_fee(1) return fee @impose_hard_limits_on_fee def eta_target_to_fee(self, num_blocks: int) -> Optional[int]: """Returns fee in sat/kbyte.""" if num_blocks == 1: fee = self.fee_estimates.get(2) if fee is not None: fee += fee / 2 fee = int(fee) else: fee = self.fee_estimates.get(num_blocks) return fee def fee_to_depth(self, target_fee: Real) -> int: """For a given sat/vbyte fee, returns an estimate of how deep it would be in the current mempool in vbytes. Pessimistic == overestimates the depth. """ depth = 0 for fee, s in self.mempool_fees: depth += s if fee <= target_fee: break return depth def depth_to_fee(self, slider_pos) -> int: """Returns fee in sat/kbyte.""" target = self.depth_target(slider_pos) return self.depth_target_to_fee(target) @impose_hard_limits_on_fee def depth_target_to_fee(self, target: int) -> int: """Returns fee in sat/kbyte. target: desired mempool depth in vbytes """ depth = 0 for fee, s in self.mempool_fees: depth += s if depth > target: break else: return 0 # add one sat/byte as currently that is # the max precision of the histogram fee += 1 # convert to sat/kbyte return fee * 1000 def depth_target(self, slider_pos): slider_pos = max(slider_pos, 0) slider_pos = min(slider_pos, len(FEE_DEPTH_TARGETS)-1) return FEE_DEPTH_TARGETS[slider_pos] def eta_target(self, i): if i == len(FEE_ETA_TARGETS): return 1 return FEE_ETA_TARGETS[i] def fee_to_eta(self, fee_per_kb): import operator l = list(self.fee_estimates.items()) + [(1, self.eta_to_fee(4))] dist = map(lambda x: (x[0], abs(x[1] - fee_per_kb)), l) min_target, min_value = min(dist, key=operator.itemgetter(1)) if fee_per_kb < self.fee_estimates.get(25)/2: min_target = -1 return min_target def depth_tooltip(self, depth): return "%.1f MB from tip"%(depth/1000000) def eta_tooltip(self, x): if x < 0: return _('Low fee') elif x == 1: return _('In the next block') else: return _('Within {} blocks').format(x) def get_fee_status(self): dyn = self.is_dynfee() mempool = self.use_mempool_fees() pos = self.get_depth_level() if mempool else self.get_fee_level() fee_rate = self.fee_per_kb() target, tooltip = self.get_fee_text(pos, dyn, mempool, fee_rate) return tooltip + ' [%s]'%target if dyn else target + ' [Static]' def get_fee_text(self, pos, dyn, mempool, fee_rate): """Returns (text, tooltip) where text is what we target: static fee / num blocks to confirm in / mempool depth tooltip is the corresponding estimate (e.g. num blocks for a static fee) fee_rate is in duffs/kbyte """ if fee_rate is None: rate_str = 'unknown' else: rate_str = format_fee_satoshis(fee_rate) + ' duffs/kB' if dyn: if mempool: depth = self.depth_target(pos) text = self.depth_tooltip(depth) else: eta = self.eta_target(pos) text = self.eta_tooltip(eta) tooltip = rate_str else: text = rate_str if mempool and self.has_fee_mempool(): depth = self.fee_to_depth(fee_rate) tooltip = self.depth_tooltip(depth) elif not mempool and self.has_fee_etas(): eta = self.fee_to_eta(fee_rate) tooltip = self.eta_tooltip(eta) else: tooltip = '' return text, tooltip def get_depth_level(self): maxp = len(FEE_DEPTH_TARGETS) - 1 return min(maxp, self.get('depth_level', 2)) def get_fee_level(self): maxp = len(FEE_ETA_TARGETS) # not (-1) to have "next block" return min(maxp, self.get('fee_level', 2)) def get_fee_slider(self, dyn, mempool): if dyn: if mempool: pos = self.get_depth_level() maxp = len(FEE_DEPTH_TARGETS) - 1 fee_rate = self.depth_to_fee(pos) else: pos = self.get_fee_level() maxp = len(FEE_ETA_TARGETS) # not (-1) to have "next block" fee_rate = self.eta_to_fee(pos) else: fee_rate = self.fee_per_kb(dyn=False) pos = self.static_fee_index(fee_rate) maxp = len(FEERATE_STATIC_VALUES) - 1 return maxp, pos, fee_rate def static_fee(self, i): return FEERATE_STATIC_VALUES[i] def static_fee_index(self, value): if value is None: raise TypeError('static fee cannot be None') dist = list(map(lambda x: abs(x - value), FEERATE_STATIC_VALUES)) return min(range(len(dist)), key=dist.__getitem__) def has_fee_etas(self): return len(self.fee_estimates) == 4 def has_fee_mempool(self): return bool(self.mempool_fees) def has_dynamic_fees_ready(self): if self.use_mempool_fees(): return self.has_fee_mempool() else: return self.has_fee_etas() def is_dynfee(self): return bool(self.get('dynamic_fees', True)) def use_mempool_fees(self): return False def _feerate_from_fractional_slider_position(self, fee_level: float, dyn: bool, mempool: bool) -> Union[int, None]: fee_level = max(fee_level, 0) fee_level = min(fee_level, 1) if dyn: max_pos = (len(FEE_DEPTH_TARGETS) - 1) if mempool else len(FEE_ETA_TARGETS) slider_pos = round(fee_level * max_pos) fee_rate = self.depth_to_fee(slider_pos) if mempool else self.eta_to_fee(slider_pos) else: max_pos = len(FEERATE_STATIC_VALUES) - 1 slider_pos = round(fee_level * max_pos) fee_rate = FEERATE_STATIC_VALUES[slider_pos] return fee_rate def fee_per_kb(self, dyn: bool=None, mempool: bool=None, fee_level: float=None) -> Union[int, None]: """Returns sat/kvB fee to pay for a txn. Note: might return None. fee_level: float between 0.0 and 1.0, representing fee slider position """ if dyn is None: dyn = self.is_dynfee() if mempool is None: mempool = self.use_mempool_fees() if fee_level is not None: return self._feerate_from_fractional_slider_position(fee_level, dyn, mempool) # there is no fee_level specified; will use config. # note: 'depth_level' and 'fee_level' in config are integer slider positions, # unlike fee_level here, which (when given) is a float in [0.0, 1.0] if dyn: if mempool: fee_rate = self.depth_to_fee(self.get_depth_level()) else: fee_rate = self.eta_to_fee(self.get_fee_level()) else: fee_rate = self.get('fee_per_kb', FEERATE_FALLBACK_STATIC_FEE) return fee_rate def estimate_fee(self, size: Union[int, float, Decimal]) -> int: fee_per_kb = self.fee_per_kb() if fee_per_kb is None: raise NoDynamicFeeEstimates() return self.estimate_fee_for_feerate(fee_per_kb, size) @classmethod def estimate_fee_for_feerate(cls, fee_per_kb: Union[int, float, Decimal], size: Union[int, float, Decimal]) -> int: size = Decimal(size) return round(fee_per_kb * size / 1000) def update_fee_estimates(self, key, value): self.fee_estimates[key] = value self.fee_estimates_last_updated[key] = time.time() def is_fee_estimates_update_required(self): """Checks time since last requested and updated fee estimates. Returns True if an update should be requested. """ now = time.time() return now - self.last_time_fee_estimates_requested > 60 def requested_fee_estimates(self): self.last_time_fee_estimates_requested = time.time() def get_video_device(self): device = self.get("video_device", "default") if device == 'default': device = '' return device def read_user_config(path): """Parse and store the user config settings in electrum-dash.conf into user_config[].""" if not path: return {} config_path = os.path.join(path, "config") if not os.path.exists(config_path): return {} try: with open(config_path, "r", encoding='utf-8') as f: data = f.read() result = json.loads(data) except: _logger.warning(f"Cannot read config file. {config_path}") return {} if not type(result) is dict: return {} return result
""" Django settings for pvfree project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ import os from pvfree import get_secret import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! _SECRETKEY = get_secret('SECRET_KEY', '.secretkey') SECRET_KEY = _SECRETKEY # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['pvfree.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'parameters', 'tastypie', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pvfree.urls' WSGI_APPLICATION = 'pvfree.wsgi.application' # Databases # use ElephantSQL database instead of heroku DATABASES = { 'default': dj_database_url.config(env='ELEPHANT_SQL', conn_max_age=600), } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'public', 'static') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this # list if you haven't customized them: 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATICFILES_DIRS = [os.path.join(BASE_DIR, "assets")] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'public', 'media') AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': ('[%(levelname)s] %(asctime)s (%(processName)s) ' + '(%(threadName)s)\n> %(message)s') }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'pvfree.log'), 'formatter': 'verbose' }, }, 'loggers': { 'parameters.models': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, }, }
#from .base import * from .production import * #try: # from .local import* #except: # pass
// ----------------------------------------------------------------------------------- // http://wowslider.com/ // JavaScript Wow Slider is a free software that helps you easily generate delicious // slideshows with gorgeous transition effects, in a few clicks without writing a single line of code. // Generated by WOW Slider 4.8 // //*********************************************** // Obfuscated by Javascript Obfuscator // http://javascript-source.com //*********************************************** function ws_slices(i,f,g){var c=jQuery;var e=function(p,v){var o=c.extend({},{effect:"random",slices:15,animSpeed:500,pauseTime:3000,startSlide:0,container:null,onEffectEnd:0},v);var r={currentSlide:0,currentImage:"",totalSlides:0,randAnim:"",stop:false};var m=c(p);m.data("wow:vars",r);if(!/absolute|relative/.test(m.css("position"))){m.css("position","relative")}var k=v.container||m;var n=m.children();r.totalSlides=n.length;if(o.startSlide>0){if(o.startSlide>=r.totalSlides){o.startSlide=r.totalSlides-1}r.currentSlide=o.startSlide}if(c(n[r.currentSlide]).is("img")){r.currentImage=c(n[r.currentSlide])}else{r.currentImage=c(n[r.currentSlide]).find("img:first")}if(c(n[r.currentSlide]).is("a")){c(n[r.currentSlide]).css("display","block")}for(var q=0;q<o.slices;q++){var u=Math.round(k.width()/o.slices);var t=c('<div class="wow-slice"></div>').css({left:u*q+"px",overflow:"hidden",width:((q==o.slices-1)?(k.width()-(u*q)):u)+"px",position:"absolute"}).appendTo(k);c("<img>").css({position:"absolute",left:0,top:0}).appendTo(t)}var l=0;this.sliderRun=function(w,x){if(r.busy){return false}o.effect=x||o.effect;r.currentSlide=w-1;s(m,n,o,false);return true};var j=function(){if(o.onEffectEnd){o.onEffectEnd(r.currentSlide)}k.hide();r.busy=0};var s=function(w,x,z,B){var C=w.data("wow:vars");if((!C||C.stop)&&!B){return false}C.busy=1;C.currentSlide++;if(C.currentSlide==C.totalSlides){C.currentSlide=0}if(C.currentSlide<0){C.currentSlide=(C.totalSlides-1)}C.currentImage=c(x[C.currentSlide]);if(!C.currentImage.is("img")){C.currentImage=C.currentImage.find("img:first")}c(".wow-slice",k).each(function(H){var J=c(this),G=c("img",J);var I=Math.round(k.width()/z.slices);G.width(k.width());G.attr("src",C.currentImage.attr("src"));G.css({left:-I*H+"px"});J.css({height:"0px",opacity:"0",left:I*H+"px",width:((H==z.slices-1)?(k.width()-(I*H)):I)+"px"})});k.show();if(z.effect=="random"){var D=new Array("sliceDownRight","sliceDownLeft","sliceUpRight","sliceUpLeft","sliceUpDownRight","sliceUpDownLeft","fold","fade");C.randAnim=D[Math.floor(Math.random()*(D.length+1))];if(C.randAnim==undefined){C.randAnim="fade"}}if(z.effect.indexOf(",")!=-1){var D=z.effect.split(",");C.randAnim=c.trim(D[Math.floor(Math.random()*D.length)])}if(z.effect=="sliceDown"||z.effect=="sliceDownRight"||C.randAnim=="sliceDownRight"||z.effect=="sliceDownLeft"||C.randAnim=="sliceDownLeft"){var y=0;var A=0;var F=c(".wow-slice",k);if(z.effect=="sliceDownLeft"||C.randAnim=="sliceDownLeft"){F=c(".wow-slice",k)._reverse()}F.each(function(){var G=c(this);G.css({top:0,bottom:""});if(A==z.slices-1){setTimeout(function(){G.animate({height:"100%",opacity:"1.0"},z.animSpeed,j)},(100+y))}else{setTimeout(function(){G.animate({height:"100%",opacity:"1.0"},z.animSpeed)},(100+y))}y+=50;A++})}else{if(z.effect=="sliceUp"||z.effect=="sliceUpRight"||C.randAnim=="sliceUpRight"||z.effect=="sliceUpLeft"||C.randAnim=="sliceUpLeft"){var y=0;var A=0;var F=c(".wow-slice",k);if(z.effect=="sliceUpLeft"||C.randAnim=="sliceUpLeft"){F=c(".wow-slice",k)._reverse()}F.each(function(){var G=c(this);G.css({top:"",bottom:0});if(A==z.slices-1){setTimeout(function(){G.animate({height:"100%",opacity:"1.0"},z.animSpeed,j)},(100+y))}else{setTimeout(function(){G.animate({height:"100%",opacity:"1.0"},z.animSpeed)},(100+y))}y+=50;A++})}else{if(z.effect=="sliceUpDown"||z.effect=="sliceUpDownRight"||C.randAnim=="sliceUpDownRight"||z.effect=="sliceUpDownLeft"||C.randAnim=="sliceUpDownLeft"){var y=0;var A=0;var E=0;var F=c(".wow-slice",k);if(z.effect=="sliceUpDownLeft"||C.randAnim=="sliceUpDownLeft"){F=c(".wow-slice",k)._reverse()}F.each(function(){var G=c(this);if(A==0){G.css({top:0,bottom:""});A++}else{G.css({top:"",bottom:0});A=0}if(E==z.slices-1){setTimeout(function(){G.animate({height:"100%",opacity:"1.0"},z.animSpeed,j)},(100+y))}else{setTimeout(function(){G.animate({height:"100%",opacity:"1.0"},z.animSpeed)},(100+y))}y+=50;E++})}else{if(z.effect=="fold"||C.randAnim=="fold"){var y=0;var A=0;c(".wow-slice",k).each(function(){var G=c(this);var H=G.width();G.css({top:"0px",height:"100%",width:"0px"});if(A==z.slices-1){setTimeout(function(){G.animate({width:H,opacity:"1.0"},z.animSpeed,j)},(100+y))}else{setTimeout(function(){G.animate({width:H,opacity:"1.0"},z.animSpeed)},(100+y))}y+=50;A++})}else{if(z.effect=="fade"||C.randAnim=="fade"){var A=0;c(".wow-slice",k).each(function(){c(this).css("height","100%");if(A==z.slices-1){c(this).animate({opacity:"1.0"},(z.animSpeed*2),j)}else{c(this).animate({opacity:"1.0"},(z.animSpeed*2))}A++})}}}}}}};c.fn._reverse=[].reverse;var a=c("li",g);var d=c("ul",g);var b=c("<div></div>").css({left:0,top:0,"z-index":8,width:"100%",height:"100%",position:"absolute"}).appendTo(g);var h=new e(d,{keyboardNav:false,caption:0,effect:"sliceDownRight,sliceDownLeft,sliceUpRight,sliceUpLeft,sliceUpDownRight,sliceUpDownLeft,sliceUpDownRight,sliceUpDownLeft,fold,fold,fold",animSpeed:i.duration,startSlide:i.startSlide,container:b,onEffectEnd:function(j){d.css({left:-j+"00%"}).stop(true,true).show()}});this.go=function(k,j){var l=h.sliderRun(k);if(l){if(i.fadeOut){d.fadeOut(i.duration)}return k}else{return -1}}};// ----------------------------------------------------------------------------------- // http://wowslider.com/ // JavaScript Wow Slider is a free software that helps you easily generate delicious // slideshows with gorgeous transition effects, in a few clicks without writing a single line of code. // Generated by WOW Slider 4.8 // //*********************************************** // Obfuscated by Javascript Obfuscator // http://javascript-source.com //*********************************************** jQuery("#wowslider-container1").wowSlider({effect:"slices",prev:"",next:"",duration:12*100,delay:50*100,width:948,height:403,autoPlay:true,playPause:true,stopOnHover:false,loop:false,bullets:true,caption:true,captionEffect:"slide",controls:true,onBeforeStep:0,images:0});
# GENERATED BY KOMAND SDK - DO NOT EDIT from .action import StartInstance
import React from 'react'; import NightOut from '../assets/Project1.png'; import DeedDone from '../assets/DeedDone.png'; import EmployeeDirectory from '../assets/EmployeeDirectory.png'; import BudgetTracker from '../assets/BudgetTracker.png'; import PasswordGenerator from '../assets/PasswordGenerator.png'; import '../style.css'; function Project() { return ( <div class="row no-gutters" style={{marginBottom: "20px"}}> <div class="col-md-6"> <a href="https://jwhendershott.github.io/NightOut/#" target="_blank" rel="noreferrer"> <img class="img img-thumbnail" src={NightOut} alt="Night Out" width= "350px" height= "350px"></img> </a> </div> <div class="col-md-6"> <a href="https://deeddone.herokuapp.com/" target="_blank" rel="noreferrer"> <img class="img img-thumbnail" src={DeedDone} alt="Deed Done" width= "350px" height= "350px"></img> </a> </div> <div class="col-md-6"> <a href="https://rchaphekar1.github.io/employeedirectory/" target="_blank" rel="noreferrer"> <img class="img img-thumbnail" src={EmployeeDirectory} alt="Employee Directory" width= "350px" height= "350px"></img> </a> </div> <div class="col-md-6"> <a href="https://budgettracker-project.herokuapp.com/" target="_blank" rel="noreferrer"> <img class="img img-thumbnail" src={BudgetTracker} alt="Budget Tracker" width= "350px" height= "350px"></img> </a> </div> <div class="col-md-6"> <a href="https://rchaphekar1.github.io/PasswordGenerator/" target="_blank" rel="noreferrer"> <img class="img img-thumbnail" src={PasswordGenerator} alt="Password Generator" width= "350px" height= "350px"></img> </a> </div> </div> ) }; export default Project;
/* global angular, console */ import 'ionic-sdk/release/js/ionic.bundle'; angular.module('app.modals.submit-password', []) .controller('SubmitPasswordCtrl', function ($scope, Wallet) { 'use strict'; $scope.form = {}; $scope.model = {}; let signer = $scope.data.signer; if (signer === Wallet.current.id) { $scope.label = 'modal.password.label'; } else { if (signer in Wallet.accounts) { signer = Wallet.accounts[signer].alias; } $scope.translationData = { key: signer }; $scope.label = 'modal.password.keyname'; } $scope.submitPassword = function () { if ($scope.form.passwordForm.$valid) { $scope.modalResolve($scope.model.password); } }; $scope.cancel = function () { $scope.closeModalService(); }; });
AUTHOR = 'Adrian Sampson' # General configuration extensions = ['sphinx.ext.autodoc', 'sphinx.ext.extlinks'] exclude_patterns = ['_build'] source_suffix = '.rst' master_doc = 'index' project = 'beets' copyright = '2016, Adrian Sampson' version = '1.6' release = '1.6.1' pygments_style = 'sphinx' # External links to the bug tracker and other sites. extlinks = { 'bug': ('https://github.com/beetbox/beets/issues/%s', '#'), 'user': ('https://github.com/%s', ''), 'pypi': ('https://pypi.org/project/%s/', ''), 'stdlib': ('https://docs.python.org/3/library/%s.html', ''), } linkcheck_ignore = [ r'https://github.com/beetbox/beets/issues/', r'https://github.com/[^/]+$', # ignore user pages r'.*localhost.*', r'https?://127\.0\.0\.1', r'https://www.musixmatch.com/', # blocks requests r'https://genius.com/', # blocks requests ] # Options for HTML output htmlhelp_basename = 'beetsdoc' # Options for LaTeX output latex_documents = [ ('index', 'beets.tex', 'beets Documentation', AUTHOR, 'manual'), ] # Options for manual page output man_pages = [ ('reference/cli', 'beet', 'music tagger and library organizer', [AUTHOR], 1), ('reference/config', 'beetsconfig', 'beets configuration file', [AUTHOR], 5), ]
// Copyright (c) 2013 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #ifndef THIRD_PARTY_LEVELDATABASE_ENV_CHROMIUM_H_ #define THIRD_PARTY_LEVELDATABASE_ENV_CHROMIUM_H_ #include <memory> #include <set> #include <string> #include <vector> #include "base/callback.h" #include "base/containers/circular_deque.h" #include "base/containers/flat_map.h" #include "base/containers/linked_list.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/metrics/histogram.h" #include "base/synchronization/condition_variable.h" #include "build/build_config.h" #include "leveldb/cache.h" #include "leveldb/db.h" #include "leveldb/env.h" #include "leveldb/export.h" #include "port/port_chromium.h" #include "util/mutexlock.h" #if defined(OS_WIN) && defined(DeleteFile) // See comment in env.h. #undef DeleteFile #define ENV_CHROMIUM_DELETEFILE_UNDEFINED #endif // defined(OS_WIN) && defined(DeleteFile) namespace base { namespace trace_event { class MemoryAllocatorDump; class ProcessMemoryDump; } // namespace trace_event } // namespace base namespace leveldb_env { // These entries map to values in tools/metrics/histograms/histograms.xml. New // values should be appended at the end. enum MethodID { kSequentialFileRead, kSequentialFileSkip, kRandomAccessFileRead, kWritableFileAppend, kWritableFileClose, kWritableFileFlush, kWritableFileSync, kNewSequentialFile, kNewRandomAccessFile, kNewWritableFile, kDeleteFile, kCreateDir, kDeleteDir, kGetFileSize, kRenameFile, kLockFile, kUnlockFile, kGetTestDirectory, kNewLogger, kSyncParent, kGetChildren, kNewAppendableFile, kNumEntries }; // leveldb::Status::Code values are mapped to these values for UMA logging. // Do not change/delete these values as you will break reporting for older // copies of Chrome. Only add new values to the end. enum LevelDBStatusValue { LEVELDB_STATUS_OK = 0, LEVELDB_STATUS_NOT_FOUND, LEVELDB_STATUS_CORRUPTION, LEVELDB_STATUS_NOT_SUPPORTED, LEVELDB_STATUS_INVALID_ARGUMENT, LEVELDB_STATUS_IO_ERROR, LEVELDB_STATUS_MAX }; LEVELDB_EXPORT LevelDBStatusValue GetLevelDBStatusUMAValue(const leveldb::Status& s); using DatabaseErrorReportingCallback = base::RepeatingCallback<void(const leveldb::Status&)>; // Create the default leveldb options object suitable for leveldb operations. struct LEVELDB_EXPORT Options : public leveldb::Options { Options(); // Called when there is a error during the Get() call. Intended for metrics // reporting. DatabaseErrorReportingCallback on_get_error; // Called when there is a error during the Write() call, which is called for // Write(), Put() and Delete(). Intended for metrics reporting. DatabaseErrorReportingCallback on_write_error; }; LEVELDB_EXPORT const char* MethodIDToString(MethodID method); leveldb::Status LEVELDB_EXPORT MakeIOError(leveldb::Slice filename, const std::string& message, MethodID method, base::File::Error error); leveldb::Status LEVELDB_EXPORT MakeIOError(leveldb::Slice filename, const std::string& message, MethodID method); enum ErrorParsingResult { METHOD_ONLY, METHOD_AND_BFE, NONE, }; ErrorParsingResult LEVELDB_EXPORT ParseMethodAndError(const leveldb::Status& status, MethodID* method, base::File::Error* error); LEVELDB_EXPORT int GetCorruptionCode(const leveldb::Status& status); LEVELDB_EXPORT int GetNumCorruptionCodes(); LEVELDB_EXPORT std::string GetCorruptionMessage(const leveldb::Status& status); LEVELDB_EXPORT bool IndicatesDiskFull(const leveldb::Status& status); // Returns the name for a temporary database copy during RewriteDB(). LEVELDB_EXPORT std::string DatabaseNameForRewriteDB( const std::string& original_name); // Determine the appropriate leveldb write buffer size to use. The default size // (4MB) may result in a log file too large to be compacted given the available // storage space. This function will return smaller values for smaller disks, // and the default leveldb value for larger disks. // // |disk_space| is the logical partition size (in bytes), and *not* available // space. A value of -1 will return leveldb's default write buffer size. LEVELDB_EXPORT extern size_t WriteBufferSize(int64_t disk_space); class LEVELDB_EXPORT UMALogger { public: virtual void RecordErrorAt(MethodID method) const = 0; virtual void RecordOSError(MethodID method, base::File::Error error) const = 0; virtual void RecordBytesRead(int amount) const = 0; virtual void RecordBytesWritten(int amount) const = 0; }; class LEVELDB_EXPORT RetrierProvider { public: virtual int MaxRetryTimeMillis() const = 0; virtual base::HistogramBase* GetRetryTimeHistogram(MethodID method) const = 0; virtual base::HistogramBase* GetRecoveredFromErrorHistogram( MethodID method) const = 0; }; class LEVELDB_EXPORT ChromiumEnv : public leveldb::Env, public UMALogger, public RetrierProvider { public: ChromiumEnv(); typedef void(ScheduleFunc)(void*); virtual ~ChromiumEnv(); bool FileExists(const std::string& fname) override; leveldb::Status GetChildren(const std::string& dir, std::vector<std::string>* result) override; leveldb::Status DeleteFile(const std::string& fname) override; leveldb::Status CreateDir(const std::string& name) override; leveldb::Status DeleteDir(const std::string& name) override; leveldb::Status GetFileSize(const std::string& fname, uint64_t* size) override; leveldb::Status RenameFile(const std::string& src, const std::string& dst) override; leveldb::Status LockFile(const std::string& fname, leveldb::FileLock** lock) override; leveldb::Status UnlockFile(leveldb::FileLock* lock) override; void Schedule(ScheduleFunc*, void* arg) override; void StartThread(void (*function)(void* arg), void* arg) override; leveldb::Status GetTestDirectory(std::string* path) override; uint64_t NowMicros() override; void SleepForMicroseconds(int micros) override; leveldb::Status NewSequentialFile(const std::string& fname, leveldb::SequentialFile** result) override; leveldb::Status NewRandomAccessFile( const std::string& fname, leveldb::RandomAccessFile** result) override; leveldb::Status NewWritableFile(const std::string& fname, leveldb::WritableFile** result) override; leveldb::Status NewAppendableFile(const std::string& fname, leveldb::WritableFile** result) override; leveldb::Status NewLogger(const std::string& fname, leveldb::Logger** result) override; void SetReadOnlyFileLimitForTesting(int max_open_files); protected: explicit ChromiumEnv(const std::string& name); static const char* FileErrorString(base::File::Error error); private: void RecordErrorAt(MethodID method) const override; void RecordOSError(MethodID method, base::File::Error error) const override; void RecordBytesRead(int amount) const override; void RecordBytesWritten(int amount) const override; base::HistogramBase* GetOSErrorHistogram(MethodID method, int limit) const; void DeleteBackupFiles(const base::FilePath& dir); // File locks may not be exclusive within a process (e.g. on POSIX). Track // locks held by the ChromiumEnv to prevent access within the process. class LockTable { public: bool Insert(const std::string& fname) { leveldb::MutexLock l(&mu_); return locked_files_.insert(fname).second; } bool Remove(const std::string& fname) { leveldb::MutexLock l(&mu_); return locked_files_.erase(fname) == 1; } private: leveldb::port::Mutex mu_; std::set<std::string> locked_files_; }; const int kMaxRetryTimeMillis; // BGThread() is the body of the background thread void BGThread(); static void BGThreadWrapper(void* arg) { reinterpret_cast<ChromiumEnv*>(arg)->BGThread(); } base::HistogramBase* GetMethodIOErrorHistogram() const; // RetrierProvider implementation. int MaxRetryTimeMillis() const override { return kMaxRetryTimeMillis; } base::HistogramBase* GetRetryTimeHistogram(MethodID method) const override; base::HistogramBase* GetRecoveredFromErrorHistogram( MethodID method) const override; base::FilePath test_directory_; std::string name_; std::string uma_ioerror_base_name_; base::Lock mu_; base::ConditionVariable bgsignal_; bool started_bgthread_; // Entry per Schedule() call struct BGItem { void* arg; void (*function)(void*); }; using BGQueue = base::circular_deque<BGItem>; BGQueue queue_; LockTable locks_; std::unique_ptr<leveldb::Cache> file_cache_; }; // Tracks databases open via OpenDatabase() method and exposes them to // memory-infra. The class is thread safe. class LEVELDB_EXPORT DBTracker { public: enum SharedReadCacheUse : int { // Use for databases whose access pattern is dictated by browser code. SharedReadCacheUse_Browser = 0, // Use for databases whose access pattern is directly influenced by Web // APIs, like Indexed DB, etc. SharedReadCacheUse_Web, SharedReadCacheUse_Unified, // When Web == Browser. SharedReadCacheUse_InMemory, // Shared by all in-memory databases. SharedReadCacheUse_NumCacheUses }; // DBTracker singleton instance. static DBTracker* GetInstance(); // Returns the memory-infra dump for |tracked_db|. Can be used to attach // additional info to the database dump, or to properly attribute memory // usage in memory dump providers that also dump |tracked_db|. // Note that |tracked_db| should be a live database instance produced by // OpenDatabase() method or leveldb_env::OpenDB() function. static base::trace_event::MemoryAllocatorDump* GetOrCreateAllocatorDump( base::trace_event::ProcessMemoryDump* pmd, leveldb::DB* tracked_db); // Returns the memory-infra dump for |tracked_memenv|. Can be used to attach // additional info to the database dump, or to properly attribute memory // usage in memory dump providers that also dump |tracked_memenv|. // Note that |tracked_memenv| should be a live Env instance produced by // leveldb_chrome::NewMemEnv(). static base::trace_event::MemoryAllocatorDump* GetOrCreateAllocatorDump( base::trace_event::ProcessMemoryDump* pmd, leveldb::Env* tracked_memenv); // Report counts to UMA. void UpdateHistograms(); // Provides extra information about a tracked database. class TrackedDB : public leveldb::DB { public: // Name that OpenDatabase() was called with. virtual const std::string& name() const = 0; // Options used when opening the database. virtual SharedReadCacheUse block_cache_type() const = 0; }; // Opens a database and starts tracking it. As long as the opened database // is alive (i.e. its instance is not destroyed) the database is exposed to // memory-infra and is enumerated by VisitDatabases() method. // This function is an implementation detail of leveldb_env::OpenDB(), and // has similar guarantees regarding |dbptr| argument. leveldb::Status OpenDatabase(const leveldb_env::Options& options, const std::string& name, TrackedDB** dbptr); private: class MemoryDumpProvider; class TrackedDBImpl; using DatabaseVisitor = base::RepeatingCallback<void(TrackedDB*)>; friend class ChromiumEnvDBTrackerTest; FRIEND_TEST_ALL_PREFIXES(ChromiumEnvDBTrackerTest, IsTrackedDB); FRIEND_TEST_ALL_PREFIXES(ChromiumEnvDBTrackerTest, MemoryDumpCreation); FRIEND_TEST_ALL_PREFIXES(ChromiumEnvDBTrackerTest, MemEnvMemoryDumpCreation); DBTracker(); ~DBTracker(); // Calls |visitor| for each live database. The database is live from the // point it was returned from OpenDatabase() and up until its instance is // destroyed. // The databases may be visited in an arbitrary order. // This function takes a lock, preventing any database from being opened or // destroyed (but doesn't lock the databases themselves). void VisitDatabases(const DatabaseVisitor& visitor); // Checks if |db| is tracked. bool IsTrackedDB(const leveldb::DB* db) const; void DatabaseOpened(TrackedDBImpl* database, SharedReadCacheUse cache_use); void DatabaseDestroyed(TrackedDBImpl* database, SharedReadCacheUse cache_use); // Protect databases_ and mdp_ members. mutable base::Lock databases_lock_; base::LinkedList<TrackedDBImpl> databases_; std::unique_ptr<MemoryDumpProvider> mdp_; DISALLOW_COPY_AND_ASSIGN(DBTracker); }; // Opens a database with the specified "name" and "options" (see note) and // exposes it to Chrome's tracing (see DBTracker for details). The function // guarantees that: // 1. |dbptr| is not touched on failure // 2. |dbptr| is not NULL on success // // Note: All |options| values are honored, except if options.env is an in-memory // Env. In this case the block cache is disabled and a minimum write buffer size // is used to conserve memory with all other values honored. LEVELDB_EXPORT leveldb::Status OpenDB(const leveldb_env::Options& options, const std::string& name, std::unique_ptr<leveldb::DB>* dbptr); // Copies the content of |dbptr| into a fresh database to remove traces of // deleted data. |options| and |name| of the old database are required to create // an identical copy. |dbptr| will be replaced with the new database on success. // If the rewrite fails e.g. because we can't write to the temporary location, // the old db is returned if possible, otherwise |*dbptr| can become NULL. // The rewrite will only be performed if |kLevelDBRewriteFeature| is enabled. LEVELDB_EXPORT leveldb::Status RewriteDB(const leveldb_env::Options& options, const std::string& name, std::unique_ptr<leveldb::DB>* dbptr); LEVELDB_EXPORT base::StringPiece MakeStringPiece(const leveldb::Slice& s); LEVELDB_EXPORT leveldb::Slice MakeSlice(const base::StringPiece& s); LEVELDB_EXPORT leveldb::Slice MakeSlice(base::span<const uint8_t> s); } // namespace leveldb_env // Redefine DeleteFile if necessary. #if defined(OS_WIN) && defined(ENV_CHROMIUM_DELETEFILE_UNDEFINED) #define DeleteFile DeleteFileW #endif #endif // THIRD_PARTY_LEVELDATABASE_ENV_CHROMIUM_H_
$(document).ready(function(){function u(e,t,n){var r="-webkit-transform",i="translate3d(0,0,0)",s=e.css(r),o=!s||!s.match(/^\s*none\s*$/i);e.css(r,o?i:s+" "+i);try{return t.apply(this,n)}finally{e.css(r,s)}}function f(e,t,n,r){var i=!1,s,o,u=$.speed(t,n,r),a=this;if(!e)return!1;for(var f in e)s=e[f],f==="height"?s==="hide"?(this.css("display","none"),i=!0,u.complete()):s==="show"&&(this.css("display",""),i=!0,u.complete()):f==="width"?s==="hide"?(this.css("display","none"),i=!0,u.complete()):s==="show"&&(this.css("display",""),i=!0,u.complete()):f==="left"&&(o=this.css("left").replace("px","")*1,typeof s=="string"&&(s.indexOf("-=")===0?o-=s.replace("-=","")*1:s.indexOf("+=")===0&&(o+=s.replace("+=","")*1)),i=!0,this.css("-webkit-perspective",1e3),this.css("-webkit-backface-visibility","hidden"),h(this[0],o,u.duration,"linear",u.complete));return i}function l(e,t,n,r){o&&(n||(n="ease"),b(e,"opacity",t,n),p(e,0),e.addEventListener("webkitTransitionEnd",$.proxy(function(){w(e),e.style.display="none",p(e,1),r&&r()},this),!1))}function c(e,t,n,r){o&&(n||(n="ease"),b(e,"opacity",t,n),p(e,1),e.addEventListener("webkitTransitionEnd",$.proxy(function(){w(e),e.style.display==="none"&&(e.style.display=""),r&&r()},this),!1))}function h(e,t,n,r,i){o&&(y(e,n,r),d(e,t),e.___animationEndHandler=i,e.___internalEndHandler=$.proxy(E,{}),e.addEventListener("webkitTransitionEnd",e.___internalEndHandler,!1))}function p(e,t){var n;o&&(n=e.style||e,n.opacity=t)}function d(e,t){var n;o?(e.___translateX=t,n=e.style||e,n.webkitTransform="translateX("+t+"px)"):e.style.left=t+"px"}function v(e,t){var n;o?(e.___translateY=t,n=e.style||e,n.webkitTransform="translateY("+t+"px)"):e.style.top=t+"px"}function m(e){var t,n,r,i,s;if(!e)return 0;if(o){t=e.style||e,n=t.webkitTransform;if(typeof n=="string"){r=new RegExp("translate(3d|X|)\\(-*(\\d+)"),i=r.exec(n);if(i){s=parseFloat(i[1]);if(isFinite(s))return s}}}else{var s=parseInt($(e).css("left"));if(isFinite(s))return s}return 0}function g(e){var t,n,r,i,s;if(!e)return 0;if(o){t=e.style||e,n=t.webkitTransform;if(typeof n=="string"){r=new RegExp("translate(3d|X|)\\(.*,\\s*-*(\\d+)"),i=r.exec(n);if(i){s=parseFloat(i[1]);if(isFinite(s))return s}}}else{var s=parseInt(jQuery(e).css("top"));if(isFinite(s))return s}return 0}function y(e,t,n){n||(n="ease"),b(e,"-webkit-transform",t,n)}function b(e,t,n,r){if(o){var i=e.style;i.webkitTransitionProperty=t,i.webkitTransitionDuration=n+"ms",i.webkitTransitionTimingFunction=r}}function w(e){if(o){var t=e.style;t.webkitTransitionProperty="none";var n=e.___internalEndHandler;n&&(delete e.___internalEndHandler,e.removeEventListener("webkitTransitionEnd",n,!1))}}function E(e){try{var t,n;switch(e.type){case"webkitTransitionEnd":t=e.target,t&&(w(t),t.___animationEndHandler&&(n=t.___animationEndHandler,t.___animationEndHandler=null,n(e)))}}catch(r){window.console&&window.console.log&&window.console.log("[ew219290] error: "+(r.message?r.message:r)+", event: "+e)}return!0}var e=window.navigator.userAgent,t=e.match(new RegExp("android ((1\\.)|(2\\.([^345]+)))","i")),n=window.WebKitCSSMatrix?!t:!1,r=typeof e=="string"&&!!e.match(/applewebkit/),i="ontouchend"in document,s=document.createElement("div"),o;s.setAttribute("style","transition:top 1s ease;-webkit-transition:top 1s ease;-moz-transition:top 1s ease;-o-transition:top 1s ease;"),document.body.appendChild(s),o=!!(s.style.transition||s.style.webkitTransition||s.style.MozTransition||s.style.OTransitionDuration),s.parentNode.removeChild(s),s=null;var a=jQuery.fn.animate;jQuery.fn.animate=function(e,t,n,i){if(!r||!f.apply(this,arguments))return u.call(this,this,function(){return a.apply(this,arguments)},arguments)}});
from setuptools import setup, find_packages, Extension from Cython.Build import cythonize setup( name='PatchMatch', license='Creative Commons Attribution-Noncommercial-Share Alike license', packages=find_packages(), ext_modules=cythonize([ Extension( "patchmatch.pm", ["patchmatch/pm.pyx"], extra_compile_args=['-O3']) ]), zip_safe=False, install_requires=['cython', 'numpy', 'pillow'], )
var old_summary = null; /** * get the raw markdown summary and display it in a textedit area instead of * the rendered HTML * param: optional text to append to the textedit area */ function make_summary_editable(text) { var $summary = $("#summary"); if (typeof text !== "string") { text = ''; } else { text = "\n"+text; } // if a textarea already, append to it if ($summary.is('textarea')) { $summary.val(function(index, value){ return value + text; }); // if not a textarea already, create one and replace the original div with it } else { $.getJSON( "/events/"+get_current_event_id()+"/summary", function(data) { var textarea = $("<textarea></textarea>") .attr({ "id": "summary", "name": "summary", "class": "input-xxlarge editable", "rows": "10" }) .val(data.summary + text); $summary.replaceWith(textarea); $("#summary").on("save", summary_save); }, 'json' // forces return to be json decoded ); } } /** * Depending on the current state either show the editable summary form or * save the markdown summary and render as HTML */ function summary_save(e, event, history) { var new_summary = $("#summary").val(); var Diff = new diff_match_patch(); var diff = Diff.diff_main(old_summary, new_summary); Diff.diff_cleanupSemantic(diff); diff = Diff.diff_prettyHtml(diff); history.summary = diff; event.summary = new_summary; var html = $("<div></div>"); html.attr("id", "summary"); html.attr("name", "summary"); html.attr("class", "input-xxlarge editable"); html.attr("rows", "10"); html.html(markdown.toHTML($("#summary").val())); $("#summary").remove(); $("#summarywrapper").append(html); $("#summaryundobutton").hide(); $("#summary").on("edit", make_summary_editable); } /** * just abort editing and display the stored data as rendered HTML */ function summary_undo_button() { $.getJSON("/events/"+get_current_event_id()+"/summary", function(data) { $('#summary').val(data.summary); }); } $("#summary").on("edit", make_summary_editable); $("#summaryundobutton").on("click", summary_undo_button); $.getJSON("/events/"+get_current_event_id()+"/summary", function(data) { old_summary = data.summary; $("#summary").html(markdown.toHTML(data.summary)); });
import main as m if __name__ == '__main__': completed = 0 methodsNotWorking = [] if m.karacaEncrypt("compsciclub") == "b4lc2cspm3caca": completed += 1 else: methodsNotWorking.append("karacaEncrypt") if m.convertToHex("compsciclub") == "63 6f 6d 70 73 63 69 63 6c 75 62": completed += 1 else: methodsNotWorking.append("convertToHex") if m.moran(132) == "H" and m.moran(133) == "M" and m.moran(134) == "Neither": completed += 1 else: methodsNotWorking.append("moran") print("You completed " + str(completed) + " tasks.") if completed != 3: print("The following are not working:") for method in methodsNotWorking: print("\t" + method) else: print("Congratulations!")
from django.contrib import admin from .models import Article # Register your models here. # admin.site.register(Article) @admin.register(Article) class ArticleModel(admin.ModelAdmin): list_filter = ('title', 'description') list_display = ('title', 'description')
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ 'use strict'; import type {SchemaType} from '../../CodegenSchema'; // File path -> contents type FilesOutput = Map<string, string>; const FileTemplate = ({ libraryName, componentNames, }: { libraryName: string, componentNames: string, }) => ` /** * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). * * Do not edit this file as changes may cause incorrect behavior and will be lost * once the code is regenerated. * * ${'@'}generated by codegen project: GenerateShadowNodeCpp.js */ #include <react/renderer/components/${libraryName}/ShadowNodes.h> namespace facebook { namespace react { ${componentNames} } // namespace react } // namespace facebook `; const ComponentTemplate = ({className}: {className: string}) => ` extern const char ${className}ComponentName[] = "${className}"; `.trim(); module.exports = { generate( libraryName: string, schema: SchemaType, packageName?: string, assumeNonnull: boolean = false, ): FilesOutput { const fileName = 'ShadowNodes.cpp'; const componentNames = Object.keys(schema.modules) .map(moduleName => { const module = schema.modules[moduleName]; if (module.type !== 'Component') { return; } const {components} = module; // No components in this module if (components == null) { return null; } return Object.keys(components) .map(componentName => { if (components[componentName].interfaceOnly === true) { return; } const replacedTemplate = ComponentTemplate({ className: componentName, }); return replacedTemplate; }) .join('\n'); }) .filter(Boolean) .join('\n'); const replacedTemplate = FileTemplate({ componentNames, libraryName, }); return new Map([[fileName, replacedTemplate]]); }, };
# -*- coding: utf-8 -*- # Copyright (c) 2019, Fivo and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class MasterProduk(Document): pass
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = class_1 + class_2 new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) # Code ends here # -------------- # Code starts here courses = {'Math':65, 'English':70, 'History':80, 'French':70, 'Science':60} total = sum(courses.values()) percentage = (total/500)*100 print(percentage) # Code ends here # -------------- # Code starts here mathematics = {'Geoffrey Hinton':78, 'Andrew Ng':95, 'Sebastian Raschka':65, 'Yoshua Benjio':50,'Hilary Mason':70,'Corinna Cortes':66,'Peter Warden':75} topper = max(mathematics, key = mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here first_name = topper.split()[0] last_name = topper.split()[1] full_name = last_name + " " + first_name certificate_name = full_name.upper() print(certificate_name) # Code ends here
import dedent from 'ts-dedent'; export default { title: 'Atoms/Custom Scrollbar', parameters: { design: { type: 'iframe', url: 'https://projects.invisionapp.com/share/3C11ABUSUADV#/454587111_WYSIWYG_Large_Tablet', }, docs: { description: { component: dedent(` Parts of the designs show a custom scrollbar, for example when tables need to scroll horizontally. This is doable in modern browsers just with CSS, but should be used sparingly. To prevent having an impact on usability, on devices with a mouse the width/height of the scrollbar will be decided by the browser/operating system. On touchscreen devices, where users are less likely to use the scrollbar directly (e.g. compared to swiping through the content) then we show a narrower scrollbar as shown in the designs. `), }, }, }, }; const Template = () => ` <div class="custom-scrollbar u-w-80 u-h-80 u-overflow-auto"> <div class="u-w-screen u-h-screen" style="background: radial-gradient(var(--t-colors-mercury), var(--t-colors-white))"></div> </div> `; export const CustomScrollbar = Template.bind({});
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.l = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // identity function for calling harmory imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ // define getter function for harmory exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ }; /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 22); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; eval("/* harmony default export */ exports[\"default\"] = {\n props: {\n beginzero:{\n type: Boolean,\n default: function () { return true; },\n },\n datalabel: {\n type: String,\n default: function () { return 'My dataset'; },\n },\n labels: {\n type: Array,\n default: function () { return ['first', 'second', 'third', 'fourth']; },\n },\n data: {\n type: Array,\n default: function () { return [40, 60, 45, 70]; },\n },\n width: {\n type: Number,\n default: function () { return null; },\n },\n height: {\n type: Number,\n default: function () { return null; },\n },\n bordercolor: {\n default: function () { return \"rgba(75,192,192,1)\"; },\n },\n backgroundcolor: {\n default: function () { return \"rgba(75,192,192,0.4)\"; },\n },\n scalesdisplay: {\n type: Boolean,\n default: function () { return true; },\n },\n target: {\n type: String,\n default: function () { return null; },\n },\n datasets:{\n type: Array,\n default: function () { return null; },\n },\n option:{\n type: Object,\n default: function () { return null; },\n },\n bind:{\n type: Boolean,\n default: function () { return false; },\n }\n },\n data: function data () {\n return {\n isDatasetsOverride : false,\n isOptionOverride : false,\n type : null,\n canvas : null,\n context : null,\n chart: null,\n chart_data : {\n labels: this.labels,\n datasets: this.datasets,\n },\n options :{\n responsive:false,\n maintainAspectRatio:false,\n scales: {\n yAxes: [{\n display: this.scalesdisplay,\n ticks: {\n beginAtZero:this.beginzero,\n }\n }]\n },\n },\n };\n },\n watch:{\n data: {\n handler: function (val, oldVal) {\n if(!this.isDatasetsOverride&&this.bind)\n {\n this.chart_data.datasets[0].data = this.data;\n this.renderChart();\n }\n },\n deep: true\n },\n labels: {\n handler: function (val, oldVal) {\n if(this.bind)\n {\n this.chart_data.labels = val;\n this.renderChart();\n }\n },\n deep: true\n },\n datasets: {\n handler: function (val, oldVal) {\n var this$1 = this;\n\n if(this.isDatasetsOverride&&this.bind)\n {\n this.cleanChart();\n this.sleep(5).then(function () {\n this$1.renderChart();\n })\n }\n },\n deep: true,\n },\n },\n methods:{\n sleep: function sleep (time) {\n return new Promise(function (resolve) { return setTimeout(resolve, time); });\n },\n setDatasets: function setDatasets(){\n this.chart_data.datasets = this.datasets;\n },\n setOption: function setOption(){\n this.options = this.option;\n },\n initTargetCanvas: function initTargetCanvas(){\n if(this.target==null){\n this.canvas = this.$refs.canvas;\n this.context = this.$refs.canvas.getContext('2d');\n this.renderChart();\n }\n else {\n this.canvas = document.getElementById(this.target);\n this.context = document.getElementById(this.target).getContext('2d');\n if(typeof datasets == 'undefined')\n window.datasets = [];\n if(typeof datasets[this.target] == 'undefined')\n window.datasets[this.target] =[];\n this.appendChart();\n }\n },\n cleanChart: function cleanChart(){\n if(this.chart!=null)\n this.chart.destroy();\n },\n checkOverride: function checkOverride(){\n if(this.datasets!=null)\n {\n this.setDatasets();\n this.isDatasetsOverride = true;\n // console.log('override the datasets');\n }\n if(this.option!=null)\n {\n this.setOption();\n this.isOptionOverride = true;\n // console.log('override the datasets');\n }\n },\n renderChart: function renderChart() {\n // console.log('renderChart');\n this.cleanChart();\n this.chart = new Chart(this.context, {\n type: this.type,\n data: this.chart_data,\n options: this.options,\n });\n },\n appendChart: function appendChart() {\n // console.log('appendChart');\n window.datasets[this.target].push(this.chart_data.datasets[0]);\n this.chart_data.datasets = window.datasets[this.target];\n if(document.getElementById(this.target).getAttribute(\"count\") == this.chart_data.datasets.length)\n {\n this.renderChart();\n }\n },\n checkSize: function checkSize(){\n if((this.width==null||this.height==null) && !this.isOptionOverride)\n {\n this.options.responsive = true;\n this.options.maintainAspectRatio = true;\n }\n },\n },\n mounted: function mounted(){\n this.checkOverride();\n this.checkSize();\n this.initTargetCanvas();\n },\n beforeDestroy: function beforeDestroy(){\n this.cleanChart();\n // console.log('Line Chart Before Destroy');\n }\n};\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMC5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL3Z1ZS1jaGFydGpzLWxpYi5qcz84YTZhIl0sInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBkZWZhdWx0e1xuICAgIHByb3BzOiB7XG4gICAgICAgIGJlZ2luemVybzp7XG4gICAgICAgICAgICB0eXBlOiBCb29sZWFuLFxuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gdHJ1ZSxcbiAgICAgICAgfSxcbiAgICAgICAgZGF0YWxhYmVsOiB7XG4gICAgICAgICAgICB0eXBlOiBTdHJpbmcsXG4gICAgICAgICAgICBkZWZhdWx0OiAoKSA9PiAnTXkgZGF0YXNldCcsXG4gICAgICAgIH0sXG4gICAgICAgIGxhYmVsczoge1xuICAgICAgICAgICAgdHlwZTogQXJyYXksXG4gICAgICAgICAgICBkZWZhdWx0OiAoKSA9PiBbJ2ZpcnN0JywgJ3NlY29uZCcsICd0aGlyZCcsICdmb3VydGgnXSxcbiAgICAgICAgfSxcbiAgICAgICAgZGF0YToge1xuICAgICAgICAgICAgdHlwZTogQXJyYXksXG4gICAgICAgICAgICBkZWZhdWx0OiAoKSA9PiBbNDAsIDYwLCA0NSwgNzBdLFxuICAgICAgICB9LFxuICAgICAgICB3aWR0aDoge1xuICAgICAgICAgICAgdHlwZTogTnVtYmVyLFxuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gbnVsbCxcbiAgICAgICAgfSxcbiAgICAgICAgaGVpZ2h0OiB7XG4gICAgICAgICAgICB0eXBlOiBOdW1iZXIsXG4gICAgICAgICAgICBkZWZhdWx0OiAoKSA9PiBudWxsLFxuICAgICAgICB9LFxuICAgICAgICBib3JkZXJjb2xvcjoge1xuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gXCJyZ2JhKDc1LDE5MiwxOTIsMSlcIixcbiAgICAgICAgfSxcbiAgICAgICAgYmFja2dyb3VuZGNvbG9yOiB7XG4gICAgICAgICAgICBkZWZhdWx0OiAoKSA9PiBcInJnYmEoNzUsMTkyLDE5MiwwLjQpXCIsXG4gICAgICAgIH0sXG4gICAgICAgIHNjYWxlc2Rpc3BsYXk6IHtcbiAgICAgICAgICAgIHR5cGU6IEJvb2xlYW4sXG4gICAgICAgICAgICBkZWZhdWx0OiAoKSA9PiB0cnVlLFxuICAgICAgICB9LFxuICAgICAgICB0YXJnZXQ6IHtcbiAgICAgICAgICAgIHR5cGU6IFN0cmluZyxcbiAgICAgICAgICAgIGRlZmF1bHQ6ICgpID0+IG51bGwsXG4gICAgICAgIH0sXG4gICAgICAgIGRhdGFzZXRzOntcbiAgICAgICAgICAgIHR5cGU6IEFycmF5LFxuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gbnVsbCxcbiAgICAgICAgfSxcbiAgICAgICAgb3B0aW9uOntcbiAgICAgICAgICAgIHR5cGU6IE9iamVjdCxcbiAgICAgICAgICAgIGRlZmF1bHQ6ICgpID0+IG51bGwsXG4gICAgICAgIH0sXG4gICAgICAgIGJpbmQ6e1xuICAgICAgICAgICAgdHlwZTogQm9vbGVhbixcbiAgICAgICAgICAgIGRlZmF1bHQ6ICgpID0+ZmFsc2UsXG4gICAgICAgIH1cbiAgICB9LFxuICAgIGRhdGEgKCkge1xuICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgaXNEYXRhc2V0c092ZXJyaWRlIDogZmFsc2UsXG4gICAgICAgICAgICBpc09wdGlvbk92ZXJyaWRlIDogZmFsc2UsXG4gICAgICAgICAgICB0eXBlIDogbnVsbCxcbiAgICAgICAgICAgIGNhbnZhcyA6IG51bGwsXG4gICAgICAgICAgICBjb250ZXh0IDogbnVsbCxcbiAgICAgICAgICAgIGNoYXJ0OiBudWxsLFxuICAgICAgICAgICAgY2hhcnRfZGF0YSA6IHtcbiAgICAgICAgICAgICAgICBsYWJlbHM6IHRoaXMubGFiZWxzLFxuICAgICAgICAgICAgICAgIGRhdGFzZXRzOiB0aGlzLmRhdGFzZXRzLFxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIG9wdGlvbnMgOntcbiAgICAgICAgICAgICAgICByZXNwb25zaXZlOmZhbHNlLFxuICAgICAgICAgICAgICAgIG1haW50YWluQXNwZWN0UmF0aW86ZmFsc2UsXG4gICAgICAgICAgICAgICAgc2NhbGVzOiB7XG4gICAgICAgICAgICAgICAgICAgIHlBeGVzOiBbe1xuICAgICAgICAgICAgICAgICAgICAgICAgZGlzcGxheTogdGhpcy5zY2FsZXNkaXNwbGF5LFxuICAgICAgICAgICAgICAgICAgICAgICAgdGlja3M6IHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBiZWdpbkF0WmVybzp0aGlzLmJlZ2luemVybyxcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgfV1cbiAgICAgICAgICAgICAgICB9LFxuICAgICAgICAgICAgfSxcbiAgICAgICAgfTtcbiAgICB9LFxuICAgIHdhdGNoOntcbiAgICAgICAgZGF0YToge1xuICAgICAgICAgICAgaGFuZGxlcjogZnVuY3Rpb24gKHZhbCwgb2xkVmFsKSB7XG4gICAgICAgICAgICAgICAgaWYoIXRoaXMuaXNEYXRhc2V0c092ZXJyaWRlJiZ0aGlzLmJpbmQpXG4gICAgICAgICAgICAgICAge1xuICAgICAgICAgICAgICAgICAgICB0aGlzLmNoYXJ0X2RhdGEuZGF0YXNldHNbMF0uZGF0YSA9IHRoaXMuZGF0YTtcbiAgICAgICAgICAgICAgICAgICAgdGhpcy5yZW5kZXJDaGFydCgpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0sXG4gICAgICAgICAgICBkZWVwOiB0cnVlXG4gICAgICAgIH0sXG4gICAgICAgIGxhYmVsczoge1xuICAgICAgICAgICAgaGFuZGxlcjogZnVuY3Rpb24gKHZhbCwgb2xkVmFsKSB7XG4gICAgICAgICAgICAgICAgaWYodGhpcy5iaW5kKVxuICAgICAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgICAgICAgdGhpcy5jaGFydF9kYXRhLmxhYmVscyA9IHZhbDtcbiAgICAgICAgICAgICAgICAgICAgdGhpcy5yZW5kZXJDaGFydCgpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0sXG4gICAgICAgICAgICBkZWVwOiB0cnVlXG4gICAgICAgIH0sXG4gICAgICAgIGRhdGFzZXRzOiB7XG4gICAgICAgICAgICBoYW5kbGVyOiBmdW5jdGlvbiAodmFsLCBvbGRWYWwpIHtcbiAgICAgICAgICAgICAgICBpZih0aGlzLmlzRGF0YXNldHNPdmVycmlkZSYmdGhpcy5iaW5kKVxuICAgICAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgICAgICAgdGhpcy5jbGVhbkNoYXJ0KCk7XG4gICAgICAgICAgICAgICAgICAgIHRoaXMuc2xlZXAoNSkudGhlbigoKSA9PiB7XG4gICAgICAgICAgICAgICAgICAgICAgICB0aGlzLnJlbmRlckNoYXJ0KCk7XG4gICAgICAgICAgICAgICAgICAgIH0pXG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIGRlZXA6IHRydWUsXG4gICAgICAgIH0sXG4gICAgfSxcbiAgICBtZXRob2RzOntcbiAgICAgICAgc2xlZXAgKHRpbWUpIHtcbiAgICAgICAgICAgIHJldHVybiBuZXcgUHJvbWlzZSgocmVzb2x2ZSkgPT4gc2V0VGltZW91dChyZXNvbHZlLCB0aW1lKSk7XG4gICAgICAgIH0sXG4gICAgICAgIHNldERhdGFzZXRzKCl7XG4gICAgICAgICAgICB0aGlzLmNoYXJ0X2RhdGEuZGF0YXNldHMgPSB0aGlzLmRhdGFzZXRzO1xuICAgICAgICB9LFxuICAgICAgICBzZXRPcHRpb24oKXtcbiAgICAgICAgICAgIHRoaXMub3B0aW9ucyA9IHRoaXMub3B0aW9uO1xuICAgICAgICB9LFxuICAgICAgICBpbml0VGFyZ2V0Q2FudmFzKCl7XG4gICAgICAgICAgICBpZih0aGlzLnRhcmdldD09bnVsbCl7XG4gICAgICAgICAgICAgICAgdGhpcy5jYW52YXMgPSB0aGlzLiRyZWZzLmNhbnZhcztcbiAgICAgICAgICAgICAgICB0aGlzLmNvbnRleHQgPSB0aGlzLiRyZWZzLmNhbnZhcy5nZXRDb250ZXh0KCcyZCcpO1xuICAgICAgICAgICAgICAgIHRoaXMucmVuZGVyQ2hhcnQoKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgIHRoaXMuY2FudmFzID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQodGhpcy50YXJnZXQpO1xuICAgICAgICAgICAgICAgIHRoaXMuY29udGV4dCA9IGRvY3VtZW50LmdldEVsZW1lbnRCeUlkKHRoaXMudGFyZ2V0KS5nZXRDb250ZXh0KCcyZCcpO1xuICAgICAgICAgICAgICAgIGlmKHR5cGVvZiBkYXRhc2V0cyA9PSAndW5kZWZpbmVkJylcbiAgICAgICAgICAgICAgICAgICAgd2luZG93LmRhdGFzZXRzID0gW107XG4gICAgICAgICAgICAgICAgaWYodHlwZW9mIGRhdGFzZXRzW3RoaXMudGFyZ2V0XSA9PSAndW5kZWZpbmVkJylcbiAgICAgICAgICAgICAgICAgICAgd2luZG93LmRhdGFzZXRzW3RoaXMudGFyZ2V0XSA9W107XG4gICAgICAgICAgICAgICAgdGhpcy5hcHBlbmRDaGFydCgpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9LFxuICAgICAgICBjbGVhbkNoYXJ0KCl7XG4gICAgICAgICAgICBpZih0aGlzLmNoYXJ0IT1udWxsKVxuICAgICAgICAgICAgICAgIHRoaXMuY2hhcnQuZGVzdHJveSgpO1xuICAgICAgICB9LFxuICAgICAgICBjaGVja092ZXJyaWRlKCl7XG4gICAgICAgICAgICBpZih0aGlzLmRhdGFzZXRzIT1udWxsKVxuICAgICAgICAgICAge1xuICAgICAgICAgICAgICAgIHRoaXMuc2V0RGF0YXNldHMoKTtcbiAgICAgICAgICAgICAgICB0aGlzLmlzRGF0YXNldHNPdmVycmlkZSA9IHRydWU7XG4gICAgICAgICAgICAgICAgLy8gY29uc29sZS5sb2coJ292ZXJyaWRlIHRoZSBkYXRhc2V0cycpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgaWYodGhpcy5vcHRpb24hPW51bGwpXG4gICAgICAgICAgICB7XG4gICAgICAgICAgICAgICAgdGhpcy5zZXRPcHRpb24oKTtcbiAgICAgICAgICAgICAgICB0aGlzLmlzT3B0aW9uT3ZlcnJpZGUgPSB0cnVlO1xuICAgICAgICAgICAgICAgIC8vIGNvbnNvbGUubG9nKCdvdmVycmlkZSB0aGUgZGF0YXNldHMnKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSxcbiAgICAgICAgcmVuZGVyQ2hhcnQoKSB7XG4gICAgICAgICAgICAvLyBjb25zb2xlLmxvZygncmVuZGVyQ2hhcnQnKTtcbiAgICAgICAgICAgIHRoaXMuY2xlYW5DaGFydCgpO1xuICAgICAgICAgICAgdGhpcy5jaGFydCA9IG5ldyBDaGFydCh0aGlzLmNvbnRleHQsIHtcbiAgICAgICAgICAgICAgICB0eXBlOiB0aGlzLnR5cGUsXG4gICAgICAgICAgICAgICAgZGF0YTogdGhpcy5jaGFydF9kYXRhLFxuICAgICAgICAgICAgICAgIG9wdGlvbnM6IHRoaXMub3B0aW9ucyxcbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9LFxuICAgICAgICBhcHBlbmRDaGFydCgpIHtcbiAgICAgICAgICAgIC8vIGNvbnNvbGUubG9nKCdhcHBlbmRDaGFydCcpO1xuICAgICAgICAgICAgd2luZG93LmRhdGFzZXRzW3RoaXMudGFyZ2V0XS5wdXNoKHRoaXMuY2hhcnRfZGF0YS5kYXRhc2V0c1swXSk7XG4gICAgICAgICAgICB0aGlzLmNoYXJ0X2RhdGEuZGF0YXNldHMgPSB3aW5kb3cuZGF0YXNldHNbdGhpcy50YXJnZXRdO1xuICAgICAgICAgICAgaWYoZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQodGhpcy50YXJnZXQpLmdldEF0dHJpYnV0ZShcImNvdW50XCIpID09IHRoaXMuY2hhcnRfZGF0YS5kYXRhc2V0cy5sZW5ndGgpXG4gICAgICAgICAgICB7XG4gICAgICAgICAgICAgICAgdGhpcy5yZW5kZXJDaGFydCgpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9LFxuICAgICAgICBjaGVja1NpemUoKXtcbiAgICAgICAgICAgIGlmKCh0aGlzLndpZHRoPT1udWxsfHx0aGlzLmhlaWdodD09bnVsbCkgJiYgIXRoaXMuaXNPcHRpb25PdmVycmlkZSlcbiAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgICB0aGlzLm9wdGlvbnMucmVzcG9uc2l2ZSA9IHRydWU7XG4gICAgICAgICAgICAgICAgdGhpcy5vcHRpb25zLm1haW50YWluQXNwZWN0UmF0aW8gPSB0cnVlO1xuICAgICAgICAgICAgfVxuICAgICAgICB9LFxuICAgIH0sXG4gICAgbW91bnRlZCgpe1xuICAgICAgICB0aGlzLmNoZWNrT3ZlcnJpZGUoKTtcbiAgICAgICAgdGhpcy5jaGVja1NpemUoKTtcbiAgICAgICAgdGhpcy5pbml0VGFyZ2V0Q2FudmFzKCk7XG4gICAgfSxcbiAgICBiZWZvcmVEZXN0cm95KCl7XG4gICAgICAgIHRoaXMuY2xlYW5DaGFydCgpO1xuICAgICAgICAvLyBjb25zb2xlLmxvZygnTGluZSBDaGFydCBCZWZvcmUgRGVzdHJveScpO1xuICAgIH1cbn1cblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyByZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL3Z1ZS1jaGFydGpzLWxpYi5qcyJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOyIsInNvdXJjZVJvb3QiOiIifQ=="); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { eval("var __vue_exports__, __vue_options__\nvar __vue_styles__ = {}\n\n/* script */\n__vue_exports__ = __webpack_require__(8)\n\n/* template */\nvar __vue_template__ = __webpack_require__(15)\n__vue_options__ = __vue_exports__ = __vue_exports__ || {}\nif (\n typeof __vue_exports__.default === \"object\" ||\n typeof __vue_exports__.default === \"function\"\n) {\nif (Object.keys(__vue_exports__).some(function (key) { return key !== \"default\" && key !== \"__esModule\" })) {console.error(\"named exports are not supported in *.vue files.\")}\n__vue_options__ = __vue_exports__ = __vue_exports__.default\n}\nif (typeof __vue_options__ === \"function\") {\n __vue_options__ = __vue_options__.options\n}\n__vue_options__.__file = \"/var/www/laravel/vue-charts-demo/resources/assets/js/vue-charts/src/components/chartjs-bar.vue\"\n__vue_options__.render = __vue_template__.render\n__vue_options__.staticRenderFns = __vue_template__.staticRenderFns\n\n/* hot reload */\nif (false) {(function () {\n var hotAPI = require(\"vue-hot-reload-api\")\n hotAPI.install(require(\"vue\"), false)\n if (!hotAPI.compatible) return\n module.hot.accept()\n if (!module.hot.data) {\n hotAPI.createRecord(\"data-v-25c2c9c8\", __vue_options__)\n } else {\n hotAPI.reload(\"data-v-25c2c9c8\", __vue_options__)\n }\n})()}\nif (__vue_options__.functional) {console.error(\"[vue-loader] chartjs-bar.vue: functional components are not supported and should be defined in plain js files using render functions.\")}\n\nmodule.exports = __vue_exports__\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMS5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLWJhci52dWU/YjM4MSJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgX192dWVfZXhwb3J0c19fLCBfX3Z1ZV9vcHRpb25zX19cbnZhciBfX3Z1ZV9zdHlsZXNfXyA9IHt9XG5cbi8qIHNjcmlwdCAqL1xuX192dWVfZXhwb3J0c19fID0gcmVxdWlyZShcIiEhYnVibGUtbG9hZGVyIXZ1ZS1sb2FkZXIvbGliL3NlbGVjdG9yP3R5cGU9c2NyaXB0JmluZGV4PTAhLi9jaGFydGpzLWJhci52dWVcIilcblxuLyogdGVtcGxhdGUgKi9cbnZhciBfX3Z1ZV90ZW1wbGF0ZV9fID0gcmVxdWlyZShcIiEhdnVlLWxvYWRlci9saWIvdGVtcGxhdGUtY29tcGlsZXI/aWQ9ZGF0YS12LTI1YzJjOWM4IXZ1ZS1sb2FkZXIvbGliL3NlbGVjdG9yP3R5cGU9dGVtcGxhdGUmaW5kZXg9MCEuL2NoYXJ0anMtYmFyLnZ1ZVwiKVxuX192dWVfb3B0aW9uc19fID0gX192dWVfZXhwb3J0c19fID0gX192dWVfZXhwb3J0c19fIHx8IHt9XG5pZiAoXG4gIHR5cGVvZiBfX3Z1ZV9leHBvcnRzX18uZGVmYXVsdCA9PT0gXCJvYmplY3RcIiB8fFxuICB0eXBlb2YgX192dWVfZXhwb3J0c19fLmRlZmF1bHQgPT09IFwiZnVuY3Rpb25cIlxuKSB7XG5pZiAoT2JqZWN0LmtleXMoX192dWVfZXhwb3J0c19fKS5zb21lKGZ1bmN0aW9uIChrZXkpIHsgcmV0dXJuIGtleSAhPT0gXCJkZWZhdWx0XCIgJiYga2V5ICE9PSBcIl9fZXNNb2R1bGVcIiB9KSkge2NvbnNvbGUuZXJyb3IoXCJuYW1lZCBleHBvcnRzIGFyZSBub3Qgc3VwcG9ydGVkIGluICoudnVlIGZpbGVzLlwiKX1cbl9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX2V4cG9ydHNfXyA9IF9fdnVlX2V4cG9ydHNfXy5kZWZhdWx0XG59XG5pZiAodHlwZW9mIF9fdnVlX29wdGlvbnNfXyA9PT0gXCJmdW5jdGlvblwiKSB7XG4gIF9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX29wdGlvbnNfXy5vcHRpb25zXG59XG5fX3Z1ZV9vcHRpb25zX18uX19maWxlID0gXCIvdmFyL3d3dy9sYXJhdmVsL3Z1ZS1jaGFydHMtZGVtby9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1iYXIudnVlXCJcbl9fdnVlX29wdGlvbnNfXy5yZW5kZXIgPSBfX3Z1ZV90ZW1wbGF0ZV9fLnJlbmRlclxuX192dWVfb3B0aW9uc19fLnN0YXRpY1JlbmRlckZucyA9IF9fdnVlX3RlbXBsYXRlX18uc3RhdGljUmVuZGVyRm5zXG5cbi8qIGhvdCByZWxvYWQgKi9cbmlmIChtb2R1bGUuaG90KSB7KGZ1bmN0aW9uICgpIHtcbiAgdmFyIGhvdEFQSSA9IHJlcXVpcmUoXCJ2dWUtaG90LXJlbG9hZC1hcGlcIilcbiAgaG90QVBJLmluc3RhbGwocmVxdWlyZShcInZ1ZVwiKSwgZmFsc2UpXG4gIGlmICghaG90QVBJLmNvbXBhdGlibGUpIHJldHVyblxuICBtb2R1bGUuaG90LmFjY2VwdCgpXG4gIGlmICghbW9kdWxlLmhvdC5kYXRhKSB7XG4gICAgaG90QVBJLmNyZWF0ZVJlY29yZChcImRhdGEtdi0yNWMyYzljOFwiLCBfX3Z1ZV9vcHRpb25zX18pXG4gIH0gZWxzZSB7XG4gICAgaG90QVBJLnJlbG9hZChcImRhdGEtdi0yNWMyYzljOFwiLCBfX3Z1ZV9vcHRpb25zX18pXG4gIH1cbn0pKCl9XG5pZiAoX192dWVfb3B0aW9uc19fLmZ1bmN0aW9uYWwpIHtjb25zb2xlLmVycm9yKFwiW3Z1ZS1sb2FkZXJdIGNoYXJ0anMtYmFyLnZ1ZTogZnVuY3Rpb25hbCBjb21wb25lbnRzIGFyZSBub3Qgc3VwcG9ydGVkIGFuZCBzaG91bGQgYmUgZGVmaW5lZCBpbiBwbGFpbiBqcyBmaWxlcyB1c2luZyByZW5kZXIgZnVuY3Rpb25zLlwiKX1cblxubW9kdWxlLmV4cG9ydHMgPSBfX3Z1ZV9leHBvcnRzX19cblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy9jb21wb25lbnRzL2NoYXJ0anMtYmFyLnZ1ZVxuLy8gbW9kdWxlIGlkID0gMVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { eval("var __vue_exports__, __vue_options__\nvar __vue_styles__ = {}\n\n/* script */\n__vue_exports__ = __webpack_require__(9)\n\n/* template */\nvar __vue_template__ = __webpack_require__(18)\n__vue_options__ = __vue_exports__ = __vue_exports__ || {}\nif (\n typeof __vue_exports__.default === \"object\" ||\n typeof __vue_exports__.default === \"function\"\n) {\nif (Object.keys(__vue_exports__).some(function (key) { return key !== \"default\" && key !== \"__esModule\" })) {console.error(\"named exports are not supported in *.vue files.\")}\n__vue_options__ = __vue_exports__ = __vue_exports__.default\n}\nif (typeof __vue_options__ === \"function\") {\n __vue_options__ = __vue_options__.options\n}\n__vue_options__.__file = \"/var/www/laravel/vue-charts-demo/resources/assets/js/vue-charts/src/components/chartjs-doughnut.vue\"\n__vue_options__.render = __vue_template__.render\n__vue_options__.staticRenderFns = __vue_template__.staticRenderFns\n\n/* hot reload */\nif (false) {(function () {\n var hotAPI = require(\"vue-hot-reload-api\")\n hotAPI.install(require(\"vue\"), false)\n if (!hotAPI.compatible) return\n module.hot.accept()\n if (!module.hot.data) {\n hotAPI.createRecord(\"data-v-59bae249\", __vue_options__)\n } else {\n hotAPI.reload(\"data-v-59bae249\", __vue_options__)\n }\n})()}\nif (__vue_options__.functional) {console.error(\"[vue-loader] chartjs-doughnut.vue: functional components are not supported and should be defined in plain js files using render functions.\")}\n\nmodule.exports = __vue_exports__\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMi5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLWRvdWdobnV0LnZ1ZT81ZjgwIl0sInNvdXJjZXNDb250ZW50IjpbInZhciBfX3Z1ZV9leHBvcnRzX18sIF9fdnVlX29wdGlvbnNfX1xudmFyIF9fdnVlX3N0eWxlc19fID0ge31cblxuLyogc2NyaXB0ICovXG5fX3Z1ZV9leHBvcnRzX18gPSByZXF1aXJlKFwiISFidWJsZS1sb2FkZXIhdnVlLWxvYWRlci9saWIvc2VsZWN0b3I/dHlwZT1zY3JpcHQmaW5kZXg9MCEuL2NoYXJ0anMtZG91Z2hudXQudnVlXCIpXG5cbi8qIHRlbXBsYXRlICovXG52YXIgX192dWVfdGVtcGxhdGVfXyA9IHJlcXVpcmUoXCIhIXZ1ZS1sb2FkZXIvbGliL3RlbXBsYXRlLWNvbXBpbGVyP2lkPWRhdGEtdi01OWJhZTI0OSF2dWUtbG9hZGVyL2xpYi9zZWxlY3Rvcj90eXBlPXRlbXBsYXRlJmluZGV4PTAhLi9jaGFydGpzLWRvdWdobnV0LnZ1ZVwiKVxuX192dWVfb3B0aW9uc19fID0gX192dWVfZXhwb3J0c19fID0gX192dWVfZXhwb3J0c19fIHx8IHt9XG5pZiAoXG4gIHR5cGVvZiBfX3Z1ZV9leHBvcnRzX18uZGVmYXVsdCA9PT0gXCJvYmplY3RcIiB8fFxuICB0eXBlb2YgX192dWVfZXhwb3J0c19fLmRlZmF1bHQgPT09IFwiZnVuY3Rpb25cIlxuKSB7XG5pZiAoT2JqZWN0LmtleXMoX192dWVfZXhwb3J0c19fKS5zb21lKGZ1bmN0aW9uIChrZXkpIHsgcmV0dXJuIGtleSAhPT0gXCJkZWZhdWx0XCIgJiYga2V5ICE9PSBcIl9fZXNNb2R1bGVcIiB9KSkge2NvbnNvbGUuZXJyb3IoXCJuYW1lZCBleHBvcnRzIGFyZSBub3Qgc3VwcG9ydGVkIGluICoudnVlIGZpbGVzLlwiKX1cbl9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX2V4cG9ydHNfXyA9IF9fdnVlX2V4cG9ydHNfXy5kZWZhdWx0XG59XG5pZiAodHlwZW9mIF9fdnVlX29wdGlvbnNfXyA9PT0gXCJmdW5jdGlvblwiKSB7XG4gIF9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX29wdGlvbnNfXy5vcHRpb25zXG59XG5fX3Z1ZV9vcHRpb25zX18uX19maWxlID0gXCIvdmFyL3d3dy9sYXJhdmVsL3Z1ZS1jaGFydHMtZGVtby9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1kb3VnaG51dC52dWVcIlxuX192dWVfb3B0aW9uc19fLnJlbmRlciA9IF9fdnVlX3RlbXBsYXRlX18ucmVuZGVyXG5fX3Z1ZV9vcHRpb25zX18uc3RhdGljUmVuZGVyRm5zID0gX192dWVfdGVtcGxhdGVfXy5zdGF0aWNSZW5kZXJGbnNcblxuLyogaG90IHJlbG9hZCAqL1xuaWYgKG1vZHVsZS5ob3QpIHsoZnVuY3Rpb24gKCkge1xuICB2YXIgaG90QVBJID0gcmVxdWlyZShcInZ1ZS1ob3QtcmVsb2FkLWFwaVwiKVxuICBob3RBUEkuaW5zdGFsbChyZXF1aXJlKFwidnVlXCIpLCBmYWxzZSlcbiAgaWYgKCFob3RBUEkuY29tcGF0aWJsZSkgcmV0dXJuXG4gIG1vZHVsZS5ob3QuYWNjZXB0KClcbiAgaWYgKCFtb2R1bGUuaG90LmRhdGEpIHtcbiAgICBob3RBUEkuY3JlYXRlUmVjb3JkKFwiZGF0YS12LTU5YmFlMjQ5XCIsIF9fdnVlX29wdGlvbnNfXylcbiAgfSBlbHNlIHtcbiAgICBob3RBUEkucmVsb2FkKFwiZGF0YS12LTU5YmFlMjQ5XCIsIF9fdnVlX29wdGlvbnNfXylcbiAgfVxufSkoKX1cbmlmIChfX3Z1ZV9vcHRpb25zX18uZnVuY3Rpb25hbCkge2NvbnNvbGUuZXJyb3IoXCJbdnVlLWxvYWRlcl0gY2hhcnRqcy1kb3VnaG51dC52dWU6IGZ1bmN0aW9uYWwgY29tcG9uZW50cyBhcmUgbm90IHN1cHBvcnRlZCBhbmQgc2hvdWxkIGJlIGRlZmluZWQgaW4gcGxhaW4ganMgZmlsZXMgdXNpbmcgcmVuZGVyIGZ1bmN0aW9ucy5cIil9XG5cbm1vZHVsZS5leHBvcnRzID0gX192dWVfZXhwb3J0c19fXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLWRvdWdobnV0LnZ1ZVxuLy8gbW9kdWxlIGlkID0gMlxuLy8gbW9kdWxlIGNodW5rcyA9IDAiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { eval("var __vue_exports__, __vue_options__\nvar __vue_styles__ = {}\n\n/* script */\n__vue_exports__ = __webpack_require__(10)\n\n/* template */\nvar __vue_template__ = __webpack_require__(21)\n__vue_options__ = __vue_exports__ = __vue_exports__ || {}\nif (\n typeof __vue_exports__.default === \"object\" ||\n typeof __vue_exports__.default === \"function\"\n) {\nif (Object.keys(__vue_exports__).some(function (key) { return key !== \"default\" && key !== \"__esModule\" })) {console.error(\"named exports are not supported in *.vue files.\")}\n__vue_options__ = __vue_exports__ = __vue_exports__.default\n}\nif (typeof __vue_options__ === \"function\") {\n __vue_options__ = __vue_options__.options\n}\n__vue_options__.__file = \"/var/www/laravel/vue-charts-demo/resources/assets/js/vue-charts/src/components/chartjs-horizontal-bar.vue\"\n__vue_options__.render = __vue_template__.render\n__vue_options__.staticRenderFns = __vue_template__.staticRenderFns\n\n/* hot reload */\nif (false) {(function () {\n var hotAPI = require(\"vue-hot-reload-api\")\n hotAPI.install(require(\"vue\"), false)\n if (!hotAPI.compatible) return\n module.hot.accept()\n if (!module.hot.data) {\n hotAPI.createRecord(\"data-v-6d89d9f1\", __vue_options__)\n } else {\n hotAPI.reload(\"data-v-6d89d9f1\", __vue_options__)\n }\n})()}\nif (__vue_options__.functional) {console.error(\"[vue-loader] chartjs-horizontal-bar.vue: functional components are not supported and should be defined in plain js files using render functions.\")}\n\nmodule.exports = __vue_exports__\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMy5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLWhvcml6b250YWwtYmFyLnZ1ZT80Y2UwIl0sInNvdXJjZXNDb250ZW50IjpbInZhciBfX3Z1ZV9leHBvcnRzX18sIF9fdnVlX29wdGlvbnNfX1xudmFyIF9fdnVlX3N0eWxlc19fID0ge31cblxuLyogc2NyaXB0ICovXG5fX3Z1ZV9leHBvcnRzX18gPSByZXF1aXJlKFwiISFidWJsZS1sb2FkZXIhdnVlLWxvYWRlci9saWIvc2VsZWN0b3I/dHlwZT1zY3JpcHQmaW5kZXg9MCEuL2NoYXJ0anMtaG9yaXpvbnRhbC1iYXIudnVlXCIpXG5cbi8qIHRlbXBsYXRlICovXG52YXIgX192dWVfdGVtcGxhdGVfXyA9IHJlcXVpcmUoXCIhIXZ1ZS1sb2FkZXIvbGliL3RlbXBsYXRlLWNvbXBpbGVyP2lkPWRhdGEtdi02ZDg5ZDlmMSF2dWUtbG9hZGVyL2xpYi9zZWxlY3Rvcj90eXBlPXRlbXBsYXRlJmluZGV4PTAhLi9jaGFydGpzLWhvcml6b250YWwtYmFyLnZ1ZVwiKVxuX192dWVfb3B0aW9uc19fID0gX192dWVfZXhwb3J0c19fID0gX192dWVfZXhwb3J0c19fIHx8IHt9XG5pZiAoXG4gIHR5cGVvZiBfX3Z1ZV9leHBvcnRzX18uZGVmYXVsdCA9PT0gXCJvYmplY3RcIiB8fFxuICB0eXBlb2YgX192dWVfZXhwb3J0c19fLmRlZmF1bHQgPT09IFwiZnVuY3Rpb25cIlxuKSB7XG5pZiAoT2JqZWN0LmtleXMoX192dWVfZXhwb3J0c19fKS5zb21lKGZ1bmN0aW9uIChrZXkpIHsgcmV0dXJuIGtleSAhPT0gXCJkZWZhdWx0XCIgJiYga2V5ICE9PSBcIl9fZXNNb2R1bGVcIiB9KSkge2NvbnNvbGUuZXJyb3IoXCJuYW1lZCBleHBvcnRzIGFyZSBub3Qgc3VwcG9ydGVkIGluICoudnVlIGZpbGVzLlwiKX1cbl9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX2V4cG9ydHNfXyA9IF9fdnVlX2V4cG9ydHNfXy5kZWZhdWx0XG59XG5pZiAodHlwZW9mIF9fdnVlX29wdGlvbnNfXyA9PT0gXCJmdW5jdGlvblwiKSB7XG4gIF9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX29wdGlvbnNfXy5vcHRpb25zXG59XG5fX3Z1ZV9vcHRpb25zX18uX19maWxlID0gXCIvdmFyL3d3dy9sYXJhdmVsL3Z1ZS1jaGFydHMtZGVtby9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1ob3Jpem9udGFsLWJhci52dWVcIlxuX192dWVfb3B0aW9uc19fLnJlbmRlciA9IF9fdnVlX3RlbXBsYXRlX18ucmVuZGVyXG5fX3Z1ZV9vcHRpb25zX18uc3RhdGljUmVuZGVyRm5zID0gX192dWVfdGVtcGxhdGVfXy5zdGF0aWNSZW5kZXJGbnNcblxuLyogaG90IHJlbG9hZCAqL1xuaWYgKG1vZHVsZS5ob3QpIHsoZnVuY3Rpb24gKCkge1xuICB2YXIgaG90QVBJID0gcmVxdWlyZShcInZ1ZS1ob3QtcmVsb2FkLWFwaVwiKVxuICBob3RBUEkuaW5zdGFsbChyZXF1aXJlKFwidnVlXCIpLCBmYWxzZSlcbiAgaWYgKCFob3RBUEkuY29tcGF0aWJsZSkgcmV0dXJuXG4gIG1vZHVsZS5ob3QuYWNjZXB0KClcbiAgaWYgKCFtb2R1bGUuaG90LmRhdGEpIHtcbiAgICBob3RBUEkuY3JlYXRlUmVjb3JkKFwiZGF0YS12LTZkODlkOWYxXCIsIF9fdnVlX29wdGlvbnNfXylcbiAgfSBlbHNlIHtcbiAgICBob3RBUEkucmVsb2FkKFwiZGF0YS12LTZkODlkOWYxXCIsIF9fdnVlX29wdGlvbnNfXylcbiAgfVxufSkoKX1cbmlmIChfX3Z1ZV9vcHRpb25zX18uZnVuY3Rpb25hbCkge2NvbnNvbGUuZXJyb3IoXCJbdnVlLWxvYWRlcl0gY2hhcnRqcy1ob3Jpem9udGFsLWJhci52dWU6IGZ1bmN0aW9uYWwgY29tcG9uZW50cyBhcmUgbm90IHN1cHBvcnRlZCBhbmQgc2hvdWxkIGJlIGRlZmluZWQgaW4gcGxhaW4ganMgZmlsZXMgdXNpbmcgcmVuZGVyIGZ1bmN0aW9ucy5cIil9XG5cbm1vZHVsZS5leHBvcnRzID0gX192dWVfZXhwb3J0c19fXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLWhvcml6b250YWwtYmFyLnZ1ZVxuLy8gbW9kdWxlIGlkID0gM1xuLy8gbW9kdWxlIGNodW5rcyA9IDAiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { eval("var __vue_exports__, __vue_options__\nvar __vue_styles__ = {}\n\n/* script */\n__vue_exports__ = __webpack_require__(11)\n\n/* template */\nvar __vue_template__ = __webpack_require__(20)\n__vue_options__ = __vue_exports__ = __vue_exports__ || {}\nif (\n typeof __vue_exports__.default === \"object\" ||\n typeof __vue_exports__.default === \"function\"\n) {\nif (Object.keys(__vue_exports__).some(function (key) { return key !== \"default\" && key !== \"__esModule\" })) {console.error(\"named exports are not supported in *.vue files.\")}\n__vue_options__ = __vue_exports__ = __vue_exports__.default\n}\nif (typeof __vue_options__ === \"function\") {\n __vue_options__ = __vue_options__.options\n}\n__vue_options__.__file = \"/var/www/laravel/vue-charts-demo/resources/assets/js/vue-charts/src/components/chartjs-line.vue\"\n__vue_options__.render = __vue_template__.render\n__vue_options__.staticRenderFns = __vue_template__.staticRenderFns\n\n/* hot reload */\nif (false) {(function () {\n var hotAPI = require(\"vue-hot-reload-api\")\n hotAPI.install(require(\"vue\"), false)\n if (!hotAPI.compatible) return\n module.hot.accept()\n if (!module.hot.data) {\n hotAPI.createRecord(\"data-v-68c558bb\", __vue_options__)\n } else {\n hotAPI.reload(\"data-v-68c558bb\", __vue_options__)\n }\n})()}\nif (__vue_options__.functional) {console.error(\"[vue-loader] chartjs-line.vue: functional components are not supported and should be defined in plain js files using render functions.\")}\n\nmodule.exports = __vue_exports__\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiNC5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLWxpbmUudnVlP2ExZmQiXSwic291cmNlc0NvbnRlbnQiOlsidmFyIF9fdnVlX2V4cG9ydHNfXywgX192dWVfb3B0aW9uc19fXG52YXIgX192dWVfc3R5bGVzX18gPSB7fVxuXG4vKiBzY3JpcHQgKi9cbl9fdnVlX2V4cG9ydHNfXyA9IHJlcXVpcmUoXCIhIWJ1YmxlLWxvYWRlciF2dWUtbG9hZGVyL2xpYi9zZWxlY3Rvcj90eXBlPXNjcmlwdCZpbmRleD0wIS4vY2hhcnRqcy1saW5lLnZ1ZVwiKVxuXG4vKiB0ZW1wbGF0ZSAqL1xudmFyIF9fdnVlX3RlbXBsYXRlX18gPSByZXF1aXJlKFwiISF2dWUtbG9hZGVyL2xpYi90ZW1wbGF0ZS1jb21waWxlcj9pZD1kYXRhLXYtNjhjNTU4YmIhdnVlLWxvYWRlci9saWIvc2VsZWN0b3I/dHlwZT10ZW1wbGF0ZSZpbmRleD0wIS4vY2hhcnRqcy1saW5lLnZ1ZVwiKVxuX192dWVfb3B0aW9uc19fID0gX192dWVfZXhwb3J0c19fID0gX192dWVfZXhwb3J0c19fIHx8IHt9XG5pZiAoXG4gIHR5cGVvZiBfX3Z1ZV9leHBvcnRzX18uZGVmYXVsdCA9PT0gXCJvYmplY3RcIiB8fFxuICB0eXBlb2YgX192dWVfZXhwb3J0c19fLmRlZmF1bHQgPT09IFwiZnVuY3Rpb25cIlxuKSB7XG5pZiAoT2JqZWN0LmtleXMoX192dWVfZXhwb3J0c19fKS5zb21lKGZ1bmN0aW9uIChrZXkpIHsgcmV0dXJuIGtleSAhPT0gXCJkZWZhdWx0XCIgJiYga2V5ICE9PSBcIl9fZXNNb2R1bGVcIiB9KSkge2NvbnNvbGUuZXJyb3IoXCJuYW1lZCBleHBvcnRzIGFyZSBub3Qgc3VwcG9ydGVkIGluICoudnVlIGZpbGVzLlwiKX1cbl9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX2V4cG9ydHNfXyA9IF9fdnVlX2V4cG9ydHNfXy5kZWZhdWx0XG59XG5pZiAodHlwZW9mIF9fdnVlX29wdGlvbnNfXyA9PT0gXCJmdW5jdGlvblwiKSB7XG4gIF9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX29wdGlvbnNfXy5vcHRpb25zXG59XG5fX3Z1ZV9vcHRpb25zX18uX19maWxlID0gXCIvdmFyL3d3dy9sYXJhdmVsL3Z1ZS1jaGFydHMtZGVtby9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1saW5lLnZ1ZVwiXG5fX3Z1ZV9vcHRpb25zX18ucmVuZGVyID0gX192dWVfdGVtcGxhdGVfXy5yZW5kZXJcbl9fdnVlX29wdGlvbnNfXy5zdGF0aWNSZW5kZXJGbnMgPSBfX3Z1ZV90ZW1wbGF0ZV9fLnN0YXRpY1JlbmRlckZuc1xuXG4vKiBob3QgcmVsb2FkICovXG5pZiAobW9kdWxlLmhvdCkgeyhmdW5jdGlvbiAoKSB7XG4gIHZhciBob3RBUEkgPSByZXF1aXJlKFwidnVlLWhvdC1yZWxvYWQtYXBpXCIpXG4gIGhvdEFQSS5pbnN0YWxsKHJlcXVpcmUoXCJ2dWVcIiksIGZhbHNlKVxuICBpZiAoIWhvdEFQSS5jb21wYXRpYmxlKSByZXR1cm5cbiAgbW9kdWxlLmhvdC5hY2NlcHQoKVxuICBpZiAoIW1vZHVsZS5ob3QuZGF0YSkge1xuICAgIGhvdEFQSS5jcmVhdGVSZWNvcmQoXCJkYXRhLXYtNjhjNTU4YmJcIiwgX192dWVfb3B0aW9uc19fKVxuICB9IGVsc2Uge1xuICAgIGhvdEFQSS5yZWxvYWQoXCJkYXRhLXYtNjhjNTU4YmJcIiwgX192dWVfb3B0aW9uc19fKVxuICB9XG59KSgpfVxuaWYgKF9fdnVlX29wdGlvbnNfXy5mdW5jdGlvbmFsKSB7Y29uc29sZS5lcnJvcihcIlt2dWUtbG9hZGVyXSBjaGFydGpzLWxpbmUudnVlOiBmdW5jdGlvbmFsIGNvbXBvbmVudHMgYXJlIG5vdCBzdXBwb3J0ZWQgYW5kIHNob3VsZCBiZSBkZWZpbmVkIGluIHBsYWluIGpzIGZpbGVzIHVzaW5nIHJlbmRlciBmdW5jdGlvbnMuXCIpfVxuXG5tb2R1bGUuZXhwb3J0cyA9IF9fdnVlX2V4cG9ydHNfX1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1saW5lLnZ1ZVxuLy8gbW9kdWxlIGlkID0gNFxuLy8gbW9kdWxlIGNodW5rcyA9IDAiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { eval("var __vue_exports__, __vue_options__\nvar __vue_styles__ = {}\n\n/* script */\n__vue_exports__ = __webpack_require__(12)\n\n/* template */\nvar __vue_template__ = __webpack_require__(16)\n__vue_options__ = __vue_exports__ = __vue_exports__ || {}\nif (\n typeof __vue_exports__.default === \"object\" ||\n typeof __vue_exports__.default === \"function\"\n) {\nif (Object.keys(__vue_exports__).some(function (key) { return key !== \"default\" && key !== \"__esModule\" })) {console.error(\"named exports are not supported in *.vue files.\")}\n__vue_options__ = __vue_exports__ = __vue_exports__.default\n}\nif (typeof __vue_options__ === \"function\") {\n __vue_options__ = __vue_options__.options\n}\n__vue_options__.__file = \"/var/www/laravel/vue-charts-demo/resources/assets/js/vue-charts/src/components/chartjs-pie.vue\"\n__vue_options__.render = __vue_template__.render\n__vue_options__.staticRenderFns = __vue_template__.staticRenderFns\n\n/* hot reload */\nif (false) {(function () {\n var hotAPI = require(\"vue-hot-reload-api\")\n hotAPI.install(require(\"vue\"), false)\n if (!hotAPI.compatible) return\n module.hot.accept()\n if (!module.hot.data) {\n hotAPI.createRecord(\"data-v-42b527d6\", __vue_options__)\n } else {\n hotAPI.reload(\"data-v-42b527d6\", __vue_options__)\n }\n})()}\nif (__vue_options__.functional) {console.error(\"[vue-loader] chartjs-pie.vue: functional components are not supported and should be defined in plain js files using render functions.\")}\n\nmodule.exports = __vue_exports__\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiNS5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLXBpZS52dWU/MTBiNSJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgX192dWVfZXhwb3J0c19fLCBfX3Z1ZV9vcHRpb25zX19cbnZhciBfX3Z1ZV9zdHlsZXNfXyA9IHt9XG5cbi8qIHNjcmlwdCAqL1xuX192dWVfZXhwb3J0c19fID0gcmVxdWlyZShcIiEhYnVibGUtbG9hZGVyIXZ1ZS1sb2FkZXIvbGliL3NlbGVjdG9yP3R5cGU9c2NyaXB0JmluZGV4PTAhLi9jaGFydGpzLXBpZS52dWVcIilcblxuLyogdGVtcGxhdGUgKi9cbnZhciBfX3Z1ZV90ZW1wbGF0ZV9fID0gcmVxdWlyZShcIiEhdnVlLWxvYWRlci9saWIvdGVtcGxhdGUtY29tcGlsZXI/aWQ9ZGF0YS12LTQyYjUyN2Q2IXZ1ZS1sb2FkZXIvbGliL3NlbGVjdG9yP3R5cGU9dGVtcGxhdGUmaW5kZXg9MCEuL2NoYXJ0anMtcGllLnZ1ZVwiKVxuX192dWVfb3B0aW9uc19fID0gX192dWVfZXhwb3J0c19fID0gX192dWVfZXhwb3J0c19fIHx8IHt9XG5pZiAoXG4gIHR5cGVvZiBfX3Z1ZV9leHBvcnRzX18uZGVmYXVsdCA9PT0gXCJvYmplY3RcIiB8fFxuICB0eXBlb2YgX192dWVfZXhwb3J0c19fLmRlZmF1bHQgPT09IFwiZnVuY3Rpb25cIlxuKSB7XG5pZiAoT2JqZWN0LmtleXMoX192dWVfZXhwb3J0c19fKS5zb21lKGZ1bmN0aW9uIChrZXkpIHsgcmV0dXJuIGtleSAhPT0gXCJkZWZhdWx0XCIgJiYga2V5ICE9PSBcIl9fZXNNb2R1bGVcIiB9KSkge2NvbnNvbGUuZXJyb3IoXCJuYW1lZCBleHBvcnRzIGFyZSBub3Qgc3VwcG9ydGVkIGluICoudnVlIGZpbGVzLlwiKX1cbl9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX2V4cG9ydHNfXyA9IF9fdnVlX2V4cG9ydHNfXy5kZWZhdWx0XG59XG5pZiAodHlwZW9mIF9fdnVlX29wdGlvbnNfXyA9PT0gXCJmdW5jdGlvblwiKSB7XG4gIF9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX29wdGlvbnNfXy5vcHRpb25zXG59XG5fX3Z1ZV9vcHRpb25zX18uX19maWxlID0gXCIvdmFyL3d3dy9sYXJhdmVsL3Z1ZS1jaGFydHMtZGVtby9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1waWUudnVlXCJcbl9fdnVlX29wdGlvbnNfXy5yZW5kZXIgPSBfX3Z1ZV90ZW1wbGF0ZV9fLnJlbmRlclxuX192dWVfb3B0aW9uc19fLnN0YXRpY1JlbmRlckZucyA9IF9fdnVlX3RlbXBsYXRlX18uc3RhdGljUmVuZGVyRm5zXG5cbi8qIGhvdCByZWxvYWQgKi9cbmlmIChtb2R1bGUuaG90KSB7KGZ1bmN0aW9uICgpIHtcbiAgdmFyIGhvdEFQSSA9IHJlcXVpcmUoXCJ2dWUtaG90LXJlbG9hZC1hcGlcIilcbiAgaG90QVBJLmluc3RhbGwocmVxdWlyZShcInZ1ZVwiKSwgZmFsc2UpXG4gIGlmICghaG90QVBJLmNvbXBhdGlibGUpIHJldHVyblxuICBtb2R1bGUuaG90LmFjY2VwdCgpXG4gIGlmICghbW9kdWxlLmhvdC5kYXRhKSB7XG4gICAgaG90QVBJLmNyZWF0ZVJlY29yZChcImRhdGEtdi00MmI1MjdkNlwiLCBfX3Z1ZV9vcHRpb25zX18pXG4gIH0gZWxzZSB7XG4gICAgaG90QVBJLnJlbG9hZChcImRhdGEtdi00MmI1MjdkNlwiLCBfX3Z1ZV9vcHRpb25zX18pXG4gIH1cbn0pKCl9XG5pZiAoX192dWVfb3B0aW9uc19fLmZ1bmN0aW9uYWwpIHtjb25zb2xlLmVycm9yKFwiW3Z1ZS1sb2FkZXJdIGNoYXJ0anMtcGllLnZ1ZTogZnVuY3Rpb25hbCBjb21wb25lbnRzIGFyZSBub3Qgc3VwcG9ydGVkIGFuZCBzaG91bGQgYmUgZGVmaW5lZCBpbiBwbGFpbiBqcyBmaWxlcyB1c2luZyByZW5kZXIgZnVuY3Rpb25zLlwiKX1cblxubW9kdWxlLmV4cG9ydHMgPSBfX3Z1ZV9leHBvcnRzX19cblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy9jb21wb25lbnRzL2NoYXJ0anMtcGllLnZ1ZVxuLy8gbW9kdWxlIGlkID0gNVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { eval("var __vue_exports__, __vue_options__\nvar __vue_styles__ = {}\n\n/* script */\n__vue_exports__ = __webpack_require__(13)\n\n/* template */\nvar __vue_template__ = __webpack_require__(19)\n__vue_options__ = __vue_exports__ = __vue_exports__ || {}\nif (\n typeof __vue_exports__.default === \"object\" ||\n typeof __vue_exports__.default === \"function\"\n) {\nif (Object.keys(__vue_exports__).some(function (key) { return key !== \"default\" && key !== \"__esModule\" })) {console.error(\"named exports are not supported in *.vue files.\")}\n__vue_options__ = __vue_exports__ = __vue_exports__.default\n}\nif (typeof __vue_options__ === \"function\") {\n __vue_options__ = __vue_options__.options\n}\n__vue_options__.__file = \"/var/www/laravel/vue-charts-demo/resources/assets/js/vue-charts/src/components/chartjs-polar-area.vue\"\n__vue_options__.render = __vue_template__.render\n__vue_options__.staticRenderFns = __vue_template__.staticRenderFns\n\n/* hot reload */\nif (false) {(function () {\n var hotAPI = require(\"vue-hot-reload-api\")\n hotAPI.install(require(\"vue\"), false)\n if (!hotAPI.compatible) return\n module.hot.accept()\n if (!module.hot.data) {\n hotAPI.createRecord(\"data-v-6502cf43\", __vue_options__)\n } else {\n hotAPI.reload(\"data-v-6502cf43\", __vue_options__)\n }\n})()}\nif (__vue_options__.functional) {console.error(\"[vue-loader] chartjs-polar-area.vue: functional components are not supported and should be defined in plain js files using render functions.\")}\n\nmodule.exports = __vue_exports__\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiNi5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLXBvbGFyLWFyZWEudnVlPzI3ZTYiXSwic291cmNlc0NvbnRlbnQiOlsidmFyIF9fdnVlX2V4cG9ydHNfXywgX192dWVfb3B0aW9uc19fXG52YXIgX192dWVfc3R5bGVzX18gPSB7fVxuXG4vKiBzY3JpcHQgKi9cbl9fdnVlX2V4cG9ydHNfXyA9IHJlcXVpcmUoXCIhIWJ1YmxlLWxvYWRlciF2dWUtbG9hZGVyL2xpYi9zZWxlY3Rvcj90eXBlPXNjcmlwdCZpbmRleD0wIS4vY2hhcnRqcy1wb2xhci1hcmVhLnZ1ZVwiKVxuXG4vKiB0ZW1wbGF0ZSAqL1xudmFyIF9fdnVlX3RlbXBsYXRlX18gPSByZXF1aXJlKFwiISF2dWUtbG9hZGVyL2xpYi90ZW1wbGF0ZS1jb21waWxlcj9pZD1kYXRhLXYtNjUwMmNmNDMhdnVlLWxvYWRlci9saWIvc2VsZWN0b3I/dHlwZT10ZW1wbGF0ZSZpbmRleD0wIS4vY2hhcnRqcy1wb2xhci1hcmVhLnZ1ZVwiKVxuX192dWVfb3B0aW9uc19fID0gX192dWVfZXhwb3J0c19fID0gX192dWVfZXhwb3J0c19fIHx8IHt9XG5pZiAoXG4gIHR5cGVvZiBfX3Z1ZV9leHBvcnRzX18uZGVmYXVsdCA9PT0gXCJvYmplY3RcIiB8fFxuICB0eXBlb2YgX192dWVfZXhwb3J0c19fLmRlZmF1bHQgPT09IFwiZnVuY3Rpb25cIlxuKSB7XG5pZiAoT2JqZWN0LmtleXMoX192dWVfZXhwb3J0c19fKS5zb21lKGZ1bmN0aW9uIChrZXkpIHsgcmV0dXJuIGtleSAhPT0gXCJkZWZhdWx0XCIgJiYga2V5ICE9PSBcIl9fZXNNb2R1bGVcIiB9KSkge2NvbnNvbGUuZXJyb3IoXCJuYW1lZCBleHBvcnRzIGFyZSBub3Qgc3VwcG9ydGVkIGluICoudnVlIGZpbGVzLlwiKX1cbl9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX2V4cG9ydHNfXyA9IF9fdnVlX2V4cG9ydHNfXy5kZWZhdWx0XG59XG5pZiAodHlwZW9mIF9fdnVlX29wdGlvbnNfXyA9PT0gXCJmdW5jdGlvblwiKSB7XG4gIF9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX29wdGlvbnNfXy5vcHRpb25zXG59XG5fX3Z1ZV9vcHRpb25zX18uX19maWxlID0gXCIvdmFyL3d3dy9sYXJhdmVsL3Z1ZS1jaGFydHMtZGVtby9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1wb2xhci1hcmVhLnZ1ZVwiXG5fX3Z1ZV9vcHRpb25zX18ucmVuZGVyID0gX192dWVfdGVtcGxhdGVfXy5yZW5kZXJcbl9fdnVlX29wdGlvbnNfXy5zdGF0aWNSZW5kZXJGbnMgPSBfX3Z1ZV90ZW1wbGF0ZV9fLnN0YXRpY1JlbmRlckZuc1xuXG4vKiBob3QgcmVsb2FkICovXG5pZiAobW9kdWxlLmhvdCkgeyhmdW5jdGlvbiAoKSB7XG4gIHZhciBob3RBUEkgPSByZXF1aXJlKFwidnVlLWhvdC1yZWxvYWQtYXBpXCIpXG4gIGhvdEFQSS5pbnN0YWxsKHJlcXVpcmUoXCJ2dWVcIiksIGZhbHNlKVxuICBpZiAoIWhvdEFQSS5jb21wYXRpYmxlKSByZXR1cm5cbiAgbW9kdWxlLmhvdC5hY2NlcHQoKVxuICBpZiAoIW1vZHVsZS5ob3QuZGF0YSkge1xuICAgIGhvdEFQSS5jcmVhdGVSZWNvcmQoXCJkYXRhLXYtNjUwMmNmNDNcIiwgX192dWVfb3B0aW9uc19fKVxuICB9IGVsc2Uge1xuICAgIGhvdEFQSS5yZWxvYWQoXCJkYXRhLXYtNjUwMmNmNDNcIiwgX192dWVfb3B0aW9uc19fKVxuICB9XG59KSgpfVxuaWYgKF9fdnVlX29wdGlvbnNfXy5mdW5jdGlvbmFsKSB7Y29uc29sZS5lcnJvcihcIlt2dWUtbG9hZGVyXSBjaGFydGpzLXBvbGFyLWFyZWEudnVlOiBmdW5jdGlvbmFsIGNvbXBvbmVudHMgYXJlIG5vdCBzdXBwb3J0ZWQgYW5kIHNob3VsZCBiZSBkZWZpbmVkIGluIHBsYWluIGpzIGZpbGVzIHVzaW5nIHJlbmRlciBmdW5jdGlvbnMuXCIpfVxuXG5tb2R1bGUuZXhwb3J0cyA9IF9fdnVlX2V4cG9ydHNfX1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1wb2xhci1hcmVhLnZ1ZVxuLy8gbW9kdWxlIGlkID0gNlxuLy8gbW9kdWxlIGNodW5rcyA9IDAiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { eval("var __vue_exports__, __vue_options__\nvar __vue_styles__ = {}\n\n/* script */\n__vue_exports__ = __webpack_require__(14)\n\n/* template */\nvar __vue_template__ = __webpack_require__(17)\n__vue_options__ = __vue_exports__ = __vue_exports__ || {}\nif (\n typeof __vue_exports__.default === \"object\" ||\n typeof __vue_exports__.default === \"function\"\n) {\nif (Object.keys(__vue_exports__).some(function (key) { return key !== \"default\" && key !== \"__esModule\" })) {console.error(\"named exports are not supported in *.vue files.\")}\n__vue_options__ = __vue_exports__ = __vue_exports__.default\n}\nif (typeof __vue_options__ === \"function\") {\n __vue_options__ = __vue_options__.options\n}\n__vue_options__.__file = \"/var/www/laravel/vue-charts-demo/resources/assets/js/vue-charts/src/components/chartjs-radar.vue\"\n__vue_options__.render = __vue_template__.render\n__vue_options__.staticRenderFns = __vue_template__.staticRenderFns\n\n/* hot reload */\nif (false) {(function () {\n var hotAPI = require(\"vue-hot-reload-api\")\n hotAPI.install(require(\"vue\"), false)\n if (!hotAPI.compatible) return\n module.hot.accept()\n if (!module.hot.data) {\n hotAPI.createRecord(\"data-v-537a6f62\", __vue_options__)\n } else {\n hotAPI.reload(\"data-v-537a6f62\", __vue_options__)\n }\n})()}\nif (__vue_options__.functional) {console.error(\"[vue-loader] chartjs-radar.vue: functional components are not supported and should be defined in plain js files using render functions.\")}\n\nmodule.exports = __vue_exports__\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiNy5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLXJhZGFyLnZ1ZT9jZGEwIl0sInNvdXJjZXNDb250ZW50IjpbInZhciBfX3Z1ZV9leHBvcnRzX18sIF9fdnVlX29wdGlvbnNfX1xudmFyIF9fdnVlX3N0eWxlc19fID0ge31cblxuLyogc2NyaXB0ICovXG5fX3Z1ZV9leHBvcnRzX18gPSByZXF1aXJlKFwiISFidWJsZS1sb2FkZXIhdnVlLWxvYWRlci9saWIvc2VsZWN0b3I/dHlwZT1zY3JpcHQmaW5kZXg9MCEuL2NoYXJ0anMtcmFkYXIudnVlXCIpXG5cbi8qIHRlbXBsYXRlICovXG52YXIgX192dWVfdGVtcGxhdGVfXyA9IHJlcXVpcmUoXCIhIXZ1ZS1sb2FkZXIvbGliL3RlbXBsYXRlLWNvbXBpbGVyP2lkPWRhdGEtdi01MzdhNmY2MiF2dWUtbG9hZGVyL2xpYi9zZWxlY3Rvcj90eXBlPXRlbXBsYXRlJmluZGV4PTAhLi9jaGFydGpzLXJhZGFyLnZ1ZVwiKVxuX192dWVfb3B0aW9uc19fID0gX192dWVfZXhwb3J0c19fID0gX192dWVfZXhwb3J0c19fIHx8IHt9XG5pZiAoXG4gIHR5cGVvZiBfX3Z1ZV9leHBvcnRzX18uZGVmYXVsdCA9PT0gXCJvYmplY3RcIiB8fFxuICB0eXBlb2YgX192dWVfZXhwb3J0c19fLmRlZmF1bHQgPT09IFwiZnVuY3Rpb25cIlxuKSB7XG5pZiAoT2JqZWN0LmtleXMoX192dWVfZXhwb3J0c19fKS5zb21lKGZ1bmN0aW9uIChrZXkpIHsgcmV0dXJuIGtleSAhPT0gXCJkZWZhdWx0XCIgJiYga2V5ICE9PSBcIl9fZXNNb2R1bGVcIiB9KSkge2NvbnNvbGUuZXJyb3IoXCJuYW1lZCBleHBvcnRzIGFyZSBub3Qgc3VwcG9ydGVkIGluICoudnVlIGZpbGVzLlwiKX1cbl9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX2V4cG9ydHNfXyA9IF9fdnVlX2V4cG9ydHNfXy5kZWZhdWx0XG59XG5pZiAodHlwZW9mIF9fdnVlX29wdGlvbnNfXyA9PT0gXCJmdW5jdGlvblwiKSB7XG4gIF9fdnVlX29wdGlvbnNfXyA9IF9fdnVlX29wdGlvbnNfXy5vcHRpb25zXG59XG5fX3Z1ZV9vcHRpb25zX18uX19maWxlID0gXCIvdmFyL3d3dy9sYXJhdmVsL3Z1ZS1jaGFydHMtZGVtby9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1yYWRhci52dWVcIlxuX192dWVfb3B0aW9uc19fLnJlbmRlciA9IF9fdnVlX3RlbXBsYXRlX18ucmVuZGVyXG5fX3Z1ZV9vcHRpb25zX18uc3RhdGljUmVuZGVyRm5zID0gX192dWVfdGVtcGxhdGVfXy5zdGF0aWNSZW5kZXJGbnNcblxuLyogaG90IHJlbG9hZCAqL1xuaWYgKG1vZHVsZS5ob3QpIHsoZnVuY3Rpb24gKCkge1xuICB2YXIgaG90QVBJID0gcmVxdWlyZShcInZ1ZS1ob3QtcmVsb2FkLWFwaVwiKVxuICBob3RBUEkuaW5zdGFsbChyZXF1aXJlKFwidnVlXCIpLCBmYWxzZSlcbiAgaWYgKCFob3RBUEkuY29tcGF0aWJsZSkgcmV0dXJuXG4gIG1vZHVsZS5ob3QuYWNjZXB0KClcbiAgaWYgKCFtb2R1bGUuaG90LmRhdGEpIHtcbiAgICBob3RBUEkuY3JlYXRlUmVjb3JkKFwiZGF0YS12LTUzN2E2ZjYyXCIsIF9fdnVlX29wdGlvbnNfXylcbiAgfSBlbHNlIHtcbiAgICBob3RBUEkucmVsb2FkKFwiZGF0YS12LTUzN2E2ZjYyXCIsIF9fdnVlX29wdGlvbnNfXylcbiAgfVxufSkoKX1cbmlmIChfX3Z1ZV9vcHRpb25zX18uZnVuY3Rpb25hbCkge2NvbnNvbGUuZXJyb3IoXCJbdnVlLWxvYWRlcl0gY2hhcnRqcy1yYWRhci52dWU6IGZ1bmN0aW9uYWwgY29tcG9uZW50cyBhcmUgbm90IHN1cHBvcnRlZCBhbmQgc2hvdWxkIGJlIGRlZmluZWQgaW4gcGxhaW4ganMgZmlsZXMgdXNpbmcgcmVuZGVyIGZ1bmN0aW9ucy5cIil9XG5cbm1vZHVsZS5leHBvcnRzID0gX192dWVfZXhwb3J0c19fXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLXJhZGFyLnZ1ZVxuLy8gbW9kdWxlIGlkID0gN1xuLy8gbW9kdWxlIGNodW5rcyA9IDAiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { "use strict"; eval("//\n//\n//\n//\n//\n\n/* harmony default export */ exports[\"default\"] = {\n mixins: [\n VueCharts.core.default,\n ],\n data: function data() {\n return {\n type: 'bar',\n chart_data: {\n labels: this.labels,\n datasets: [{\n type: 'bar',\n label: this.datalabel,\n backgroundColor: this.backgroundcolor,\n borderColor: this.bordercolor,\n borderWidth: 1,\n data: this.data,\n }, ],\n },\n };\n },\n};\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiOC5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1iYXIudnVlPzJkM2UiXSwic291cmNlc0NvbnRlbnQiOlsiLy9cbi8vXG4vL1xuLy9cbi8vXG5cbmV4cG9ydCBkZWZhdWx0IHtcbiAgICBtaXhpbnM6IFtcbiAgICAgICAgVnVlQ2hhcnRzLmNvcmUuZGVmYXVsdCxcbiAgICBdLFxuICAgIGRhdGEoKSB7XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICB0eXBlOiAnYmFyJyxcbiAgICAgICAgICAgIGNoYXJ0X2RhdGE6IHtcbiAgICAgICAgICAgICAgICBsYWJlbHM6IHRoaXMubGFiZWxzLFxuICAgICAgICAgICAgICAgIGRhdGFzZXRzOiBbe1xuICAgICAgICAgICAgICAgICAgICB0eXBlOiAnYmFyJyxcbiAgICAgICAgICAgICAgICAgICAgbGFiZWw6IHRoaXMuZGF0YWxhYmVsLFxuICAgICAgICAgICAgICAgICAgICBiYWNrZ3JvdW5kQ29sb3I6IHRoaXMuYmFja2dyb3VuZGNvbG9yLFxuICAgICAgICAgICAgICAgICAgICBib3JkZXJDb2xvcjogdGhpcy5ib3JkZXJjb2xvcixcbiAgICAgICAgICAgICAgICAgICAgYm9yZGVyV2lkdGg6IDEsXG4gICAgICAgICAgICAgICAgICAgIGRhdGE6IHRoaXMuZGF0YSxcbiAgICAgICAgICAgICAgICB9LCBdLFxuICAgICAgICAgICAgfSxcbiAgICAgICAgfTtcbiAgICB9LFxufVxuXG5cblxuLy8gV0VCUEFDSyBGT09URVIgLy9cbi8vIHJlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLWJhci52dWUiXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7QUFNQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { "use strict"; eval("//\n//\n//\n//\n//\n\n/* harmony default export */ exports[\"default\"] = {\n mixins: [\n VueCharts.core.default,\n ],\n props: {\n backgroundcolor:{\n default: function () { return [\n \"#FF6384\",\n \"#36A2EB\",\n \"#FFCE56\",\n \"#00A600\"\n ]; },\n },\n hoverbackgroundcolor: {\n default: function () { return [\n \"#FF6384\",\n \"#36A2EB\",\n \"#FFCE56\",\n \"#00A600\"\n ]; },\n },\n bordercolor:{\n default: function () { return \"#fff\"; },\n },\n hoverbordercolor: {\n default: function () { return \"\"; },\n }\n },\n data: function data() {\n return {\n type: 'doughnut',\n chart_data: {\n labels: this.labels,\n datasets: [{\n label: this.datalabel,\n backgroundColor: this.backgroundcolor,\n borderColor: this.bordercolor,\n hoverBackgroundColor: this.hoverbackgroundcolor,\n hoverBorderColor: this.hoverbackgroundcolor,\n data: this.data\n }],\n },\n };\n },\n};\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiOS5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1kb3VnaG51dC52dWU/MTMzYiJdLCJzb3VyY2VzQ29udGVudCI6WyIvL1xuLy9cbi8vXG4vL1xuLy9cblxuZXhwb3J0IGRlZmF1bHQge1xuICAgIG1peGluczogW1xuICAgICAgICBWdWVDaGFydHMuY29yZS5kZWZhdWx0LFxuICAgIF0sXG4gICAgcHJvcHM6IHtcbiAgICAgICAgYmFja2dyb3VuZGNvbG9yOntcbiAgICAgICAgICAgIGRlZmF1bHQ6ICgpID0+IFtcbiAgICAgICAgICAgICAgICBcIiNGRjYzODRcIixcbiAgICAgICAgICAgICAgICBcIiMzNkEyRUJcIixcbiAgICAgICAgICAgICAgICBcIiNGRkNFNTZcIixcbiAgICAgICAgICAgICAgICBcIiMwMEE2MDBcIlxuICAgICAgICAgICAgXSxcbiAgICAgICAgfSxcbiAgICAgICAgaG92ZXJiYWNrZ3JvdW5kY29sb3I6IHtcbiAgICAgICAgICAgIGRlZmF1bHQ6ICgpID0+IFtcbiAgICAgICAgICAgICAgICBcIiNGRjYzODRcIixcbiAgICAgICAgICAgICAgICBcIiMzNkEyRUJcIixcbiAgICAgICAgICAgICAgICBcIiNGRkNFNTZcIixcbiAgICAgICAgICAgICAgICBcIiMwMEE2MDBcIlxuICAgICAgICAgICAgXSxcbiAgICAgICAgfSxcbiAgICAgICAgYm9yZGVyY29sb3I6e1xuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gXCIjZmZmXCIsXG4gICAgICAgIH0sXG4gICAgICAgIGhvdmVyYm9yZGVyY29sb3I6IHtcbiAgICAgICAgICAgIGRlZmF1bHQ6ICgpID0+IFwiXCIsXG4gICAgICAgIH1cbiAgICB9LFxuICAgIGRhdGEoKSB7XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICB0eXBlOiAnZG91Z2hudXQnLFxuICAgICAgICAgICAgY2hhcnRfZGF0YToge1xuICAgICAgICAgICAgICAgIGxhYmVsczogdGhpcy5sYWJlbHMsXG4gICAgICAgICAgICAgICAgZGF0YXNldHM6IFt7XG4gICAgICAgICAgICAgICAgICAgIGxhYmVsOiB0aGlzLmRhdGFsYWJlbCxcbiAgICAgICAgICAgICAgICAgICAgYmFja2dyb3VuZENvbG9yOiB0aGlzLmJhY2tncm91bmRjb2xvcixcbiAgICAgICAgICAgICAgICAgICAgYm9yZGVyQ29sb3I6IHRoaXMuYm9yZGVyY29sb3IsXG4gICAgICAgICAgICAgICAgICAgIGhvdmVyQmFja2dyb3VuZENvbG9yOiB0aGlzLmhvdmVyYmFja2dyb3VuZGNvbG9yLFxuICAgICAgICAgICAgICAgICAgICBob3ZlckJvcmRlckNvbG9yOiB0aGlzLmhvdmVyYmFja2dyb3VuZGNvbG9yLFxuICAgICAgICAgICAgICAgICAgICBkYXRhOiB0aGlzLmRhdGFcbiAgICAgICAgICAgICAgICB9XSxcbiAgICAgICAgICAgIH0sXG4gICAgICAgIH07XG4gICAgfSxcbn1cblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyByZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1kb3VnaG51dC52dWUiXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7QUFNQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { "use strict"; eval("//\n//\n//\n//\n//\n\n/* harmony default export */ exports[\"default\"] = {\n mixins: [\n VueCharts.core.default,\n ],\n data: function data() {\n return {\n type: 'horizontalBar',\n chart_data: {\n labels: this.labels,\n datasets: [{\n type: 'horizontalBar',\n label: this.datalabel,\n backgroundColor: this.backgroundcolor,\n borderColor: this.bordercolor,\n borderWidth: 1,\n data: this.data,\n }, ],\n },\n options: {\n scales: {\n yAxes: [{\n stacked: false\n }],\n xAxes: [{\n stacked: true\n }]\n }\n }\n };\n },\n};\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMTAuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy9jb21wb25lbnRzL2NoYXJ0anMtaG9yaXpvbnRhbC1iYXIudnVlPzc3NzMiXSwic291cmNlc0NvbnRlbnQiOlsiLy9cbi8vXG4vL1xuLy9cbi8vXG5cbmV4cG9ydCBkZWZhdWx0IHtcbiAgICBtaXhpbnM6IFtcbiAgICAgICAgVnVlQ2hhcnRzLmNvcmUuZGVmYXVsdCxcbiAgICBdLFxuICAgIGRhdGEoKSB7XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICB0eXBlOiAnaG9yaXpvbnRhbEJhcicsXG4gICAgICAgICAgICBjaGFydF9kYXRhOiB7XG4gICAgICAgICAgICAgICAgbGFiZWxzOiB0aGlzLmxhYmVscyxcbiAgICAgICAgICAgICAgICBkYXRhc2V0czogW3tcbiAgICAgICAgICAgICAgICAgICAgdHlwZTogJ2hvcml6b250YWxCYXInLFxuICAgICAgICAgICAgICAgICAgICBsYWJlbDogdGhpcy5kYXRhbGFiZWwsXG4gICAgICAgICAgICAgICAgICAgIGJhY2tncm91bmRDb2xvcjogdGhpcy5iYWNrZ3JvdW5kY29sb3IsXG4gICAgICAgICAgICAgICAgICAgIGJvcmRlckNvbG9yOiB0aGlzLmJvcmRlcmNvbG9yLFxuICAgICAgICAgICAgICAgICAgICBib3JkZXJXaWR0aDogMSxcbiAgICAgICAgICAgICAgICAgICAgZGF0YTogdGhpcy5kYXRhLFxuICAgICAgICAgICAgICAgIH0sIF0sXG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgb3B0aW9uczoge1xuICAgICAgICAgICAgICAgIHNjYWxlczoge1xuICAgICAgICAgICAgICAgICAgICB5QXhlczogW3tcbiAgICAgICAgICAgICAgICAgICAgICAgIHN0YWNrZWQ6IGZhbHNlXG4gICAgICAgICAgICAgICAgICAgIH1dLFxuICAgICAgICAgICAgICAgICAgICB4QXhlczogW3tcbiAgICAgICAgICAgICAgICAgICAgICAgIHN0YWNrZWQ6IHRydWVcbiAgICAgICAgICAgICAgICAgICAgfV1cbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9XG4gICAgICAgIH07XG4gICAgfSxcbn1cblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyByZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1ob3Jpem9udGFsLWJhci52dWUiXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7QUFNQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0="); /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { "use strict"; eval("//\n//\n//\n//\n//\n\n/* harmony default export */ exports[\"default\"] = {\n mixins: [\n VueCharts.core.default,\n ],\n props: {\n beginzero:{\n type: Boolean,\n default: false,\n },\n fill:{\n type: Boolean,\n default: false,\n },\n linetension: {\n type: Number,\n default: function () { return 0.2; },\n },\n pointbordercolor: {\n type: String,\n default: function () { return \"rgba(75,192,192,1)\"; },\n },\n pointbackgroundcolor: {\n type: String,\n default: function () { return \"#fff\"; },\n },\n pointhoverbackgroundcolor: {\n type: String,\n default: function () { return \"rgba(75,192,192,1)\"; },\n },\n pointhoverbordercolor: {\n type: String,\n default: function () { return \"rgba(220,220,220,1)\"; },\n },\n pointborderwidth: {\n type: Number,\n default: function () { return 1; },\n },\n pointhoverborderwidth:{\n type: Number,\n default: function () { return 2; },\n }\n },\n data: function data() {\n return {\n type: 'line',\n chart_data: {\n labels: this.labels,\n datasets: [{\n type: 'line',\n label: this.datalabel,\n fill: this.fill,\n lineTension: this.linetension,\n backgroundColor: this.backgroundcolor,\n borderColor: this.bordercolor,\n borderCapStyle: 'butt',\n borderDash: [],\n borderDashOffset: 0.0,\n borderJoinStyle: 'miter',\n pointBorderColor: this.pointbordercolor,\n pointBackgroundColor: this.pointbackgroundcolor,\n pointBorderWidth: this.pointborderwidth,\n pointHoverRadius: 5,\n pointHoverBackgroundColor: this.pointhoverbackgroundcolor,\n pointHoverBorderColor: this.pointhoverbordercolor,\n pointHoverBorderWidth: this.pointhoverborderwidth,\n pointRadius: 1,\n pointHitRadius: 10,\n data: this.data,\n spanGaps: false,\n }, ],\n },\n };\n },\n};\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMTEuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy9jb21wb25lbnRzL2NoYXJ0anMtbGluZS52dWU/Zjg4MyJdLCJzb3VyY2VzQ29udGVudCI6WyIvL1xuLy9cbi8vXG4vL1xuLy9cblxuZXhwb3J0IGRlZmF1bHQge1xuICAgIG1peGluczogW1xuICAgICAgICBWdWVDaGFydHMuY29yZS5kZWZhdWx0LFxuICAgIF0sXG4gICAgcHJvcHM6IHtcbiAgICAgICAgYmVnaW56ZXJvOntcbiAgICAgICAgICAgIHR5cGU6IEJvb2xlYW4sXG4gICAgICAgICAgICBkZWZhdWx0OiBmYWxzZSxcbiAgICAgICAgfSxcbiAgICAgICAgZmlsbDp7XG4gICAgICAgICAgICB0eXBlOiBCb29sZWFuLFxuICAgICAgICAgICAgZGVmYXVsdDogZmFsc2UsXG4gICAgICAgIH0sXG4gICAgICAgIGxpbmV0ZW5zaW9uOiB7XG4gICAgICAgICAgICB0eXBlOiBOdW1iZXIsXG4gICAgICAgICAgICBkZWZhdWx0OiAoKSA9PiAwLjIsXG4gICAgICAgIH0sXG4gICAgICAgIHBvaW50Ym9yZGVyY29sb3I6IHtcbiAgICAgICAgICAgIHR5cGU6IFN0cmluZyxcbiAgICAgICAgICAgIGRlZmF1bHQ6ICgpID0+IFwicmdiYSg3NSwxOTIsMTkyLDEpXCIsXG4gICAgICAgIH0sXG4gICAgICAgIHBvaW50YmFja2dyb3VuZGNvbG9yOiB7XG4gICAgICAgICAgICB0eXBlOiBTdHJpbmcsXG4gICAgICAgICAgICBkZWZhdWx0OiAoKSA9PiBcIiNmZmZcIixcbiAgICAgICAgfSxcbiAgICAgICAgcG9pbnRob3ZlcmJhY2tncm91bmRjb2xvcjoge1xuICAgICAgICAgICAgdHlwZTogU3RyaW5nLFxuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gXCJyZ2JhKDc1LDE5MiwxOTIsMSlcIixcbiAgICAgICAgfSxcbiAgICAgICAgcG9pbnRob3ZlcmJvcmRlcmNvbG9yOiB7XG4gICAgICAgICAgICB0eXBlOiBTdHJpbmcsXG4gICAgICAgICAgICBkZWZhdWx0OiAoKSA9PiBcInJnYmEoMjIwLDIyMCwyMjAsMSlcIixcbiAgICAgICAgfSxcbiAgICAgICAgcG9pbnRib3JkZXJ3aWR0aDoge1xuICAgICAgICAgICAgdHlwZTogTnVtYmVyLFxuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gMSxcbiAgICAgICAgfSxcbiAgICAgICAgcG9pbnRob3ZlcmJvcmRlcndpZHRoOntcbiAgICAgICAgICAgIHR5cGU6IE51bWJlcixcbiAgICAgICAgICAgIGRlZmF1bHQ6ICgpID0+IDIsXG4gICAgICAgIH1cbiAgICB9LFxuICAgIGRhdGEoKSB7XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICB0eXBlOiAnbGluZScsXG4gICAgICAgICAgICBjaGFydF9kYXRhOiB7XG4gICAgICAgICAgICAgICAgbGFiZWxzOiB0aGlzLmxhYmVscyxcbiAgICAgICAgICAgICAgICBkYXRhc2V0czogW3tcbiAgICAgICAgICAgICAgICAgICAgdHlwZTogJ2xpbmUnLFxuICAgICAgICAgICAgICAgICAgICBsYWJlbDogdGhpcy5kYXRhbGFiZWwsXG4gICAgICAgICAgICAgICAgICAgIGZpbGw6IHRoaXMuZmlsbCxcbiAgICAgICAgICAgICAgICAgICAgbGluZVRlbnNpb246ICB0aGlzLmxpbmV0ZW5zaW9uLFxuICAgICAgICAgICAgICAgICAgICBiYWNrZ3JvdW5kQ29sb3I6IHRoaXMuYmFja2dyb3VuZGNvbG9yLFxuICAgICAgICAgICAgICAgICAgICBib3JkZXJDb2xvcjogdGhpcy5ib3JkZXJjb2xvcixcbiAgICAgICAgICAgICAgICAgICAgYm9yZGVyQ2FwU3R5bGU6ICdidXR0JyxcbiAgICAgICAgICAgICAgICAgICAgYm9yZGVyRGFzaDogW10sXG4gICAgICAgICAgICAgICAgICAgIGJvcmRlckRhc2hPZmZzZXQ6IDAuMCxcbiAgICAgICAgICAgICAgICAgICAgYm9yZGVySm9pblN0eWxlOiAnbWl0ZXInLFxuICAgICAgICAgICAgICAgICAgICBwb2ludEJvcmRlckNvbG9yOiB0aGlzLnBvaW50Ym9yZGVyY29sb3IsXG4gICAgICAgICAgICAgICAgICAgIHBvaW50QmFja2dyb3VuZENvbG9yOiB0aGlzLnBvaW50YmFja2dyb3VuZGNvbG9yLFxuICAgICAgICAgICAgICAgICAgICBwb2ludEJvcmRlcldpZHRoOiB0aGlzLnBvaW50Ym9yZGVyd2lkdGgsXG4gICAgICAgICAgICAgICAgICAgIHBvaW50SG92ZXJSYWRpdXM6IDUsXG4gICAgICAgICAgICAgICAgICAgIHBvaW50SG92ZXJCYWNrZ3JvdW5kQ29sb3I6IHRoaXMucG9pbnRob3ZlcmJhY2tncm91bmRjb2xvcixcbiAgICAgICAgICAgICAgICAgICAgcG9pbnRIb3ZlckJvcmRlckNvbG9yOiB0aGlzLnBvaW50aG92ZXJib3JkZXJjb2xvcixcbiAgICAgICAgICAgICAgICAgICAgcG9pbnRIb3ZlckJvcmRlcldpZHRoOiB0aGlzLnBvaW50aG92ZXJib3JkZXJ3aWR0aCxcbiAgICAgICAgICAgICAgICAgICAgcG9pbnRSYWRpdXM6IDEsXG4gICAgICAgICAgICAgICAgICAgIHBvaW50SGl0UmFkaXVzOiAxMCxcbiAgICAgICAgICAgICAgICAgICAgZGF0YTogdGhpcy5kYXRhLFxuICAgICAgICAgICAgICAgICAgICBzcGFuR2FwczogZmFsc2UsXG4gICAgICAgICAgICAgICAgfSwgXSxcbiAgICAgICAgICAgIH0sXG4gICAgICAgIH07XG4gICAgfSxcbn1cblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyByZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1saW5lLnZ1ZSJdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7OztBQU1BO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { "use strict"; eval("//\n//\n//\n//\n//\n\n/* harmony default export */ exports[\"default\"] = {\n mixins: [\n VueCharts.core.default,\n ],\n props: {\n backgroundcolor:{\n default: function () { return [\n \"#FF6384\",\n \"#36A2EB\",\n \"#FFCE56\",\n \"#00A600\"\n ]; },\n },\n hoverbackgroundcolor: {\n default: function () { return [\n \"#FF6384\",\n \"#36A2EB\",\n \"#FFCE56\",\n \"#00A600\"\n ]; },\n },\n bordercolor:{\n default: function () { return \"#fff\"; },\n },\n hoverbordercolor: {\n default: function () { return \"\"; },\n }\n },\n data: function data() {\n return {\n type: 'pie',\n chart_data: {\n labels: this.labels,\n datasets: [{\n label: this.datalabel,\n backgroundColor: this.backgroundcolor,\n borderColor: this.bordercolor,\n hoverBackgroundColor: this.hoverbackgroundcolor,\n hoverBorderColor: this.hoverbackgroundcolor,\n data: this.data\n }],\n },\n };\n },\n};\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMTIuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy9jb21wb25lbnRzL2NoYXJ0anMtcGllLnZ1ZT81MTUwIl0sInNvdXJjZXNDb250ZW50IjpbIi8vXG4vL1xuLy9cbi8vXG4vL1xuXG5leHBvcnQgZGVmYXVsdCB7XG4gICAgbWl4aW5zOiBbXG4gICAgICAgIFZ1ZUNoYXJ0cy5jb3JlLmRlZmF1bHQsXG4gICAgXSxcbiAgICBwcm9wczoge1xuICAgICAgICBiYWNrZ3JvdW5kY29sb3I6e1xuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gW1xuICAgICAgICAgICAgICAgIFwiI0ZGNjM4NFwiLFxuICAgICAgICAgICAgICAgIFwiIzM2QTJFQlwiLFxuICAgICAgICAgICAgICAgIFwiI0ZGQ0U1NlwiLFxuICAgICAgICAgICAgICAgIFwiIzAwQTYwMFwiXG4gICAgICAgICAgICBdLFxuICAgICAgICB9LFxuICAgICAgICBob3ZlcmJhY2tncm91bmRjb2xvcjoge1xuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gW1xuICAgICAgICAgICAgICAgIFwiI0ZGNjM4NFwiLFxuICAgICAgICAgICAgICAgIFwiIzM2QTJFQlwiLFxuICAgICAgICAgICAgICAgIFwiI0ZGQ0U1NlwiLFxuICAgICAgICAgICAgICAgIFwiIzAwQTYwMFwiXG4gICAgICAgICAgICBdLFxuICAgICAgICB9LFxuICAgICAgICBib3JkZXJjb2xvcjp7XG4gICAgICAgICAgICBkZWZhdWx0OiAoKSA9PiBcIiNmZmZcIixcbiAgICAgICAgfSxcbiAgICAgICAgaG92ZXJib3JkZXJjb2xvcjoge1xuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gXCJcIixcbiAgICAgICAgfVxuICAgIH0sXG4gICAgZGF0YSgpIHtcbiAgICAgICAgcmV0dXJuIHtcbiAgICAgICAgICAgIHR5cGU6ICdwaWUnLFxuICAgICAgICAgICAgY2hhcnRfZGF0YToge1xuICAgICAgICAgICAgICAgIGxhYmVsczogdGhpcy5sYWJlbHMsXG4gICAgICAgICAgICAgICAgZGF0YXNldHM6IFt7XG4gICAgICAgICAgICAgICAgICAgIGxhYmVsOiB0aGlzLmRhdGFsYWJlbCxcbiAgICAgICAgICAgICAgICAgICAgYmFja2dyb3VuZENvbG9yOiB0aGlzLmJhY2tncm91bmRjb2xvcixcbiAgICAgICAgICAgICAgICAgICAgYm9yZGVyQ29sb3I6IHRoaXMuYm9yZGVyY29sb3IsXG4gICAgICAgICAgICAgICAgICAgIGhvdmVyQmFja2dyb3VuZENvbG9yOiB0aGlzLmhvdmVyYmFja2dyb3VuZGNvbG9yLFxuICAgICAgICAgICAgICAgICAgICBob3ZlckJvcmRlckNvbG9yOiB0aGlzLmhvdmVyYmFja2dyb3VuZGNvbG9yLFxuICAgICAgICAgICAgICAgICAgICBkYXRhOiB0aGlzLmRhdGFcbiAgICAgICAgICAgICAgICB9XSxcbiAgICAgICAgICAgIH0sXG4gICAgICAgIH07XG4gICAgfSxcbn1cblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyByZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1waWUudnVlIl0sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7O0FBTUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOyIsInNvdXJjZVJvb3QiOiIifQ=="); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { "use strict"; eval("//\n//\n//\n//\n//\n\n/* harmony default export */ exports[\"default\"] = {\n mixins: [\n VueCharts.core.default,\n ],\n props: {\n hoverbackgroundcolor: {\n default: function () { return \"rgba(75,192,192,0.6)\"; },\n },\n hoverbordercolor: {\n default: function () { return \"rgba(179,181,198,1)\"; },\n }\n },\n data: function data() {\n return {\n type: 'polarArea',\n chart_data: {\n labels: this.labels,\n datasets: [{\n label: this.datalabel,\n backgroundColor: this.backgroundcolor,\n borderColor: this.bordercolor,\n hoverBackgroundColor: this.hoverbackgroundcolor,\n hoverBorderColor: this.hoverbackgroundcolor,\n data: this.data\n }],\n },\n };\n },\n};\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMTMuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy9jb21wb25lbnRzL2NoYXJ0anMtcG9sYXItYXJlYS52dWU/MDBiMyJdLCJzb3VyY2VzQ29udGVudCI6WyIvL1xuLy9cbi8vXG4vL1xuLy9cblxuZXhwb3J0IGRlZmF1bHQge1xuICAgIG1peGluczogW1xuICAgICAgICBWdWVDaGFydHMuY29yZS5kZWZhdWx0LFxuICAgIF0sXG4gICAgcHJvcHM6IHtcbiAgICAgICAgaG92ZXJiYWNrZ3JvdW5kY29sb3I6IHtcbiAgICAgICAgICAgIGRlZmF1bHQ6ICgpID0+IFwicmdiYSg3NSwxOTIsMTkyLDAuNilcIixcbiAgICAgICAgfSxcbiAgICAgICAgaG92ZXJib3JkZXJjb2xvcjoge1xuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gXCJyZ2JhKDE3OSwxODEsMTk4LDEpXCIsXG4gICAgICAgIH1cbiAgICB9LFxuICAgIGRhdGEoKSB7XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICB0eXBlOiAncG9sYXJBcmVhJyxcbiAgICAgICAgICAgIGNoYXJ0X2RhdGE6IHtcbiAgICAgICAgICAgICAgICBsYWJlbHM6IHRoaXMubGFiZWxzLFxuICAgICAgICAgICAgICAgIGRhdGFzZXRzOiBbe1xuICAgICAgICAgICAgICAgICAgICBsYWJlbDogdGhpcy5kYXRhbGFiZWwsXG4gICAgICAgICAgICAgICAgICAgIGJhY2tncm91bmRDb2xvcjogdGhpcy5iYWNrZ3JvdW5kY29sb3IsXG4gICAgICAgICAgICAgICAgICAgIGJvcmRlckNvbG9yOiB0aGlzLmJvcmRlcmNvbG9yLFxuICAgICAgICAgICAgICAgICAgICBob3ZlckJhY2tncm91bmRDb2xvcjogdGhpcy5ob3ZlcmJhY2tncm91bmRjb2xvcixcbiAgICAgICAgICAgICAgICAgICAgaG92ZXJCb3JkZXJDb2xvcjogdGhpcy5ob3ZlcmJhY2tncm91bmRjb2xvcixcbiAgICAgICAgICAgICAgICAgICAgZGF0YTogdGhpcy5kYXRhXG4gICAgICAgICAgICAgICAgfV0sXG4gICAgICAgICAgICB9LFxuICAgICAgICB9O1xuICAgIH0sXG59XG5cblxuXG4vLyBXRUJQQUNLIEZPT1RFUiAvL1xuLy8gcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy9jb21wb25lbnRzL2NoYXJ0anMtcG9sYXItYXJlYS52dWUiXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7QUFNQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOyIsInNvdXJjZVJvb3QiOiIifQ=="); /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { "use strict"; eval("//\n//\n//\n//\n//\n\n/* harmony default export */ exports[\"default\"] = {\n mixins: [\n VueCharts.core.default,\n ],\n props: {\n pointbordercolor: {\n default: function () { return \"#fff\"; },\n },\n pointbackgroundcolor: {\n default: function () { return \"rgba(179,181,198,1)\"; },\n }\n },\n data: function data() {\n return {\n type: 'radar',\n chart_data: {\n labels: this.labels,\n datasets: [{\n label: this.datalabel,\n backgroundColor: this.backgroundcolor,\n borderColor: this.bordercolor,\n pointBackgroundColor: this.pointbackgroundcolor,\n pointBorderColor: this.pointbordercolor,\n pointHoverBackgroundColor: \"#fff\",\n pointHoverBorderColor: \"rgba(179,181,198,1)\",\n data: this.data\n }],\n },\n options: {\n scale: {\n reverse: false,\n ticks: {\n beginAtZero: this.beginzero\n }\n }\n },\n };\n },\n};\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMTQuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy9jb21wb25lbnRzL2NoYXJ0anMtcmFkYXIudnVlPzYwYjciXSwic291cmNlc0NvbnRlbnQiOlsiLy9cbi8vXG4vL1xuLy9cbi8vXG5cbmV4cG9ydCBkZWZhdWx0IHtcbiAgICBtaXhpbnM6IFtcbiAgICAgICAgVnVlQ2hhcnRzLmNvcmUuZGVmYXVsdCxcbiAgICBdLFxuICAgIHByb3BzOiB7XG4gICAgICAgIHBvaW50Ym9yZGVyY29sb3I6IHtcbiAgICAgICAgICAgIGRlZmF1bHQ6ICgpID0+IFwiI2ZmZlwiLFxuICAgICAgICB9LFxuICAgICAgICBwb2ludGJhY2tncm91bmRjb2xvcjoge1xuICAgICAgICAgICAgZGVmYXVsdDogKCkgPT4gXCJyZ2JhKDE3OSwxODEsMTk4LDEpXCIsXG4gICAgICAgIH1cbiAgICB9LFxuICAgIGRhdGEoKSB7XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICB0eXBlOiAncmFkYXInLFxuICAgICAgICAgICAgY2hhcnRfZGF0YToge1xuICAgICAgICAgICAgICAgIGxhYmVsczogdGhpcy5sYWJlbHMsXG4gICAgICAgICAgICAgICAgZGF0YXNldHM6IFt7XG4gICAgICAgICAgICAgICAgICAgIGxhYmVsOiB0aGlzLmRhdGFsYWJlbCxcbiAgICAgICAgICAgICAgICAgICAgYmFja2dyb3VuZENvbG9yOiB0aGlzLmJhY2tncm91bmRjb2xvcixcbiAgICAgICAgICAgICAgICAgICAgYm9yZGVyQ29sb3I6IHRoaXMuYm9yZGVyY29sb3IsXG4gICAgICAgICAgICAgICAgICAgIHBvaW50QmFja2dyb3VuZENvbG9yOiB0aGlzLnBvaW50YmFja2dyb3VuZGNvbG9yLFxuICAgICAgICAgICAgICAgICAgICBwb2ludEJvcmRlckNvbG9yOiB0aGlzLnBvaW50Ym9yZGVyY29sb3IsXG4gICAgICAgICAgICAgICAgICAgIHBvaW50SG92ZXJCYWNrZ3JvdW5kQ29sb3I6IFwiI2ZmZlwiLFxuICAgICAgICAgICAgICAgICAgICBwb2ludEhvdmVyQm9yZGVyQ29sb3I6IFwicmdiYSgxNzksMTgxLDE5OCwxKVwiLFxuICAgICAgICAgICAgICAgICAgICBkYXRhOiB0aGlzLmRhdGFcbiAgICAgICAgICAgICAgICB9XSxcbiAgICAgICAgICAgIH0sXG4gICAgICAgICAgICBvcHRpb25zOiB7XG4gICAgICAgICAgICAgICAgc2NhbGU6IHtcbiAgICAgICAgICAgICAgICAgICAgcmV2ZXJzZTogZmFsc2UsXG4gICAgICAgICAgICAgICAgICAgIHRpY2tzOiB7XG4gICAgICAgICAgICAgICAgICAgICAgICBiZWdpbkF0WmVybzogdGhpcy5iZWdpbnplcm9cbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0sXG4gICAgICAgIH07XG4gICAgfSxcbn1cblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyByZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1yYWRhci52dWUiXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7QUFNQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { eval("module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;\n return _c('div', [(!_vm.target) ? _c('canvas', {\n ref: \"canvas\",\n attrs: {\n \"width\": _vm.width,\n \"height\": _vm.height\n }\n }) : _vm._e()])\n},staticRenderFns: []}\nif (false) {\n module.hot.accept()\n if (module.hot.data) {\n require(\"vue-hot-reload-api\").rerender(\"data-v-25c2c9c8\", module.exports)\n }\n}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMTUuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1iYXIudnVlPzQ0YjEiXSwic291cmNlc0NvbnRlbnQiOlsibW9kdWxlLmV4cG9ydHM9e3JlbmRlcjpmdW5jdGlvbiAoKXt2YXIgX3ZtPXRoaXM7dmFyIF9oPV92bS4kY3JlYXRlRWxlbWVudDt2YXIgX2M9X3ZtLl9zZWxmLl9jfHxfaDtcbiAgcmV0dXJuIF9jKCdkaXYnLCBbKCFfdm0udGFyZ2V0KSA/IF9jKCdjYW52YXMnLCB7XG4gICAgcmVmOiBcImNhbnZhc1wiLFxuICAgIGF0dHJzOiB7XG4gICAgICBcIndpZHRoXCI6IF92bS53aWR0aCxcbiAgICAgIFwiaGVpZ2h0XCI6IF92bS5oZWlnaHRcbiAgICB9XG4gIH0pIDogX3ZtLl9lKCldKVxufSxzdGF0aWNSZW5kZXJGbnM6IFtdfVxuaWYgKG1vZHVsZS5ob3QpIHtcbiAgbW9kdWxlLmhvdC5hY2NlcHQoKVxuICBpZiAobW9kdWxlLmhvdC5kYXRhKSB7XG4gICAgIHJlcXVpcmUoXCJ2dWUtaG90LXJlbG9hZC1hcGlcIikucmVyZW5kZXIoXCJkYXRhLXYtMjVjMmM5YzhcIiwgbW9kdWxlLmV4cG9ydHMpXG4gIH1cbn1cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL34vdnVlLWxvYWRlci9saWIvdGVtcGxhdGUtY29tcGlsZXIuanM/aWQ9ZGF0YS12LTI1YzJjOWM4IS4vfi92dWUtbG9hZGVyL2xpYi9zZWxlY3Rvci5qcz90eXBlPXRlbXBsYXRlJmluZGV4PTAhLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1iYXIudnVlXG4vLyBtb2R1bGUgaWQgPSAxNVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsInNvdXJjZVJvb3QiOiIifQ=="); /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { eval("module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;\n return _c('div', [(!_vm.target) ? _c('canvas', {\n ref: \"canvas\",\n attrs: {\n \"width\": _vm.width,\n \"height\": _vm.height\n }\n }) : _vm._e()])\n},staticRenderFns: []}\nif (false) {\n module.hot.accept()\n if (module.hot.data) {\n require(\"vue-hot-reload-api\").rerender(\"data-v-42b527d6\", module.exports)\n }\n}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMTYuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1waWUudnVlPzNjNzEiXSwic291cmNlc0NvbnRlbnQiOlsibW9kdWxlLmV4cG9ydHM9e3JlbmRlcjpmdW5jdGlvbiAoKXt2YXIgX3ZtPXRoaXM7dmFyIF9oPV92bS4kY3JlYXRlRWxlbWVudDt2YXIgX2M9X3ZtLl9zZWxmLl9jfHxfaDtcbiAgcmV0dXJuIF9jKCdkaXYnLCBbKCFfdm0udGFyZ2V0KSA/IF9jKCdjYW52YXMnLCB7XG4gICAgcmVmOiBcImNhbnZhc1wiLFxuICAgIGF0dHJzOiB7XG4gICAgICBcIndpZHRoXCI6IF92bS53aWR0aCxcbiAgICAgIFwiaGVpZ2h0XCI6IF92bS5oZWlnaHRcbiAgICB9XG4gIH0pIDogX3ZtLl9lKCldKVxufSxzdGF0aWNSZW5kZXJGbnM6IFtdfVxuaWYgKG1vZHVsZS5ob3QpIHtcbiAgbW9kdWxlLmhvdC5hY2NlcHQoKVxuICBpZiAobW9kdWxlLmhvdC5kYXRhKSB7XG4gICAgIHJlcXVpcmUoXCJ2dWUtaG90LXJlbG9hZC1hcGlcIikucmVyZW5kZXIoXCJkYXRhLXYtNDJiNTI3ZDZcIiwgbW9kdWxlLmV4cG9ydHMpXG4gIH1cbn1cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL34vdnVlLWxvYWRlci9saWIvdGVtcGxhdGUtY29tcGlsZXIuanM/aWQ9ZGF0YS12LTQyYjUyN2Q2IS4vfi92dWUtbG9hZGVyL2xpYi9zZWxlY3Rvci5qcz90eXBlPXRlbXBsYXRlJmluZGV4PTAhLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1waWUudnVlXG4vLyBtb2R1bGUgaWQgPSAxNlxuLy8gbW9kdWxlIGNodW5rcyA9IDAiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsInNvdXJjZVJvb3QiOiIifQ=="); /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { eval("module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;\n return _c('div', [(!_vm.target) ? _c('canvas', {\n ref: \"canvas\",\n attrs: {\n \"width\": _vm.width,\n \"height\": _vm.height\n }\n }) : _vm._e()])\n},staticRenderFns: []}\nif (false) {\n module.hot.accept()\n if (module.hot.data) {\n require(\"vue-hot-reload-api\").rerender(\"data-v-537a6f62\", module.exports)\n }\n}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMTcuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1yYWRhci52dWU/OTc2MCJdLCJzb3VyY2VzQ29udGVudCI6WyJtb2R1bGUuZXhwb3J0cz17cmVuZGVyOmZ1bmN0aW9uICgpe3ZhciBfdm09dGhpczt2YXIgX2g9X3ZtLiRjcmVhdGVFbGVtZW50O3ZhciBfYz1fdm0uX3NlbGYuX2N8fF9oO1xuICByZXR1cm4gX2MoJ2RpdicsIFsoIV92bS50YXJnZXQpID8gX2MoJ2NhbnZhcycsIHtcbiAgICByZWY6IFwiY2FudmFzXCIsXG4gICAgYXR0cnM6IHtcbiAgICAgIFwid2lkdGhcIjogX3ZtLndpZHRoLFxuICAgICAgXCJoZWlnaHRcIjogX3ZtLmhlaWdodFxuICAgIH1cbiAgfSkgOiBfdm0uX2UoKV0pXG59LHN0YXRpY1JlbmRlckZuczogW119XG5pZiAobW9kdWxlLmhvdCkge1xuICBtb2R1bGUuaG90LmFjY2VwdCgpXG4gIGlmIChtb2R1bGUuaG90LmRhdGEpIHtcbiAgICAgcmVxdWlyZShcInZ1ZS1ob3QtcmVsb2FkLWFwaVwiKS5yZXJlbmRlcihcImRhdGEtdi01MzdhNmY2MlwiLCBtb2R1bGUuZXhwb3J0cylcbiAgfVxufVxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vfi92dWUtbG9hZGVyL2xpYi90ZW1wbGF0ZS1jb21waWxlci5qcz9pZD1kYXRhLXYtNTM3YTZmNjIhLi9+L3Z1ZS1sb2FkZXIvbGliL3NlbGVjdG9yLmpzP3R5cGU9dGVtcGxhdGUmaW5kZXg9MCEuL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLXJhZGFyLnZ1ZVxuLy8gbW9kdWxlIGlkID0gMTdcbi8vIG1vZHVsZSBjaHVua3MgPSAwIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJzb3VyY2VSb290IjoiIn0="); /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { eval("module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;\n return _c('div', [(!_vm.target) ? _c('canvas', {\n ref: \"canvas\",\n attrs: {\n \"width\": _vm.width,\n \"height\": _vm.height\n }\n }) : _vm._e()])\n},staticRenderFns: []}\nif (false) {\n module.hot.accept()\n if (module.hot.data) {\n require(\"vue-hot-reload-api\").rerender(\"data-v-59bae249\", module.exports)\n }\n}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMTguanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1kb3VnaG51dC52dWU/ZGE0NCJdLCJzb3VyY2VzQ29udGVudCI6WyJtb2R1bGUuZXhwb3J0cz17cmVuZGVyOmZ1bmN0aW9uICgpe3ZhciBfdm09dGhpczt2YXIgX2g9X3ZtLiRjcmVhdGVFbGVtZW50O3ZhciBfYz1fdm0uX3NlbGYuX2N8fF9oO1xuICByZXR1cm4gX2MoJ2RpdicsIFsoIV92bS50YXJnZXQpID8gX2MoJ2NhbnZhcycsIHtcbiAgICByZWY6IFwiY2FudmFzXCIsXG4gICAgYXR0cnM6IHtcbiAgICAgIFwid2lkdGhcIjogX3ZtLndpZHRoLFxuICAgICAgXCJoZWlnaHRcIjogX3ZtLmhlaWdodFxuICAgIH1cbiAgfSkgOiBfdm0uX2UoKV0pXG59LHN0YXRpY1JlbmRlckZuczogW119XG5pZiAobW9kdWxlLmhvdCkge1xuICBtb2R1bGUuaG90LmFjY2VwdCgpXG4gIGlmIChtb2R1bGUuaG90LmRhdGEpIHtcbiAgICAgcmVxdWlyZShcInZ1ZS1ob3QtcmVsb2FkLWFwaVwiKS5yZXJlbmRlcihcImRhdGEtdi01OWJhZTI0OVwiLCBtb2R1bGUuZXhwb3J0cylcbiAgfVxufVxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vfi92dWUtbG9hZGVyL2xpYi90ZW1wbGF0ZS1jb21waWxlci5qcz9pZD1kYXRhLXYtNTliYWUyNDkhLi9+L3Z1ZS1sb2FkZXIvbGliL3NlbGVjdG9yLmpzP3R5cGU9dGVtcGxhdGUmaW5kZXg9MCEuL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLWRvdWdobnV0LnZ1ZVxuLy8gbW9kdWxlIGlkID0gMThcbi8vIG1vZHVsZSBjaHVua3MgPSAwIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJzb3VyY2VSb290IjoiIn0="); /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { eval("module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;\n return _c('div', [(!_vm.target) ? _c('canvas', {\n ref: \"canvas\",\n attrs: {\n \"width\": _vm.width,\n \"height\": _vm.height\n }\n }) : _vm._e()])\n},staticRenderFns: []}\nif (false) {\n module.hot.accept()\n if (module.hot.data) {\n require(\"vue-hot-reload-api\").rerender(\"data-v-6502cf43\", module.exports)\n }\n}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMTkuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1wb2xhci1hcmVhLnZ1ZT9jMmNiIl0sInNvdXJjZXNDb250ZW50IjpbIm1vZHVsZS5leHBvcnRzPXtyZW5kZXI6ZnVuY3Rpb24gKCl7dmFyIF92bT10aGlzO3ZhciBfaD1fdm0uJGNyZWF0ZUVsZW1lbnQ7dmFyIF9jPV92bS5fc2VsZi5fY3x8X2g7XG4gIHJldHVybiBfYygnZGl2JywgWyghX3ZtLnRhcmdldCkgPyBfYygnY2FudmFzJywge1xuICAgIHJlZjogXCJjYW52YXNcIixcbiAgICBhdHRyczoge1xuICAgICAgXCJ3aWR0aFwiOiBfdm0ud2lkdGgsXG4gICAgICBcImhlaWdodFwiOiBfdm0uaGVpZ2h0XG4gICAgfVxuICB9KSA6IF92bS5fZSgpXSlcbn0sc3RhdGljUmVuZGVyRm5zOiBbXX1cbmlmIChtb2R1bGUuaG90KSB7XG4gIG1vZHVsZS5ob3QuYWNjZXB0KClcbiAgaWYgKG1vZHVsZS5ob3QuZGF0YSkge1xuICAgICByZXF1aXJlKFwidnVlLWhvdC1yZWxvYWQtYXBpXCIpLnJlcmVuZGVyKFwiZGF0YS12LTY1MDJjZjQzXCIsIG1vZHVsZS5leHBvcnRzKVxuICB9XG59XG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9+L3Z1ZS1sb2FkZXIvbGliL3RlbXBsYXRlLWNvbXBpbGVyLmpzP2lkPWRhdGEtdi02NTAyY2Y0MyEuL34vdnVlLWxvYWRlci9saWIvc2VsZWN0b3IuanM/dHlwZT10ZW1wbGF0ZSZpbmRleD0wIS4vcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy9jb21wb25lbnRzL2NoYXJ0anMtcG9sYXItYXJlYS52dWVcbi8vIG1vZHVsZSBpZCA9IDE5XG4vLyBtb2R1bGUgY2h1bmtzID0gMCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { eval("module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;\n return _c('div', [(!_vm.target) ? _c('canvas', {\n ref: \"canvas\",\n attrs: {\n \"width\": _vm.width,\n \"height\": _vm.height\n }\n }) : _vm._e()])\n},staticRenderFns: []}\nif (false) {\n module.hot.accept()\n if (module.hot.data) {\n require(\"vue-hot-reload-api\").rerender(\"data-v-68c558bb\", module.exports)\n }\n}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjAuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1saW5lLnZ1ZT85ZTBmIl0sInNvdXJjZXNDb250ZW50IjpbIm1vZHVsZS5leHBvcnRzPXtyZW5kZXI6ZnVuY3Rpb24gKCl7dmFyIF92bT10aGlzO3ZhciBfaD1fdm0uJGNyZWF0ZUVsZW1lbnQ7dmFyIF9jPV92bS5fc2VsZi5fY3x8X2g7XG4gIHJldHVybiBfYygnZGl2JywgWyghX3ZtLnRhcmdldCkgPyBfYygnY2FudmFzJywge1xuICAgIHJlZjogXCJjYW52YXNcIixcbiAgICBhdHRyczoge1xuICAgICAgXCJ3aWR0aFwiOiBfdm0ud2lkdGgsXG4gICAgICBcImhlaWdodFwiOiBfdm0uaGVpZ2h0XG4gICAgfVxuICB9KSA6IF92bS5fZSgpXSlcbn0sc3RhdGljUmVuZGVyRm5zOiBbXX1cbmlmIChtb2R1bGUuaG90KSB7XG4gIG1vZHVsZS5ob3QuYWNjZXB0KClcbiAgaWYgKG1vZHVsZS5ob3QuZGF0YSkge1xuICAgICByZXF1aXJlKFwidnVlLWhvdC1yZWxvYWQtYXBpXCIpLnJlcmVuZGVyKFwiZGF0YS12LTY4YzU1OGJiXCIsIG1vZHVsZS5leHBvcnRzKVxuICB9XG59XG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9+L3Z1ZS1sb2FkZXIvbGliL3RlbXBsYXRlLWNvbXBpbGVyLmpzP2lkPWRhdGEtdi02OGM1NThiYiEuL34vdnVlLWxvYWRlci9saWIvc2VsZWN0b3IuanM/dHlwZT10ZW1wbGF0ZSZpbmRleD0wIS4vcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy9jb21wb25lbnRzL2NoYXJ0anMtbGluZS52dWVcbi8vIG1vZHVsZSBpZCA9IDIwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwic291cmNlUm9vdCI6IiJ9"); /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { eval("module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;\n return _c('div', [(!_vm.target) ? _c('canvas', {\n ref: \"canvas\",\n attrs: {\n \"width\": _vm.width,\n \"height\": _vm.height\n }\n }) : _vm._e()])\n},staticRenderFns: []}\nif (false) {\n module.hot.accept()\n if (module.hot.data) {\n require(\"vue-hot-reload-api\").rerender(\"data-v-6d89d9f1\", module.exports)\n }\n}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjEuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvYXNzZXRzL2pzL3Z1ZS1jaGFydHMvc3JjL2NvbXBvbmVudHMvY2hhcnRqcy1ob3Jpem9udGFsLWJhci52dWU/MmUwNyJdLCJzb3VyY2VzQ29udGVudCI6WyJtb2R1bGUuZXhwb3J0cz17cmVuZGVyOmZ1bmN0aW9uICgpe3ZhciBfdm09dGhpczt2YXIgX2g9X3ZtLiRjcmVhdGVFbGVtZW50O3ZhciBfYz1fdm0uX3NlbGYuX2N8fF9oO1xuICByZXR1cm4gX2MoJ2RpdicsIFsoIV92bS50YXJnZXQpID8gX2MoJ2NhbnZhcycsIHtcbiAgICByZWY6IFwiY2FudmFzXCIsXG4gICAgYXR0cnM6IHtcbiAgICAgIFwid2lkdGhcIjogX3ZtLndpZHRoLFxuICAgICAgXCJoZWlnaHRcIjogX3ZtLmhlaWdodFxuICAgIH1cbiAgfSkgOiBfdm0uX2UoKV0pXG59LHN0YXRpY1JlbmRlckZuczogW119XG5pZiAobW9kdWxlLmhvdCkge1xuICBtb2R1bGUuaG90LmFjY2VwdCgpXG4gIGlmIChtb2R1bGUuaG90LmRhdGEpIHtcbiAgICAgcmVxdWlyZShcInZ1ZS1ob3QtcmVsb2FkLWFwaVwiKS5yZXJlbmRlcihcImRhdGEtdi02ZDg5ZDlmMVwiLCBtb2R1bGUuZXhwb3J0cylcbiAgfVxufVxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vfi92dWUtbG9hZGVyL2xpYi90ZW1wbGF0ZS1jb21waWxlci5qcz9pZD1kYXRhLXYtNmQ4OWQ5ZjEhLi9+L3Z1ZS1sb2FkZXIvbGliL3NlbGVjdG9yLmpzP3R5cGU9dGVtcGxhdGUmaW5kZXg9MCEuL3Jlc291cmNlcy9hc3NldHMvanMvdnVlLWNoYXJ0cy9zcmMvY29tcG9uZW50cy9jaGFydGpzLWhvcml6b250YWwtYmFyLnZ1ZVxuLy8gbW9kdWxlIGlkID0gMjFcbi8vIG1vZHVsZSBjaHVua3MgPSAwIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJzb3VyY2VSb290IjoiIn0="); /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { eval("if(typeof Chart === \"undefined\")\n throw \"ChartJS is undefined\";\n// 4 kb here\nwindow.VueCharts = {};\n\nVueCharts.core = __webpack_require__(0);\n\nVueCharts.install = function (Vue) {\n Vue.component('chartjs-line', __webpack_require__(4));\n Vue.component('chartjs-bar', __webpack_require__(1));\n Vue.component('chartjs-horizontal-bar', __webpack_require__(3));\n Vue.component('chartjs-radar', __webpack_require__(7));\n Vue.component('chartjs-polar-area', __webpack_require__(6));\n Vue.component('chartjs-pie', __webpack_require__(5));\n Vue.component('chartjs-doughnut', __webpack_require__(2));\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjIuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy92dWUtY2hhcnRzLmpzP2Q3NjYiXSwic291cmNlc0NvbnRlbnQiOlsiaWYodHlwZW9mIENoYXJ0ID09PSBcInVuZGVmaW5lZFwiKVxuICAgIHRocm93IFwiQ2hhcnRKUyBpcyB1bmRlZmluZWRcIjtcbi8vIDQga2IgaGVyZVxud2luZG93LlZ1ZUNoYXJ0cyA9IHt9O1xuXG5WdWVDaGFydHMuY29yZSA9IHJlcXVpcmUoJy4vdnVlLWNoYXJ0anMtbGliLmpzJyk7XG5cblZ1ZUNoYXJ0cy5pbnN0YWxsID0gZnVuY3Rpb24gKFZ1ZSkge1xuICAgIFZ1ZS5jb21wb25lbnQoJ2NoYXJ0anMtbGluZScsIHJlcXVpcmUoJy4vY29tcG9uZW50cy9jaGFydGpzLWxpbmUudnVlJykpO1xuICAgIFZ1ZS5jb21wb25lbnQoJ2NoYXJ0anMtYmFyJywgcmVxdWlyZSgnLi9jb21wb25lbnRzL2NoYXJ0anMtYmFyLnZ1ZScpKTtcbiAgICBWdWUuY29tcG9uZW50KCdjaGFydGpzLWhvcml6b250YWwtYmFyJywgcmVxdWlyZSgnLi9jb21wb25lbnRzL2NoYXJ0anMtaG9yaXpvbnRhbC1iYXIudnVlJykpO1xuICAgIFZ1ZS5jb21wb25lbnQoJ2NoYXJ0anMtcmFkYXInLCByZXF1aXJlKCcuL2NvbXBvbmVudHMvY2hhcnRqcy1yYWRhci52dWUnKSk7XG4gICAgVnVlLmNvbXBvbmVudCgnY2hhcnRqcy1wb2xhci1hcmVhJywgcmVxdWlyZSgnLi9jb21wb25lbnRzL2NoYXJ0anMtcG9sYXItYXJlYS52dWUnKSk7XG4gICAgVnVlLmNvbXBvbmVudCgnY2hhcnRqcy1waWUnLCByZXF1aXJlKCcuL2NvbXBvbmVudHMvY2hhcnRqcy1waWUudnVlJykpO1xuICAgIFZ1ZS5jb21wb25lbnQoJ2NoYXJ0anMtZG91Z2hudXQnLCByZXF1aXJlKCcuL2NvbXBvbmVudHMvY2hhcnRqcy1kb3VnaG51dC52dWUnKSk7XG59XG5cblxuXG4vLyBXRUJQQUNLIEZPT1RFUiAvL1xuLy8gcmVzb3VyY2VzL2Fzc2V0cy9qcy92dWUtY2hhcnRzL3NyYy92dWUtY2hhcnRzLmpzIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOyIsInNvdXJjZVJvb3QiOiIifQ=="); /***/ } /******/ ]);
import vcr # Set to True to enable 'once' mock recording MOCK_RECORDING_ENABLED = False vcr = vcr.VCR( cassette_library_dir='tests/mock/', record_mode='once' if MOCK_RECORDING_ENABLED else 'none', match_on=['uri'], )
class NNL: def __init__(self, parentLayer=None, childLayer=None, linearOutput=False, useMomentum=False, momentumFactor=0.9) -> None: self.parentLayer = parentLayer #NNL self.childLayer = childLayer #NNL self.linearOutput = linearOutput #bool self.useMomentum = useMomentum #bool self.momentumFactor = momentumFactor #double self.numNodes = None #int self.numChildNodes = None #int self.numParentNodes = None #int self.weights = None #double** self.weightChanges = None #double** self.neuronValues = None #double* self.desiredValues = None #double* self.errors = None #double* self.biasWeights = None #double* self.biasValues = None #double* self.learningRate = None #double* def initialize(self, parentNNLayer, childNNLayer): self.neuronValues = [0] * self.numNodes self.desiredValues = [0] * self.numNodes self.errors = [0] * self.numNodes self.parentLayer = parentNNLayer if parentNNLayer is not None else None if(childNNLayer is not None): self.childLayer = childNNLayer self.weights = [0] * self.numNodes self.weightChanges = [0] * self.numNodes for x in range(self.numNodes): self.weights[x] = [0] * self.numChildNodes self.weightChanges[x] = [0] * self.numChildNodes self.biasValues = [-1] * self.numChildNodes self.biasWeights = [0] * self.numChildNodes def cleanup(): pass def randomizeWeights(): pass def calculateErrors(): pass def adjustWeights(): pass def calculateNeuronValues(): pass class NN: def __init__(self, ipl: NNL, hdl: NNL, opl: NNL) -> None: self.inputLayer = ipl self.hiddenLayer = hdl self.outputLayer = opl pass def initialize(self,nNodesInput, nNodesHidden, nNodesOutput): self.inputLayer.numNodes = nNodesInput self.inputLayer.numChildNodes = nNodesHidden self.inputLayer.numParentNodes = 0 self.inputLayer.initialize(None, self.hiddenLayer) self.inputLayer.randomizeWeights() self.hiddenLayer.numNodes = nNodesHidden self.hiddenLayer.numChildNodes = nNodesOutput self.hiddenLayer.numParentNodes = nNodesInput self.hiddenLayer.initialize(self.inputLayer, self.outputLayer) self.hiddenLayer.randomizeWeights() self.outputLayer.numNodes = nNodesOutput self.outputLayer.numChildNodes = 0 self.outputLayer.numParentNodes = nNodesHidden self.outputLayer.initialize(self.hiddenLayer, None) def main(): #test = NN test = NNL(linearOutput=True, useMomentum=True, momentumFactor=0.91) test.numNodes = 2 test.numChildNodes = 3 test.initialize(None, None) print(test.weights) print(test.weightChanges) print(test.biasValues) print(test.biasWeights) # test.numNodes = 10 # test.numChildNodes = 12 # test.numParentNodes = 0 # test.initialize(None, ) # print(test.linearOutput) # print(test.parentLayer.useMomentum) # print(test.childLayer.useMomentum) main()
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2014 Grupo de Sistemas Inteligentes (GSI) DIT, UPM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Senpy is a modular sentiment analysis server. This script runs an instance of the server. """ from flask import Flask from senpy.extensions import Senpy from senpy.utils import easy_test import logging import os import sys import argparse import senpy SERVER_PORT = os.environ.get("PORT", 5000) def main(): parser = argparse.ArgumentParser(description='Run a Senpy server') parser.add_argument( '--level', '-l', metavar='logging_level', type=str, default="INFO", help='Logging level') parser.add_argument( '--log-format', metavar='log_format', type=str, default='%(asctime)s %(levelname)-10s %(name)-30s \t %(message)s', help='Logging format') parser.add_argument( '--debug', '-d', action='store_true', default=False, help='Run the application in debug mode') parser.add_argument( '--no-default-plugins', action='store_true', default=False, help='Do not load the default plugins') parser.add_argument( '--host', type=str, default="0.0.0.0", help='Use 0.0.0.0 to accept requests from any host.') parser.add_argument( '--port', '-p', type=int, default=SERVER_PORT, help='Port to listen on.') parser.add_argument( '--plugins-folder', '-f', type=str, action='append', help='Where to look for plugins.') parser.add_argument( '--only-install', '-i', action='store_true', default=False, help='Do not run a server, only install plugin dependencies') parser.add_argument( '--only-test', action='store_true', default=False, help='Do not run a server, just test all plugins') parser.add_argument( '--test', '-t', action='store_true', default=False, help='Test all plugins before launching the server') parser.add_argument( '--only-list', '--list', action='store_true', default=False, help='Do not run a server, only list plugins found') parser.add_argument( '--data-folder', '--data', type=str, default=None, help='Where to look for data. It be set with the SENPY_DATA environment variable as well.') parser.add_argument( '--no-threaded', action='store_true', default=False, help='Run a single-threaded server') parser.add_argument( '--no-deps', '-n', action='store_true', default=False, help='Skip installing dependencies') parser.add_argument( '--version', '-v', action='store_true', default=False, help='Output the senpy version and exit') parser.add_argument( '--allow-fail', '--fail', action='store_true', default=False, help='Do not exit if some plugins fail to activate') args = parser.parse_args() print('Senpy version {}'.format(senpy.__version__)) print(sys.version) if args.version: exit(1) rl = logging.getLogger() rl.setLevel(getattr(logging, args.level)) logger_handler = rl.handlers[0] # First, generic formatter: logger_handler.setFormatter(logging.Formatter(args.log_format)) app = Flask(__name__) app.debug = args.debug sp = Senpy(app, plugin_folder=None, default_plugins=not args.no_default_plugins, data_folder=args.data_folder) folders = list(args.plugins_folder) if args.plugins_folder else [] if not folders: folders.append(".") for p in folders: sp.add_folder(p) plugins = sp.plugins(plugin_type=None, is_activated=False) maxname = max(len(x.name) for x in plugins) maxversion = max(len(str(x.version)) for x in plugins) print('Found {} plugins:'.format(len(plugins))) for plugin in plugins: import inspect fpath = inspect.getfile(plugin.__class__) print('\t{: <{maxname}} @ {: <{maxversion}} -> {}'.format(plugin.name, plugin.version, fpath, maxname=maxname, maxversion=maxversion)) if args.only_list: return if not args.no_deps: sp.install_deps() if args.only_install: return sp.activate_all(allow_fail=args.allow_fail) if args.test or args.only_test: easy_test(sp.plugins(), debug=args.debug) if args.only_test: return print('Senpy version {}'.format(senpy.__version__)) print('Server running on port %s:%d. Ctrl+C to quit' % (args.host, args.port)) try: app.run(args.host, args.port, threaded=not args.no_threaded, debug=app.debug) except KeyboardInterrupt: print('Bye!') sp.deactivate_all() if __name__ == '__main__': main()
import * as actionTypes from './actionTypes' import * as Api from '../api/backendApi' export const loadCommentsSuccess = (comments) => { return { type: actionTypes.LOAD_COMMENTS_SUCCESS, comments } } export const loadComments = (postId) => { return (dispatch) => { return Api.getCommentsByPostId(postId).then(comments => { dispatch(loadCommentsSuccess(comments)) }).catch(error => { throw(error) }) } }
export default class DragAndDropHandler { match(dragState, context) { // eslint-disable-line return false } drop(dragState, context) { // eslint-disable-line // nothing } get _isDragAndDropHandler () { return true } }
db= [{'_id' : '[O][O]', 'stoich' : 'O2', 'charge' : 0, 'mult' : 3, 'HeatForm': {0:0,'sigma':0.0}, 'g09' : { 'b3lyp' : {'6-311+g(d,p)':{'energy': -150.26605, 'sigma':0}}, 'm062x' : {'6-311+g(d,p)':{'energy': -150.308589, 'sigma':0}}, 'ccsd' : {'cc-pvtz':{'energy': -150.1110736, 'sigma':0}}, 'ccsd(t)' : {'cc-pvtz':{'energy': -150.1290363, 'sigma':0, 'zmat':'\n 0 3\n o1\n o2 o1 r2\nVariables:\n R2\t1.2123\n'}, 'freq': ' ' } } }, {'_id' : '[H][H]', 'stoich' : 'H2', 'charge' : 0, 'mult' : 1, 'HeatForm': {0:0, 298:0, 'sigma':0.0}, 'g09' : { 'b3lyp' : {'6-31+g(d,p)':{'energy': -1.17853935, 'sigma':0}}, 'ccsd' : {'cc-pvtz':{'energy': -1.1723367, 'sigma':0}}, 'ccsd(t)' : {'cc-pvtz':{'energy': -1.1723367, 'sigma':0, 'zmat' : '\n 0 1\n h1\n h2 h1 r2\nVariables:\n R2\t0.7427\n'}} } }, {'_id' : 'O', 'stoich' : 'H2O', 'charge' : 0, 'mult' : 1, 'HeatForm': {0:-286.300, 298:-285.828, 'sigma':0.027}, 'g09' : { 'b3lyp' : {'6-311+g(d,p)':{'energy': -76.434049, 'sigma':0}}, 'ccsd' : {'cc-pvtz':{'energy': -76.3245455, 'sigma':0}}, 'ccsd(t)' : {'cc-pvtz':{'energy': -76.3322164, 'sigma':0, 'zmat' : '\n 0 1\n o1\n h2 o1 r2\n h3 o1 r3 h2 a3\nVariables:\n R2\t0.9594\n R3\t0.9594\n A3\t103.5862\n'}} } }, {'_id' : 'C', 'stoich' : 'CH4', 'charge' : 0, 'mult' : 1, 'HeatForm': {0:-66.50, 298:-74.520, 'sigma':0.057}, 'g09' : { 'b3lyp' : {'6-31+g(d,p)':{'energy': -40.52613767, 'sigma':0, 'zmat': '\n 0 1\n c1\n h2 c1 R1\n h3 c1 R2 h2 A2\n h4 c1 R3 h2 A3 h3 D3 0\n h5 c1 R4 h2 A4 h3 D4 0\nVariables:\n R1\t1.0922\n R2\t1.0922\n A2\t109.4712\n R3\t1.0922\n A3\t109.4712\n D3\t240.0\n R4\t1.0922\n A4\t109.4712\n D4\t120.001\n'}}, 'm062x' : {'6-311+g(d,p)':{'energy': -40.4967602, 'sigma':0}}, 'ccsd' : {'cc-pvtz':{'energy': -40.4318181, 'sigma':0}}, 'ccsd(t)' : {'cc-pvtz':{'energy': -40.4380993, 'sigma':0, 'zmat': '\n 0 1\n c1\n h2 c1 R1\n h3 c1 R2 h2 A2\n h4 c1 R3 h2 A3 h3 D3 0\n h5 c1 R4 h2 A4 h3 D4 0\nVariables:\n R1\t1.0889\n R2\t1.0889\n A2\t109.4712\n R3\t1.0889\n A3\t109.4712\n D3\t240.0\n R4\t1.0889\n A4\t109.4712\n D4\t120.0\n'}} } }, {'_id' : 'O=C=O', 'stoich' : 'CO2', 'charge' : 0, 'mult' : 1, 'HeatForm': {0:-393.109, 298:-393.475, 'sigma':0.015}, 'g09' : { 'b3lyp' : {'6-311+g(d,p)':{'energy': -188.59039, 'sigma':0, 'zmat': '\n 0 1\n o1\n c2 o1 r2\n o3 c2 r3 o1 a3\nVariables:\n R2\t1.1694\n R3\t1.1694\n A3\t179.9963\n'}} } }, {'_id' : 'CC', 'stoich' : 'CH3CH3', 'charge' : 0, 'mult' : 1, 'HeatForm': {0:-68.29, 298:-83.91, 'sigma':0.14}, 'g09' : { 'b3lyp' : {'6-311+g(d,p)':{'energy': -79.84164, 'sigma':0, 'zmat': '\n 0 1\n c1\n h2 c1 R1\n h3 c1 R2 h2 A2\n h4 c1 R3 h2 A3 h3 D3 0\n h5 c1 R4 h2 A4 h3 D4 0\nVariables:\n R1\t1.0889\n R2\t1.0889\n A2\t109.4712\n R3\t1.0889\n A3\t109.4712\n D3\t240.0\n R4\t1.0889\n A4\t109.4712\n D4\t120.0\n'}} } }, {'_id' : 'CO', 'stoich' : 'CH3OH', 'charge' : 0, 'mult' : 1, 'HeatForm': {0:-189.83, 298:-200.71, 'sigma':0.16}, 'g09' : { 'b3lyp' : {'6-311+g(d,p)':{'energy': -115.73487, 'sigma':0}} } }, {'_id' : 'N', 'stoich' : 'NH3', 'charge' : 0, 'mult' : 1, 'HeatForm': {0:-38.562, 298:-45.554, 'sigma':0.057} }, {'_id' : 'C=O', 'stoich' : 'CH2O', 'charge' : 0, 'mult' : 1, 'HeatForm': {0:-105.349, 298:-109.188, 'sigma':0.099}, 'g09' : { 'm062x' : {'6-311+g(d,p)':{'energy': -114.51152, 'sigma':0, 'zmat':'\n 0 1\n c1\n o2 c1 R1\n h3 c1 R2 o2 A2\n h4 c1 R3 o2 A3 h3 D3 0\nVariables:\n R1\t1.1969\n R2\t1.1047\n A2\t121.7284\n R3\t1.1047\n A3\t121.7284\n D3\t179.9995\n'}} } }]
'use strict'; var browserSync = require('browser-sync'), gulp = require('gulp'); gulp.task('browserSync', function() { browserSync({ files: ['views/**'], proxy: 'localhost:8080', notify: false }); });
var PersistentFilter = require('broccoli-persistent-filter'), RSVP = require('rsvp'), path = require('path'), fs = require('fs'), fsExtra = require('fs-extra'), Builder = require('systemjs-builder'), symlinkOrCopySync = require('symlink-or-copy').sync; var isWin = process.platform.match(/^win/); function toFileURL(path) { return 'file://' + (isWin ? '/' : '') + path.replace(/\\/g, '/'); }; function SystemJSBuilder ( inputNodes, baseURL, configPaths, fn ) { if (!(this instanceof SystemJSBuilder)) { return new SystemJSBuilder(inputNodes, baseURL, configPath, fn); } PersistentFilter.call(this, inputNodes); this.buildCount = 0; this.builder = new Builder(); this.baseURL = baseURL; this.configPaths = configPaths; this.fn = fn; }; SystemJSBuilder.prototype = Object.create(PersistentFilter.prototype); SystemJSBuilder.prototype.constructor = SystemJSBuilder; SystemJSBuilder.prototype.build = function() { var sourceDir = this.inputPaths[0], destDir = this.outputPath, configPaths = this.configPaths, baseURL = path.join(destDir, this.baseURL), builder = this.builder, fn = this.fn, self = this; return PersistentFilter.prototype.build.call(this).then(function() { if (self.buildCount++ === 0) { builder.config({ baseURL: baseURL }, true, false); configPaths.forEach(function(configPath) { configPath = path.join(destDir, configPath); builder.loadConfigSync(configPath, true, true); }); } var cwd = process.cwd(); // XXX: Not currently a good way to configure the output directory process.chdir(destDir); return fn(builder, sourceDir, destDir).then(function(res) { process.chdir(cwd); return res; }, function(err) { process.chdir(cwd); throw err; }); }); }; SystemJSBuilder.prototype._handleFile = function(relativePath, srcDir, destDir, entry, outputPath, isChange, instrumentation) { var srcPath = path.join(srcDir, relativePath); // Copy since we could be injecting configuration if(entry.relativePath === this.configPath) { fsExtra.copySync(srcPath, outputPath); return; } instrumentation.linked++; if (isChange) { fs.unlinkSync(outputPath); } symlinkOrCopySync(srcPath, outputPath); if(this.buildCount > 0) { this.builder.invalidate(toFileURL(outputPath)); // also invalidate any plugin syntax cases this.builder.invalidate(toFileURL(outputPath) + '!*'); } }; module.exports = SystemJSBuilder;
from django.db import models class CompanyIndustries(models.Model): name = models.CharField(max_length=50, verbose_name="行业名称") add_time = models.DateTimeField(verbose_name="新增时间") update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间") is_effective = models.BooleanField(default=True, verbose_name="是否有效") class Meta: app_label = 'position' managed = True db_table = 'position_company_industries' verbose_name = '公司所属行业' verbose_name_plural = verbose_name def __str__(self): return self.name
from flask import Blueprint public = Blueprint('public', __name__) from . import public_endpoints
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/localization/en/MathML.js * * Copyright (c) 2009-2013 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Localization.addTranslation("en","MathML",{ version: "2.3", isLoaded: true, strings: { BadMglyph: "Bad mglyph: %1", BadMglyphFont: "Bad font: %1", MathPlayer: "MathJax was not able to set up MathPlayer.\n\nIf MathPlayer is not installed, you need to install it first.\nOtherwise, your security settings may be preventing ActiveX \ncontrols from running. Use the Internet Options item under\nthe Tools menu and select the Security tab, then press the\nCustom Level button. Check that the settings for\n'Run ActiveX Controls', and 'Binary and script behaviors'\nare enabled.\n\nCurrently you will see error messages rather than\ntypeset mathematics.", CantCreateXMLParser: "MathJax can't create an XML parser for MathML. Check that\nthe 'Script ActiveX controls marked safe for scripting' security\nsetting is enabled (use the Internet Options item in the Tools\nmenu, and select the Security panel, then press the Custom Level\nbutton to check this).\n\nMathML equations will not be able to be processed by MathJax.", UnknownNodeType: "Unknown node type: %1", UnexpectedTextNode: "Unexpected text node: %1", ErrorParsingMathML: "Error parsing MathML", ParsingError: "Error parsing MathML: %1", MathMLSingleElement: "MathML must be formed by a single element", MathMLRootElement: "MathML must be formed by a \u003Cmath\u003E element, not %1" } }); MathJax.Ajax.loadComplete("[MathJax]/localization/en/MathML.js");
/*! * Copyright 2015 Drifty Co. * http://drifty.com/ * * Ionic, v1.2.4 * A powerful HTML5 mobile app framework. * http://ionicframework.com/ * * By @maxlynch, @benjsperry, @adamdbradley <3 * * Licensed under the MIT license. Please see LICENSE for more information. * */ (function() { // Create global ionic obj and its namespaces // build processes may have already created an ionic obj window.ionic = window.ionic || {}; window.ionic.views = {}; window.ionic.version = '1.2.4'; (function (ionic) { ionic.DelegateService = function(methodNames) { if (methodNames.indexOf('$getByHandle') > -1) { throw new Error("Method '$getByHandle' is implicitly added to each delegate service. Do not list it as a method."); } function trueFn() { return true; } return ['$log', function($log) { /* * Creates a new object that will have all the methodNames given, * and call them on the given the controller instance matching given * handle. * The reason we don't just let $getByHandle return the controller instance * itself is that the controller instance might not exist yet. * * We want people to be able to do * `var instance = $ionicScrollDelegate.$getByHandle('foo')` on controller * instantiation, but on controller instantiation a child directive * may not have been compiled yet! * * So this is our way of solving this problem: we create an object * that will only try to fetch the controller with given handle * once the methods are actually called. */ function DelegateInstance(instances, handle) { this._instances = instances; this.handle = handle; } methodNames.forEach(function(methodName) { DelegateInstance.prototype[methodName] = instanceMethodCaller(methodName); }); /** * The delegate service (eg $ionicNavBarDelegate) is just an instance * with a non-defined handle, a couple extra methods for registering * and narrowing down to a specific handle. */ function DelegateService() { this._instances = []; } DelegateService.prototype = DelegateInstance.prototype; DelegateService.prototype._registerInstance = function(instance, handle, filterFn) { var instances = this._instances; instance.$$delegateHandle = handle; instance.$$filterFn = filterFn || trueFn; instances.push(instance); return function deregister() { var index = instances.indexOf(instance); if (index !== -1) { instances.splice(index, 1); } }; }; DelegateService.prototype.$getByHandle = function(handle) { return new DelegateInstance(this._instances, handle); }; return new DelegateService(); function instanceMethodCaller(methodName) { return function caller() { var handle = this.handle; var args = arguments; var foundInstancesCount = 0; var returnValue; this._instances.forEach(function(instance) { if ((!handle || handle == instance.$$delegateHandle) && instance.$$filterFn(instance)) { foundInstancesCount++; var ret = instance[methodName].apply(instance, args); //Only return the value from the first call if (foundInstancesCount === 1) { returnValue = ret; } } }); if (!foundInstancesCount && handle) { return $log.warn( 'Delegate for handle "' + handle + '" could not find a ' + 'corresponding element with delegate-handle="' + handle + '"! ' + methodName + '() was not called!\n' + 'Possible cause: If you are calling ' + methodName + '() immediately, and ' + 'your element with delegate-handle="' + handle + '" is a child of your ' + 'controller, then your element may not be compiled yet. Put a $timeout ' + 'around your call to ' + methodName + '() and try again.' ); } return returnValue; }; } }]; }; })(window.ionic); (function(window, document, ionic) { var readyCallbacks = []; var isDomReady = document.readyState === 'complete' || document.readyState === 'interactive'; function domReady() { isDomReady = true; for (var x = 0; x < readyCallbacks.length; x++) { ionic.requestAnimationFrame(readyCallbacks[x]); } readyCallbacks = []; document.removeEventListener('DOMContentLoaded', domReady); } if (!isDomReady) { document.addEventListener('DOMContentLoaded', domReady); } // From the man himself, Mr. Paul Irish. // The requestAnimationFrame polyfill // Put it on window just to preserve its context // without having to use .call window._rAF = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 16); }; })(); var cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelRequestAnimationFrame; /** * @ngdoc utility * @name ionic.DomUtil * @module ionic */ ionic.DomUtil = { //Call with proper context /** * @ngdoc method * @name ionic.DomUtil#requestAnimationFrame * @alias ionic.requestAnimationFrame * @description Calls [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame), or a polyfill if not available. * @param {function} callback The function to call when the next frame * happens. */ requestAnimationFrame: function(cb) { return window._rAF(cb); }, cancelAnimationFrame: function(requestId) { cancelAnimationFrame(requestId); }, /** * @ngdoc method * @name ionic.DomUtil#animationFrameThrottle * @alias ionic.animationFrameThrottle * @description * When given a callback, if that callback is called 100 times between * animation frames, adding Throttle will make it only run the last of * the 100 calls. * * @param {function} callback a function which will be throttled to * requestAnimationFrame * @returns {function} A function which will then call the passed in callback. * The passed in callback will receive the context the returned function is * called with. */ animationFrameThrottle: function(cb) { var args, isQueued, context; return function() { args = arguments; context = this; if (!isQueued) { isQueued = true; ionic.requestAnimationFrame(function() { cb.apply(context, args); isQueued = false; }); } }; }, contains: function(parentNode, otherNode) { var current = otherNode; while (current) { if (current === parentNode) return true; current = current.parentNode; } }, /** * @ngdoc method * @name ionic.DomUtil#getPositionInParent * @description * Find an element's scroll offset within its container. * @param {DOMElement} element The element to find the offset of. * @returns {object} A position object with the following properties: * - `{number}` `left` The left offset of the element. * - `{number}` `top` The top offset of the element. */ getPositionInParent: function(el) { return { left: el.offsetLeft, top: el.offsetTop }; }, getOffsetTop: function(el) { var curtop = 0; if (el.offsetParent) { do { curtop += el.offsetTop; el = el.offsetParent; } while (el) return curtop; } }, /** * @ngdoc method * @name ionic.DomUtil#ready * @description * Call a function when the DOM is ready, or if it is already ready * call the function immediately. * @param {function} callback The function to be called. */ ready: function(cb) { if (isDomReady) { ionic.requestAnimationFrame(cb); } else { readyCallbacks.push(cb); } }, /** * @ngdoc method * @name ionic.DomUtil#getTextBounds * @description * Get a rect representing the bounds of the given textNode. * @param {DOMElement} textNode The textNode to find the bounds of. * @returns {object} An object representing the bounds of the node. Properties: * - `{number}` `left` The left position of the textNode. * - `{number}` `right` The right position of the textNode. * - `{number}` `top` The top position of the textNode. * - `{number}` `bottom` The bottom position of the textNode. * - `{number}` `width` The width of the textNode. * - `{number}` `height` The height of the textNode. */ getTextBounds: function(textNode) { if (document.createRange) { var range = document.createRange(); range.selectNodeContents(textNode); if (range.getBoundingClientRect) { var rect = range.getBoundingClientRect(); if (rect) { var sx = window.scrollX; var sy = window.scrollY; return { top: rect.top + sy, left: rect.left + sx, right: rect.left + sx + rect.width, bottom: rect.top + sy + rect.height, width: rect.width, height: rect.height }; } } } return null; }, /** * @ngdoc method * @name ionic.DomUtil#getChildIndex * @description * Get the first index of a child node within the given element of the * specified type. * @param {DOMElement} element The element to find the index of. * @param {string} type The nodeName to match children of element against. * @returns {number} The index, or -1, of a child with nodeName matching type. */ getChildIndex: function(element, type) { if (type) { var ch = element.parentNode.children; var c; for (var i = 0, k = 0, j = ch.length; i < j; i++) { c = ch[i]; if (c.nodeName && c.nodeName.toLowerCase() == type) { if (c == element) { return k; } k++; } } } return Array.prototype.slice.call(element.parentNode.children).indexOf(element); }, /** * @private */ swapNodes: function(src, dest) { dest.parentNode.insertBefore(src, dest); }, elementIsDescendant: function(el, parent, stopAt) { var current = el; do { if (current === parent) return true; current = current.parentNode; } while (current && current !== stopAt); return false; }, /** * @ngdoc method * @name ionic.DomUtil#getParentWithClass * @param {DOMElement} element * @param {string} className * @returns {DOMElement} The closest parent of element matching the * className, or null. */ getParentWithClass: function(e, className, depth) { depth = depth || 10; while (e.parentNode && depth--) { if (e.parentNode.classList && e.parentNode.classList.contains(className)) { return e.parentNode; } e = e.parentNode; } return null; }, /** * @ngdoc method * @name ionic.DomUtil#getParentOrSelfWithClass * @param {DOMElement} element * @param {string} className * @returns {DOMElement} The closest parent or self matching the * className, or null. */ getParentOrSelfWithClass: function(e, className, depth) { depth = depth || 10; while (e && depth--) { if (e.classList && e.classList.contains(className)) { return e; } e = e.parentNode; } return null; }, /** * @ngdoc method * @name ionic.DomUtil#rectContains * @param {number} x * @param {number} y * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @returns {boolean} Whether {x,y} fits within the rectangle defined by * {x1,y1,x2,y2}. */ rectContains: function(x, y, x1, y1, x2, y2) { if (x < x1 || x > x2) return false; if (y < y1 || y > y2) return false; return true; }, /** * @ngdoc method * @name ionic.DomUtil#blurAll * @description * Blurs any currently focused input element * @returns {DOMElement} The element blurred or null */ blurAll: function() { if (document.activeElement && document.activeElement != document.body) { document.activeElement.blur(); return document.activeElement; } return null; }, cachedAttr: function(ele, key, value) { ele = ele && ele.length && ele[0] || ele; if (ele && ele.setAttribute) { var dataKey = '$attr-' + key; if (arguments.length > 2) { if (ele[dataKey] !== value) { ele.setAttribute(key, value); ele[dataKey] = value; } } else if (typeof ele[dataKey] == 'undefined') { ele[dataKey] = ele.getAttribute(key); } return ele[dataKey]; } }, cachedStyles: function(ele, styles) { ele = ele && ele.length && ele[0] || ele; if (ele && ele.style) { for (var prop in styles) { if (ele['$style-' + prop] !== styles[prop]) { ele.style[prop] = ele['$style-' + prop] = styles[prop]; } } } } }; //Shortcuts ionic.requestAnimationFrame = ionic.DomUtil.requestAnimationFrame; ionic.cancelAnimationFrame = ionic.DomUtil.cancelAnimationFrame; ionic.animationFrameThrottle = ionic.DomUtil.animationFrameThrottle; })(window, document, ionic); /** * ion-events.js * * Author: Max Lynch <max@drifty.com> * * Framework events handles various mobile browser events, and * detects special events like tap/swipe/etc. and emits them * as custom events that can be used in an app. * * Portions lovingly adapted from github.com/maker/ratchet and github.com/alexgibson/tap.js - thanks guys! */ (function(ionic) { // Custom event polyfill ionic.CustomEvent = (function() { if( typeof window.CustomEvent === 'function' ) return CustomEvent; var customEvent = function(event, params) { var evt; params = params || { bubbles: false, cancelable: false, detail: undefined }; try { evt = document.createEvent("CustomEvent"); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); } catch (error) { // fallback for browsers that don't support createEvent('CustomEvent') evt = document.createEvent("Event"); for (var param in params) { evt[param] = params[param]; } evt.initEvent(event, params.bubbles, params.cancelable); } return evt; }; customEvent.prototype = window.Event.prototype; return customEvent; })(); /** * @ngdoc utility * @name ionic.EventController * @module ionic */ ionic.EventController = { VIRTUALIZED_EVENTS: ['tap', 'swipe', 'swiperight', 'swipeleft', 'drag', 'hold', 'release'], /** * @ngdoc method * @name ionic.EventController#trigger * @alias ionic.trigger * @param {string} eventType The event to trigger. * @param {object} data The data for the event. Hint: pass in * `{target: targetElement}` * @param {boolean=} bubbles Whether the event should bubble up the DOM. * @param {boolean=} cancelable Whether the event should be cancelable. */ // Trigger a new event trigger: function(eventType, data, bubbles, cancelable) { var event = new ionic.CustomEvent(eventType, { detail: data, bubbles: !!bubbles, cancelable: !!cancelable }); // Make sure to trigger the event on the given target, or dispatch it from // the window if we don't have an event target data && data.target && data.target.dispatchEvent && data.target.dispatchEvent(event) || window.dispatchEvent(event); }, /** * @ngdoc method * @name ionic.EventController#on * @alias ionic.on * @description Listen to an event on an element. * @param {string} type The event to listen for. * @param {function} callback The listener to be called. * @param {DOMElement} element The element to listen for the event on. */ on: function(type, callback, element) { var e = element || window; // Bind a gesture if it's a virtual event for(var i = 0, j = this.VIRTUALIZED_EVENTS.length; i < j; i++) { if(type == this.VIRTUALIZED_EVENTS[i]) { var gesture = new ionic.Gesture(element); gesture.on(type, callback); return gesture; } } // Otherwise bind a normal event e.addEventListener(type, callback); }, /** * @ngdoc method * @name ionic.EventController#off * @alias ionic.off * @description Remove an event listener. * @param {string} type * @param {function} callback * @param {DOMElement} element */ off: function(type, callback, element) { element.removeEventListener(type, callback); }, /** * @ngdoc method * @name ionic.EventController#onGesture * @alias ionic.onGesture * @description Add an event listener for a gesture on an element. * * Available eventTypes (from [hammer.js](http://eightmedia.github.io/hammer.js/)): * * `hold`, `tap`, `doubletap`, `drag`, `dragstart`, `dragend`, `dragup`, `dragdown`, <br/> * `dragleft`, `dragright`, `swipe`, `swipeup`, `swipedown`, `swipeleft`, `swiperight`, <br/> * `transform`, `transformstart`, `transformend`, `rotate`, `pinch`, `pinchin`, `pinchout`, </br> * `touch`, `release` * * @param {string} eventType The gesture event to listen for. * @param {function(e)} callback The function to call when the gesture * happens. * @param {DOMElement} element The angular element to listen for the event on. * @param {object} options object. * @returns {ionic.Gesture} The gesture object (use this to remove the gesture later on). */ onGesture: function(type, callback, element, options) { var gesture = new ionic.Gesture(element, options); gesture.on(type, callback); return gesture; }, /** * @ngdoc method * @name ionic.EventController#offGesture * @alias ionic.offGesture * @description Remove an event listener for a gesture created on an element. * @param {ionic.Gesture} gesture The gesture that should be removed. * @param {string} eventType The gesture event to remove the listener for. * @param {function(e)} callback The listener to remove. */ offGesture: function(gesture, type, callback) { gesture && gesture.off(type, callback); }, handlePopState: function() {} }; // Map some convenient top-level functions for event handling ionic.on = function() { ionic.EventController.on.apply(ionic.EventController, arguments); }; ionic.off = function() { ionic.EventController.off.apply(ionic.EventController, arguments); }; ionic.trigger = ionic.EventController.trigger;//function() { ionic.EventController.trigger.apply(ionic.EventController.trigger, arguments); }; ionic.onGesture = function() { return ionic.EventController.onGesture.apply(ionic.EventController.onGesture, arguments); }; ionic.offGesture = function() { return ionic.EventController.offGesture.apply(ionic.EventController.offGesture, arguments); }; })(window.ionic); /* eslint camelcase:0 */ /** * Simple gesture controllers with some common gestures that emit * gesture events. * * Ported from github.com/EightMedia/hammer.js Gestures - thanks! */ (function(ionic) { /** * ionic.Gestures * use this to create instances * @param {HTMLElement} element * @param {Object} options * @returns {ionic.Gestures.Instance} * @constructor */ ionic.Gesture = function(element, options) { return new ionic.Gestures.Instance(element, options || {}); }; ionic.Gestures = {}; // default settings ionic.Gestures.defaults = { // add css to the element to prevent the browser from doing // its native behavior. this doesnt prevent the scrolling, // but cancels the contextmenu, tap highlighting etc // set to false to disable this stop_browser_behavior: 'disable-user-behavior' }; // detect touchevents ionic.Gestures.HAS_POINTEREVENTS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled; ionic.Gestures.HAS_TOUCHEVENTS = ('ontouchstart' in window); // dont use mouseevents on mobile devices ionic.Gestures.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android|silk/i; ionic.Gestures.NO_MOUSEEVENTS = ionic.Gestures.HAS_TOUCHEVENTS && window.navigator.userAgent.match(ionic.Gestures.MOBILE_REGEX); // eventtypes per touchevent (start, move, end) // are filled by ionic.Gestures.event.determineEventTypes on setup ionic.Gestures.EVENT_TYPES = {}; // direction defines ionic.Gestures.DIRECTION_DOWN = 'down'; ionic.Gestures.DIRECTION_LEFT = 'left'; ionic.Gestures.DIRECTION_UP = 'up'; ionic.Gestures.DIRECTION_RIGHT = 'right'; // pointer type ionic.Gestures.POINTER_MOUSE = 'mouse'; ionic.Gestures.POINTER_TOUCH = 'touch'; ionic.Gestures.POINTER_PEN = 'pen'; // touch event defines ionic.Gestures.EVENT_START = 'start'; ionic.Gestures.EVENT_MOVE = 'move'; ionic.Gestures.EVENT_END = 'end'; // hammer document where the base events are added at ionic.Gestures.DOCUMENT = window.document; // plugins namespace ionic.Gestures.plugins = {}; // if the window events are set... ionic.Gestures.READY = false; /** * setup events to detect gestures on the document */ function setup() { if(ionic.Gestures.READY) { return; } // find what eventtypes we add listeners to ionic.Gestures.event.determineEventTypes(); // Register all gestures inside ionic.Gestures.gestures for(var name in ionic.Gestures.gestures) { if(ionic.Gestures.gestures.hasOwnProperty(name)) { ionic.Gestures.detection.register(ionic.Gestures.gestures[name]); } } // Add touch events on the document ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_MOVE, ionic.Gestures.detection.detect); ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_END, ionic.Gestures.detection.detect); // ionic.Gestures is ready...! ionic.Gestures.READY = true; } /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * @param {HTMLElement} element * @param {Object} [options={}] * @returns {ionic.Gestures.Instance} * @name Gesture.Instance * @constructor */ ionic.Gestures.Instance = function(element, options) { var self = this; // A null element was passed into the instance, which means // whatever lookup was done to find this element failed to find it // so we can't listen for events on it. if(element === null) { console.error('Null element passed to gesture (element does not exist). Not listening for gesture'); return this; } // setup ionic.GesturesJS window events and register all gestures // this also sets up the default options setup(); this.element = element; // start/stop detection option this.enabled = true; // merge options this.options = ionic.Gestures.utils.extend( ionic.Gestures.utils.extend({}, ionic.Gestures.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.stop_browser_behavior) { ionic.Gestures.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior); } // start detection on touchstart ionic.Gestures.event.onTouch(element, ionic.Gestures.EVENT_START, function(ev) { if(self.enabled) { ionic.Gestures.detection.startDetect(self, ev); } }); // return instance return this; }; ionic.Gestures.Instance.prototype = { /** * bind events to the instance * @param {String} gesture * @param {Function} handler * @returns {ionic.Gestures.Instance} */ on: function onEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t = 0; t < gestures.length; t++) { this.element.addEventListener(gestures[t], handler, false); } return this; }, /** * unbind events to the instance * @param {String} gesture * @param {Function} handler * @returns {ionic.Gestures.Instance} */ off: function offEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t = 0; t < gestures.length; t++) { this.element.removeEventListener(gestures[t], handler, false); } return this; }, /** * trigger gesture event * @param {String} gesture * @param {Object} eventData * @returns {ionic.Gestures.Instance} */ trigger: function triggerEvent(gesture, eventData){ // create DOM event var event = ionic.Gestures.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(ionic.Gestures.utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @param {Boolean} state * @returns {ionic.Gestures.Instance} */ enable: function enable(state) { this.enabled = state; return this; } }; /** * this holds the last move event, * used to fix empty touchend issue * see the onTouch event for an explanation * type {Object} */ var last_move_event = null; /** * when the mouse is hold down, this is true * type {Boolean} */ var enable_detect = false; /** * when touch events have been fired, this is true * type {Boolean} */ var touch_triggered = false; ionic.Gestures.event = { /** * simple addEventListener * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ bindDom: function(element, type, handler) { var types = type.split(' '); for(var t = 0; t < types.length; t++) { element.addEventListener(types[t], handler, false); } }, /** * touch events with mouse fallback * @param {HTMLElement} element * @param {String} eventType like ionic.Gestures.EVENT_MOVE * @param {Function} handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; this.bindDom(element, ionic.Gestures.EVENT_TYPES[eventType], function bindDomOnTouch(ev) { var sourceEventType = ev.type.toLowerCase(); // onmouseup, but when touchend has been fired we do nothing. // this is for touchdevices which also fire a mouseup on touchend if(sourceEventType.match(/mouse/) && touch_triggered) { return; } // mousebutton must be down or a touch event else if( sourceEventType.match(/touch/) || // touch events are always on screen sourceEventType.match(/pointerdown/) || // pointerevents touch (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed ){ enable_detect = true; } // mouse isn't pressed else if(sourceEventType.match(/mouse/) && ev.which !== 1) { enable_detect = false; } // we are in a touch event, set the touch triggered bool to true, // this for the conflicts that may occur on ios and android if(sourceEventType.match(/touch|pointer/)) { touch_triggered = true; } // count the total touches on the screen var count_touches = 0; // when touch has been triggered in this detection session // and we are now handling a mouse event, we stop that to prevent conflicts if(enable_detect) { // update pointerevent if(ionic.Gestures.HAS_POINTEREVENTS && eventType != ionic.Gestures.EVENT_END) { count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev); } // touch else if(sourceEventType.match(/touch/)) { count_touches = ev.touches.length; } // mouse else if(!touch_triggered) { count_touches = sourceEventType.match(/up/) ? 0 : 1; } // if we are in a end event, but when we remove one touch and // we still have enough, set eventType to move if(count_touches > 0 && eventType == ionic.Gestures.EVENT_END) { eventType = ionic.Gestures.EVENT_MOVE; } // no touches, force the end event else if(!count_touches) { eventType = ionic.Gestures.EVENT_END; } // store the last move event if(count_touches || last_move_event === null) { last_move_event = ev; } // trigger the handler handler.call(ionic.Gestures.detection, self.collectEventData(element, eventType, self.getTouchList(last_move_event, eventType), ev)); // remove pointerevent from list if(ionic.Gestures.HAS_POINTEREVENTS && eventType == ionic.Gestures.EVENT_END) { count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev); } } //debug(sourceEventType +" "+ eventType); // on the end we reset everything if(!count_touches) { last_move_event = null; enable_detect = false; touch_triggered = false; ionic.Gestures.PointerEvent.reset(); } }); }, /** * we have different events for each device/browser * determine what we need and set them in the ionic.Gestures.EVENT_TYPES constant */ determineEventTypes: function determineEventTypes() { // determine the eventtype we want to set var types; // pointerEvents magic if(ionic.Gestures.HAS_POINTEREVENTS) { types = ionic.Gestures.PointerEvent.getEvents(); } // on Android, iOS, blackberry, windows mobile we dont want any mouseevents else if(ionic.Gestures.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel']; } // for non pointer events browsers and mixed browsers, // like chrome on windows8 touch laptop else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup']; } ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_START] = types[0]; ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_MOVE] = types[1]; ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_END] = types[2]; }, /** * create touchlist depending on the event * @param {Object} ev * @param {String} eventType used by the fakemultitouch plugin */ getTouchList: function getTouchList(ev/*, eventType*/) { // get the fake pointerEvent touchlist if(ionic.Gestures.HAS_POINTEREVENTS) { return ionic.Gestures.PointerEvent.getTouchList(); } // get the touchlist else if(ev.touches) { return ev.touches; } // make fake touchlist from mouse position else { ev.identifier = 1; return [ev]; } }, /** * collect event data for ionic.Gestures js * @param {HTMLElement} element * @param {String} eventType like ionic.Gestures.EVENT_MOVE * @param {Object} eventData */ collectEventData: function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = ionic.Gestures.POINTER_TOUCH; if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) { pointerType = ionic.Gestures.POINTER_MOUSE; } return { center: ionic.Gestures.utils.getCenter(touches), timeStamp: new Date().getTime(), target: ev.target, touches: touches, eventType: eventType, pointerType: pointerType, srcEvent: ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { if(this.srcEvent.preventManipulation) { this.srcEvent.preventManipulation(); } if(this.srcEvent.preventDefault) { // this.srcEvent.preventDefault(); } }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return ionic.Gestures.detection.stopDetect(); } }; } }; ionic.Gestures.PointerEvent = { /** * holds all pointers * type {Object} */ pointers: {}, /** * get a list of pointers * @returns {Array} touchlist */ getTouchList: function() { var self = this; var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Object.keys(self.pointers).sort().forEach(function(id) { touchlist.push(self.pointers[id]); }); return touchlist; }, /** * update the position of a pointer * @param {String} type ionic.Gestures.EVENT_END * @param {Object} pointerEvent */ updatePointer: function(type, pointerEvent) { if(type == ionic.Gestures.EVENT_END) { this.pointers = {}; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } return Object.keys(this.pointers).length; }, /** * check if ev matches pointertype * @param {String} pointerType ionic.Gestures.POINTER_MOUSE * @param {PointerEvent} ev */ matchType: function(pointerType, ev) { if(!ev.pointerType) { return false; } var types = {}; types[ionic.Gestures.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == ionic.Gestures.POINTER_MOUSE); types[ionic.Gestures.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == ionic.Gestures.POINTER_TOUCH); types[ionic.Gestures.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == ionic.Gestures.POINTER_PEN); return types[pointerType]; }, /** * get events */ getEvents: function() { return [ 'pointerdown MSPointerDown', 'pointermove MSPointerMove', 'pointerup pointercancel MSPointerUp MSPointerCancel' ]; }, /** * reset the list */ reset: function() { this.pointers = {}; } }; ionic.Gestures.utils = { /** * extend method, * also used for cloning when dest is an empty object * @param {Object} dest * @param {Object} src * @param {Boolean} merge do a merge * @returns {Object} dest */ extend: function extend(dest, src, merge) { for (var key in src) { if(dest[key] !== undefined && merge) { continue; } dest[key] = src[key]; } return dest; }, /** * find if a node is in the given parent * used for event delegation tricks * @param {HTMLElement} node * @param {HTMLElement} parent * @returns {boolean} has_parent */ hasParent: function(node, parent) { while(node){ if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @param {Array} touches * @returns {Object} center */ getCenter: function getCenter(touches) { var valuesX = [], valuesY = []; for(var t = 0, len = touches.length; t < len; t++) { valuesX.push(touches[t].pageX); valuesY.push(touches[t].pageY); } return { pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2), pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2) }; }, /** * calculate the velocity between two points * @param {Number} delta_time * @param {Number} delta_x * @param {Number} delta_y * @returns {Object} velocity */ getVelocity: function getVelocity(delta_time, delta_x, delta_y) { return { x: Math.abs(delta_x / delta_time) || 0, y: Math.abs(delta_y / delta_time) || 0 }; }, /** * calculate the angle between two coordinates * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} angle */ getAngle: function getAngle(touch1, touch2) { var y = touch2.pageY - touch1.pageY, x = touch2.pageX - touch1.pageX; return Math.atan2(y, x) * 180 / Math.PI; }, /** * angle to direction define * @param {Touch} touch1 * @param {Touch} touch2 * @returns {String} direction constant, like ionic.Gestures.DIRECTION_LEFT */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.pageX - touch2.pageX), y = Math.abs(touch1.pageY - touch2.pageY); if(x >= y) { return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } else { return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } }, /** * calculate the distance between two touches * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.pageX - touch1.pageX, y = touch2.pageY - touch1.pageY; return Math.sqrt((x * x) + (y * y)); }, /** * calculate the scale factor between two touchLists (fingers) * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start * @param {Array} end * @returns {Number} scale */ getScale: function getScale(start, end) { // need two fingers... if(start.length >= 2 && end.length >= 2) { return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]); } return 1; }, /** * calculate the rotation degrees between two touchLists (fingers) * @param {Array} start * @param {Array} end * @returns {Number} rotation */ getRotation: function getRotation(start, end) { // need two fingers if(start.length >= 2 && end.length >= 2) { return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]); } return 0; }, /** * boolean if the direction is vertical * @param {String} direction * @returns {Boolean} is_vertical */ isVertical: function isVertical(direction) { return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN); }, /** * stop browser default behavior with css class * @param {HtmlElement} element * @param {Object} css_class */ stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_class) { // changed from making many style changes to just adding a preset classname // less DOM manipulations, less code, and easier to control in the CSS side of things // hammer.js doesn't come with CSS, but ionic does, which is why we prefer this method if(element && element.classList) { element.classList.add(css_class); element.onselectstart = function() { return false; }; } } }; ionic.Gestures.detection = { // contains all registred ionic.Gestures.gestures in the correct order gestures: [], // data of the current ionic.Gestures.gesture detection session current: null, // the previous ionic.Gestures.gesture session data // is a full clone of the previous gesture.current object previous: null, // when this becomes true, no gestures are fired stopped: false, /** * start ionic.Gestures.gesture detection * @param {ionic.Gestures.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a ionic.Gestures.gesture detection on an element if(this.current) { return; } this.stopped = false; this.current = { inst: inst, // reference to ionic.GesturesInstance we're working for startEvent: ionic.Gestures.utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent: false, // last eventData name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * ionic.Gestures.gesture detection * @param {Object} eventData */ detect: function detect(eventData) { if(!this.current || this.stopped) { return null; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // instance options var inst_options = this.current.inst.options; // call ionic.Gestures.gesture handlers for(var g = 0, len = this.gestures.length; g < len; g++) { var gesture = this.gestures[g]; // only when the instance options have enabled this gesture if(!this.stopped && inst_options[gesture.name] !== false) { // if a handler returns false, we stop with the detection if(gesture.handler.call(gesture, eventData, this.current.inst) === false) { this.stopDetect(); break; } } } // store as previous event event if(this.current) { this.current.lastEvent = eventData; } // endevent, but not the last touch, so dont stop if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length - 1) { this.stopDetect(); } return eventData; }, /** * clear the ionic.Gestures.gesture vars * this is called on endDetect, but can also be used when a final ionic.Gestures.gesture has been detected * to stop other ionic.Gestures.gestures from being fired */ stopDetect: function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = ionic.Gestures.utils.extend({}, this.current); // reset the current this.current = null; // stopped! this.stopped = true; }, /** * extend eventData for ionic.Gestures.gestures * @param {Object} ev * @returns {Object} ev */ extendEventData: function extendEventData(ev) { var startEv = this.current.startEvent; // if the touches change, set the new touches over the startEvent touches // this because touchevents don't have all the touches on touchstart, or the // user must place his fingers at the EXACT same time on the screen, which is not realistic // but, sometimes it happens that both fingers are touching at the EXACT same time if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) { // extend 1 level deep to get the touchlist with the touch objects startEv.touches = []; for(var i = 0, len = ev.touches.length; i < len; i++) { startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i])); } } var delta_time = ev.timeStamp - startEv.timeStamp, delta_x = ev.center.pageX - startEv.center.pageX, delta_y = ev.center.pageY - startEv.center.pageY, velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y); ionic.Gestures.utils.extend(ev, { deltaTime: delta_time, deltaX: delta_x, deltaY: delta_y, velocityX: velocity.x, velocityY: velocity.y, distance: ionic.Gestures.utils.getDistance(startEv.center, ev.center), angle: ionic.Gestures.utils.getAngle(startEv.center, ev.center), direction: ionic.Gestures.utils.getDirection(startEv.center, ev.center), scale: ionic.Gestures.utils.getScale(startEv.touches, ev.touches), rotation: ionic.Gestures.utils.getRotation(startEv.touches, ev.touches), startEvent: startEv }); return ev; }, /** * register new gesture * @param {Object} gesture object, see gestures.js for documentation * @returns {Array} gestures */ register: function register(gesture) { // add an enable gesture options if there is no given var options = gesture.defaults || {}; if(options[gesture.name] === undefined) { options[gesture.name] = true; } // extend ionic.Gestures default options with the ionic.Gestures.gesture options ionic.Gestures.utils.extend(ionic.Gestures.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add ionic.Gestures.gesture to the list this.gestures.push(gesture); // sort the list by index this.gestures.sort(function(a, b) { if (a.index < b.index) { return -1; } if (a.index > b.index) { return 1; } return 0; }); return this.gestures; } }; ionic.Gestures.gestures = ionic.Gestures.gestures || {}; /** * Custom gestures * ============================== * * Gesture object * -------------------- * The object structure of a gesture: * * { name: 'mygesture', * index: 1337, * defaults: { * mygesture_option: true * } * handler: function(type, ev, inst) { * // trigger gesture event * inst.trigger(this.name, ev); * } * } * @param {String} name * this should be the name of the gesture, lowercase * it is also being used to disable/enable the gesture per instance config. * * @param {Number} [index=1000] * the index of the gesture, where it is going to be in the stack of gestures detection * like when you build an gesture that depends on the drag gesture, it is a good * idea to place it after the index of the drag gesture. * * @param {Object} [defaults={}] * the default settings of the gesture. these are added to the instance settings, * and can be overruled per instance. you can also add the name of the gesture, * but this is also added by default (and set to true). * * @param {Function} handler * this handles the gesture detection of your custom gesture and receives the * following arguments: * * @param {Object} eventData * event data containing the following properties: * timeStamp {Number} time the event occurred * target {HTMLElement} target element * touches {Array} touches (fingers, pointers, mouse) on the screen * pointerType {String} kind of pointer that was used. matches ionic.Gestures.POINTER_MOUSE|TOUCH * center {Object} center position of the touches. contains pageX and pageY * deltaTime {Number} the total time of the touches in the screen * deltaX {Number} the delta on x axis we haved moved * deltaY {Number} the delta on y axis we haved moved * velocityX {Number} the velocity on the x * velocityY {Number} the velocity on y * angle {Number} the angle we are moving * direction {String} the direction we are moving. matches ionic.Gestures.DIRECTION_UP|DOWN|LEFT|RIGHT * distance {Number} the distance we haved moved * scale {Number} scaling of the touches, needs 2 touches * rotation {Number} rotation of the touches, needs 2 touches * * eventType {String} matches ionic.Gestures.EVENT_START|MOVE|END * srcEvent {Object} the source event, like TouchStart or MouseDown * * startEvent {Object} contains the same properties as above, * but from the first touch. this is used to calculate * distances, deltaTime, scaling etc * * @param {ionic.Gestures.Instance} inst * the instance we are doing the detection for. you can get the options from * the inst.options object and trigger the gesture event by calling inst.trigger * * * Handle gestures * -------------------- * inside the handler you can get/set ionic.Gestures.detectionic.current. This is the current * detection sessionic. It has the following properties * @param {String} name * contains the name of the gesture we have detected. it has not a real function, * only to check in other gestures if something is detected. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can * check if the current gesture is 'drag' by accessing ionic.Gestures.detectionic.current.name * * readonly * @param {ionic.Gestures.Instance} inst * the instance we do the detection for * * readonly * @param {Object} startEvent * contains the properties of the first gesture detection in this sessionic. * Used for calculations about timing, distance, etc. * * readonly * @param {Object} lastEvent * contains all the properties of the last gesture detect in this sessionic. * * after the gesture detection session has been completed (user has released the screen) * the ionic.Gestures.detectionic.current object is copied into ionic.Gestures.detectionic.previous, * this is usefull for gestures like doubletap, where you need to know if the * previous gesture was a tap * * options that have been set by the instance can be received by calling inst.options * * You can trigger a gesture event by calling inst.trigger("mygesture", event). * The first param is the name of your gesture, the second the event argument * * * Register gestures * -------------------- * When an gesture is added to the ionic.Gestures.gestures object, it is auto registered * at the setup of the first ionic.Gestures instance. You can also call ionic.Gestures.detectionic.register * manually and pass your gesture object as a param * */ /** * Hold * Touch stays at the same place for x time * events hold */ ionic.Gestures.gestures.Hold = { name: 'hold', index: 10, defaults: { hold_timeout: 500, hold_threshold: 9 }, timer: null, handler: function holdGesture(ev, inst) { switch(ev.eventType) { case ionic.Gestures.EVENT_START: // clear any running timers clearTimeout(this.timer); // set the gesture so we can check in the timeout if it still is ionic.Gestures.detection.current.name = this.name; // set timer and if after the timeout it still is hold, // we trigger the hold event this.timer = setTimeout(function() { if(ionic.Gestures.detection.current.name == 'hold') { ionic.tap.cancelClick(); inst.trigger('hold', ev); } }, inst.options.hold_timeout); break; // when you move or end we clear the timer case ionic.Gestures.EVENT_MOVE: if(ev.distance > inst.options.hold_threshold) { clearTimeout(this.timer); } break; case ionic.Gestures.EVENT_END: clearTimeout(this.timer); break; } } }; /** * Tap/DoubleTap * Quick touch at a place or double at the same place * events tap, doubletap */ ionic.Gestures.gestures.Tap = { name: 'tap', index: 100, defaults: { tap_max_touchtime: 250, tap_max_distance: 10, tap_always: true, doubletap_distance: 20, doubletap_interval: 300 }, handler: function tapGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END && ev.srcEvent.type != 'touchcancel') { // previous gesture, for the double tap since these are two different gesture detections var prev = ionic.Gestures.detection.previous, did_doubletap = false; // when the touchtime is higher then the max touch time // or when the moving distance is too much if(ev.deltaTime > inst.options.tap_max_touchtime || ev.distance > inst.options.tap_max_distance) { return; } // check if double tap if(prev && prev.name == 'tap' && (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval && ev.distance < inst.options.doubletap_distance) { inst.trigger('doubletap', ev); did_doubletap = true; } // do a single tap if(!did_doubletap || inst.options.tap_always) { ionic.Gestures.detection.current.name = 'tap'; inst.trigger('tap', ev); } } } }; /** * Swipe * triggers swipe events when the end velocity is above the threshold * events swipe, swipeleft, swiperight, swipeup, swipedown */ ionic.Gestures.gestures.Swipe = { name: 'swipe', index: 40, defaults: { // set 0 for unlimited, but this can conflict with transform swipe_max_touches: 1, swipe_velocity: 0.4 }, handler: function swipeGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { // max touches if(inst.options.swipe_max_touches > 0 && ev.touches.length > inst.options.swipe_max_touches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > inst.options.swipe_velocity || ev.velocityY > inst.options.swipe_velocity) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * Drag * Move with x fingers (default 1) around on the page. Blocking the scrolling when * moving left and right is a good practice. When all the drag events are blocking * you disable scrolling on that area. * events drag, drapleft, dragright, dragup, dragdown */ ionic.Gestures.gestures.Drag = { name: 'drag', index: 50, defaults: { drag_min_distance: 10, // Set correct_for_drag_min_distance to true to make the starting point of the drag // be calculated from where the drag was triggered, not from where the touch started. // Useful to avoid a jerk-starting drag, which can make fine-adjustments // through dragging difficult, and be visually unappealing. correct_for_drag_min_distance: true, // set 0 for unlimited, but this can conflict with transform drag_max_touches: 1, // prevent default browser behavior when dragging occurs // be careful with it, it makes the element a blocking element // when you are using the drag gesture, it is a good practice to set this true drag_block_horizontal: true, drag_block_vertical: true, // drag_lock_to_axis keeps the drag gesture on the axis that it started on, // It disallows vertical directions if the initial direction was horizontal, and vice versa. drag_lock_to_axis: false, // drag lock only kicks in when distance > drag_lock_min_distance // This way, locking occurs only when the distance has become large enough to reliably determine the direction drag_lock_min_distance: 25, // prevent default if the gesture is going the given direction prevent_default_directions: [] }, triggered: false, handler: function dragGesture(ev, inst) { if (ev.srcEvent.type == 'touchstart' || ev.srcEvent.type == 'touchend') { this.preventedFirstMove = false; } else if (!this.preventedFirstMove && ev.srcEvent.type == 'touchmove') { // Prevent gestures that are not intended for this event handler from firing subsequent times if (inst.options.prevent_default_directions.length > 0 && inst.options.prevent_default_directions.indexOf(ev.direction) != -1) { ev.srcEvent.preventDefault(); } this.preventedFirstMove = true; } // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(ionic.Gestures.detection.current.name != this.name && this.triggered) { inst.trigger(this.name + 'end', ev); this.triggered = false; return; } // max touches if(inst.options.drag_max_touches > 0 && ev.touches.length > inst.options.drag_max_touches) { return; } switch(ev.eventType) { case ionic.Gestures.EVENT_START: this.triggered = false; break; case ionic.Gestures.EVENT_MOVE: // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.distance < inst.options.drag_min_distance && ionic.Gestures.detection.current.name != this.name) { return; } // we are dragging! if(ionic.Gestures.detection.current.name != this.name) { ionic.Gestures.detection.current.name = this.name; if (inst.options.correct_for_drag_min_distance) { // When a drag is triggered, set the event center to drag_min_distance pixels from the original event center. // Without this correction, the dragged distance would jumpstart at drag_min_distance pixels instead of at 0. // It might be useful to save the original start point somewhere var factor = Math.abs(inst.options.drag_min_distance / ev.distance); ionic.Gestures.detection.current.startEvent.center.pageX += ev.deltaX * factor; ionic.Gestures.detection.current.startEvent.center.pageY += ev.deltaY * factor; // recalculate event data using new start point ev = ionic.Gestures.detection.extendEventData(ev); } } // lock drag to axis? if(ionic.Gestures.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance <= ev.distance)) { ev.drag_locked_to_axis = true; } var last_direction = ionic.Gestures.detection.current.lastEvent.direction; if(ev.drag_locked_to_axis && last_direction !== ev.direction) { // keep direction on the axis that the drag gesture started on if(ionic.Gestures.utils.isVertical(last_direction)) { ev.direction = (ev.deltaY < 0) ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name + 'start', ev); this.triggered = true; } // trigger normal event inst.trigger(this.name, ev); // direction event, like dragdown inst.trigger(this.name + ev.direction, ev); // block the browser events if( (inst.options.drag_block_vertical && ionic.Gestures.utils.isVertical(ev.direction)) || (inst.options.drag_block_horizontal && !ionic.Gestures.utils.isVertical(ev.direction))) { ev.preventDefault(); } break; case ionic.Gestures.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name + 'end', ev); } this.triggered = false; break; } } }; /** * Transform * User want to scale or rotate with 2 fingers * events transform, pinch, pinchin, pinchout, rotate */ ionic.Gestures.gestures.Transform = { name: 'transform', index: 45, defaults: { // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 transform_min_scale: 0.01, // rotation in degrees transform_min_rotation: 1, // prevent default browser behavior when two touches are on the screen // but it makes the element a blocking element // when you are using the transform gesture, it is a good practice to set this true transform_always_block: false }, triggered: false, handler: function transformGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(ionic.Gestures.detection.current.name != this.name && this.triggered) { inst.trigger(this.name + 'end', ev); this.triggered = false; return; } // atleast multitouch if(ev.touches.length < 2) { return; } // prevent default when two fingers are on the screen if(inst.options.transform_always_block) { ev.preventDefault(); } switch(ev.eventType) { case ionic.Gestures.EVENT_START: this.triggered = false; break; case ionic.Gestures.EVENT_MOVE: var scale_threshold = Math.abs(1 - ev.scale); var rotation_threshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scale_threshold < inst.options.transform_min_scale && rotation_threshold < inst.options.transform_min_rotation) { return; } // we are transforming! ionic.Gestures.detection.current.name = this.name; // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name + 'start', ev); this.triggered = true; } inst.trigger(this.name, ev); // basic transform event // trigger rotate event if(rotation_threshold > inst.options.transform_min_rotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scale_threshold > inst.options.transform_min_scale) { inst.trigger('pinch', ev); inst.trigger('pinch' + ((ev.scale < 1) ? 'in' : 'out'), ev); } break; case ionic.Gestures.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name + 'end', ev); } this.triggered = false; break; } } }; /** * Touch * Called as first, tells the user has touched the screen * events touch */ ionic.Gestures.gestures.Touch = { name: 'touch', index: -Infinity, defaults: { // call preventDefault at touchstart, and makes the element blocking by // disabling the scrolling of the page, but it improves gestures like // transforming and dragging. // be careful with using this, it can be very annoying for users to be stuck // on the page prevent_default: false, // disable mouse events, so only touch (or pen!) input triggers events prevent_mouseevents: false }, handler: function touchGesture(ev, inst) { if(inst.options.prevent_mouseevents && ev.pointerType == ionic.Gestures.POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.prevent_default) { ev.preventDefault(); } if(ev.eventType == ionic.Gestures.EVENT_START) { inst.trigger(this.name, ev); } } }; /** * Release * Called as last, tells the user has released the screen * events release */ ionic.Gestures.gestures.Release = { name: 'release', index: Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { inst.trigger(this.name, ev); } } }; })(window.ionic); (function(window, document, ionic) { function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } var IOS = 'ios'; var ANDROID = 'android'; var WINDOWS_PHONE = 'windowsphone'; var EDGE = 'edge'; var CROSSWALK = 'crosswalk'; var requestAnimationFrame = ionic.requestAnimationFrame; /** * @ngdoc utility * @name ionic.Platform * @module ionic * @description * A set of utility methods that can be used to retrieve the device ready state and * various other information such as what kind of platform the app is currently installed on. * * @usage * ```js * angular.module('PlatformApp', ['ionic']) * .controller('PlatformCtrl', function($scope) { * * ionic.Platform.ready(function(){ * // will execute when device is ready, or immediately if the device is already ready. * }); * * var deviceInformation = ionic.Platform.device(); * * var isWebView = ionic.Platform.isWebView(); * var isIPad = ionic.Platform.isIPad(); * var isIOS = ionic.Platform.isIOS(); * var isAndroid = ionic.Platform.isAndroid(); * var isWindowsPhone = ionic.Platform.isWindowsPhone(); * * var currentPlatform = ionic.Platform.platform(); * var currentPlatformVersion = ionic.Platform.version(); * * ionic.Platform.exitApp(); // stops the app * }); * ``` */ var self = ionic.Platform = { // Put navigator on platform so it can be mocked and set // the browser does not allow window.navigator to be set navigator: window.navigator, /** * @ngdoc property * @name ionic.Platform#isReady * @returns {boolean} Whether the device is ready. */ isReady: false, /** * @ngdoc property * @name ionic.Platform#isFullScreen * @returns {boolean} Whether the device is fullscreen. */ isFullScreen: false, /** * @ngdoc property * @name ionic.Platform#platforms * @returns {Array(string)} An array of all platforms found. */ platforms: null, /** * @ngdoc property * @name ionic.Platform#grade * @returns {string} What grade the current platform is. */ grade: null, ua: navigator.userAgent, /** * @ngdoc method * @name ionic.Platform#ready * @description * Trigger a callback once the device is ready, or immediately * if the device is already ready. This method can be run from * anywhere and does not need to be wrapped by any additonal methods. * When the app is within a WebView (Cordova), it'll fire * the callback once the device is ready. If the app is within * a web browser, it'll fire the callback after `window.load`. * Please remember that Cordova features (Camera, FileSystem, etc) still * will not work in a web browser. * @param {function} callback The function to call. */ ready: function(cb) { // run through tasks to complete now that the device is ready if (self.isReady) { cb(); } else { // the platform isn't ready yet, add it to this array // which will be called once the platform is ready readyCallbacks.push(cb); } }, /** * @private */ detect: function() { self._checkPlatforms(); requestAnimationFrame(function() { // only add to the body class if we got platform info for (var i = 0; i < self.platforms.length; i++) { document.body.classList.add('platform-' + self.platforms[i]); } }); }, /** * @ngdoc method * @name ionic.Platform#setGrade * @description Set the grade of the device: 'a', 'b', or 'c'. 'a' is the best * (most css features enabled), 'c' is the worst. By default, sets the grade * depending on the current device. * @param {string} grade The new grade to set. */ setGrade: function(grade) { var oldGrade = self.grade; self.grade = grade; requestAnimationFrame(function() { if (oldGrade) { document.body.classList.remove('grade-' + oldGrade); } document.body.classList.add('grade-' + grade); }); }, /** * @ngdoc method * @name ionic.Platform#device * @description Return the current device (given by cordova). * @returns {object} The device object. */ device: function() { return window.device || {}; }, _checkPlatforms: function() { self.platforms = []; var grade = 'a'; if (self.isWebView()) { self.platforms.push('webview'); if (!(!window.cordova && !window.PhoneGap && !window.phonegap)) { self.platforms.push('cordova'); } else if (window.forge) { self.platforms.push('trigger'); } } else { self.platforms.push('browser'); } if (self.isIPad()) self.platforms.push('ipad'); var platform = self.platform(); if (platform) { self.platforms.push(platform); var version = self.version(); if (version) { var v = version.toString(); if (v.indexOf('.') > 0) { v = v.replace('.', '_'); } else { v += '_0'; } self.platforms.push(platform + v.split('_')[0]); self.platforms.push(platform + v); if (self.isAndroid() && version < 4.4) { grade = (version < 4 ? 'c' : 'b'); } else if (self.isWindowsPhone()) { grade = 'b'; } } } self.setGrade(grade); }, /** * @ngdoc method * @name ionic.Platform#isWebView * @returns {boolean} Check if we are running within a WebView (such as Cordova). */ isWebView: function() { return !(!window.cordova && !window.PhoneGap && !window.phonegap && !window.forge); }, /** * @ngdoc method * @name ionic.Platform#isIPad * @returns {boolean} Whether we are running on iPad. */ isIPad: function() { if (/iPad/i.test(self.navigator.platform)) { return true; } return /iPad/i.test(self.ua); }, /** * @ngdoc method * @name ionic.Platform#isIOS * @returns {boolean} Whether we are running on iOS. */ isIOS: function() { return self.is(IOS); }, /** * @ngdoc method * @name ionic.Platform#isAndroid * @returns {boolean} Whether we are running on Android. */ isAndroid: function() { return self.is(ANDROID); }, /** * @ngdoc method * @name ionic.Platform#isWindowsPhone * @returns {boolean} Whether we are running on Windows Phone. */ isWindowsPhone: function() { return self.is(WINDOWS_PHONE); }, /** * @ngdoc method * @name ionic.Platform#isEdge * @returns {boolean} Whether we are running on MS Edge/Windows 10 (inc. Phone) */ isEdge: function() { return self.is(EDGE); }, isCrosswalk: function() { return self.is(CROSSWALK); }, /** * @ngdoc method * @name ionic.Platform#platform * @returns {string} The name of the current platform. */ platform: function() { // singleton to get the platform name if (platformName === null) self.setPlatform(self.device().platform); return platformName; }, /** * @private */ setPlatform: function(n) { if (typeof n != 'undefined' && n !== null && n.length) { platformName = n.toLowerCase(); } else if (getParameterByName('ionicplatform')) { platformName = getParameterByName('ionicplatform'); } else if (self.ua.indexOf('Edge') > -1) { platformName = EDGE; } else if (self.ua.indexOf('Windows Phone') > -1) { platformName = WINDOWS_PHONE; } else if (self.ua.indexOf('Android') > 0) { platformName = ANDROID; } else if (/iPhone|iPad|iPod/.test(self.ua)) { platformName = IOS; } else { platformName = self.navigator.platform && navigator.platform.toLowerCase().split(' ')[0] || ''; } }, /** * @ngdoc method * @name ionic.Platform#version * @returns {number} The version of the current device platform. */ version: function() { // singleton to get the platform version if (platformVersion === null) self.setVersion(self.device().version); return platformVersion; }, /** * @private */ setVersion: function(v) { if (typeof v != 'undefined' && v !== null) { v = v.split('.'); v = parseFloat(v[0] + '.' + (v.length > 1 ? v[1] : 0)); if (!isNaN(v)) { platformVersion = v; return; } } platformVersion = 0; // fallback to user-agent checking var pName = self.platform(); var versionMatch = { 'android': /Android (\d+).(\d+)?/, 'ios': /OS (\d+)_(\d+)?/, 'windowsphone': /Windows Phone (\d+).(\d+)?/ }; if (versionMatch[pName]) { v = self.ua.match(versionMatch[pName]); if (v && v.length > 2) { platformVersion = parseFloat(v[1] + '.' + v[2]); } } }, /** * @ngdoc method * @name ionic.Platform#is * @param {string} Platform name. * @returns {boolean} Whether the platform name provided is detected. */ is: function(type) { type = type.toLowerCase(); // check if it has an array of platforms if (self.platforms) { for (var x = 0; x < self.platforms.length; x++) { if (self.platforms[x] === type) return true; } } // exact match var pName = self.platform(); if (pName) { return pName === type.toLowerCase(); } // A quick hack for to check userAgent return self.ua.toLowerCase().indexOf(type) >= 0; }, /** * @ngdoc method * @name ionic.Platform#exitApp * @description Exit the app. */ exitApp: function() { self.ready(function() { navigator.app && navigator.app.exitApp && navigator.app.exitApp(); }); }, /** * @ngdoc method * @name ionic.Platform#showStatusBar * @description Shows or hides the device status bar (in Cordova). Requires `cordova plugin add org.apache.cordova.statusbar` * @param {boolean} shouldShow Whether or not to show the status bar. */ showStatusBar: function(val) { // Only useful when run within cordova self._showStatusBar = val; self.ready(function() { // run this only when or if the platform (cordova) is ready requestAnimationFrame(function() { if (self._showStatusBar) { // they do not want it to be full screen window.StatusBar && window.StatusBar.show(); document.body.classList.remove('status-bar-hide'); } else { // it should be full screen window.StatusBar && window.StatusBar.hide(); document.body.classList.add('status-bar-hide'); } }); }); }, /** * @ngdoc method * @name ionic.Platform#fullScreen * @description * Sets whether the app is fullscreen or not (in Cordova). * @param {boolean=} showFullScreen Whether or not to set the app to fullscreen. Defaults to true. Requires `cordova plugin add org.apache.cordova.statusbar` * @param {boolean=} showStatusBar Whether or not to show the device's status bar. Defaults to false. */ fullScreen: function(showFullScreen, showStatusBar) { // showFullScreen: default is true if no param provided self.isFullScreen = (showFullScreen !== false); // add/remove the fullscreen classname to the body ionic.DomUtil.ready(function() { // run this only when or if the DOM is ready requestAnimationFrame(function() { if (self.isFullScreen) { document.body.classList.add('fullscreen'); } else { document.body.classList.remove('fullscreen'); } }); // showStatusBar: default is false if no param provided self.showStatusBar((showStatusBar === true)); }); } }; var platformName = null, // just the name, like iOS or Android platformVersion = null, // a float of the major and minor, like 7.1 readyCallbacks = [], windowLoadListenderAttached, platformReadyTimer = 2000; // How long to wait for platform ready before emitting a warning verifyPlatformReady(); // Warn the user if deviceready did not fire in a reasonable amount of time, and how to fix it. function verifyPlatformReady() { setTimeout(function() { if(!self.isReady && self.isWebView()) { console.warn('Possible issue: deviceready did not fire in a reasonable amount of time. ' + 'This can be caused by plugins in an inconsistent state. One possible solution: uninstall/remove all ' + 'plugins and reinstall them. Additionally, one or more plugins might be faulty or out of date.'); } }, platformReadyTimer); } // setup listeners to know when the device is ready to go function onWindowLoad() { if (self.isWebView()) { // the window and scripts are fully loaded, and a cordova/phonegap // object exists then let's listen for the deviceready document.addEventListener("deviceready", onPlatformReady, false); } else { // the window and scripts are fully loaded, but the window object doesn't have the // cordova/phonegap object, so its just a browser, not a webview wrapped w/ cordova onPlatformReady(); } if (windowLoadListenderAttached) { window.removeEventListener("load", onWindowLoad, false); } } if (document.readyState === 'complete') { onWindowLoad(); } else { windowLoadListenderAttached = true; window.addEventListener("load", onWindowLoad, false); } function onPlatformReady() { // the device is all set to go, init our own stuff then fire off our event self.isReady = true; self.detect(); for (var x = 0; x < readyCallbacks.length; x++) { // fire off all the callbacks that were added before the platform was ready readyCallbacks[x](); } readyCallbacks = []; ionic.trigger('platformready', { target: document }); requestAnimationFrame(function() { document.body.classList.add('platform-ready'); }); } })(window, document, ionic); (function(document, ionic) { 'use strict'; // Ionic CSS polyfills ionic.CSS = {}; ionic.CSS.TRANSITION = []; ionic.CSS.TRANSFORM = []; ionic.EVENTS = {}; (function() { // transform var i, keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform', '-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform', 'msTransform']; for (i = 0; i < keys.length; i++) { if (document.documentElement.style[keys[i]] !== undefined) { ionic.CSS.TRANSFORM = keys[i]; break; } } // transition keys = ['webkitTransition', 'mozTransition', 'msTransition', 'transition']; for (i = 0; i < keys.length; i++) { if (document.documentElement.style[keys[i]] !== undefined) { ionic.CSS.TRANSITION = keys[i]; break; } } // Fallback in case the keys don't exist at all ionic.CSS.TRANSITION = ionic.CSS.TRANSITION || 'transition'; // The only prefix we care about is webkit for transitions. var isWebkit = ionic.CSS.TRANSITION.indexOf('webkit') > -1; // transition duration ionic.CSS.TRANSITION_DURATION = (isWebkit ? '-webkit-' : '') + 'transition-duration'; // To be sure transitionend works everywhere, include *both* the webkit and non-webkit events ionic.CSS.TRANSITIONEND = (isWebkit ? 'webkitTransitionEnd ' : '') + 'transitionend'; })(); (function() { var touchStartEvent = 'touchstart'; var touchMoveEvent = 'touchmove'; var touchEndEvent = 'touchend'; var touchCancelEvent = 'touchcancel'; if (window.navigator.pointerEnabled) { touchStartEvent = 'pointerdown'; touchMoveEvent = 'pointermove'; touchEndEvent = 'pointerup'; touchCancelEvent = 'pointercancel'; } else if (window.navigator.msPointerEnabled) { touchStartEvent = 'MSPointerDown'; touchMoveEvent = 'MSPointerMove'; touchEndEvent = 'MSPointerUp'; touchCancelEvent = 'MSPointerCancel'; } ionic.EVENTS.touchstart = touchStartEvent; ionic.EVENTS.touchmove = touchMoveEvent; ionic.EVENTS.touchend = touchEndEvent; ionic.EVENTS.touchcancel = touchCancelEvent; })(); // classList polyfill for them older Androids // https://gist.github.com/devongovett/1381839 if (!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') { Object.defineProperty(HTMLElement.prototype, 'classList', { get: function() { var self = this; function update(fn) { return function() { var x, classes = self.className.split(/\s+/); for (x = 0; x < arguments.length; x++) { fn(classes, classes.indexOf(arguments[x]), arguments[x]); } self.className = classes.join(" "); }; } return { add: update(function(classes, index, value) { ~index || classes.push(value); }), remove: update(function(classes, index) { ~index && classes.splice(index, 1); }), toggle: update(function(classes, index, value) { ~index ? classes.splice(index, 1) : classes.push(value); }), contains: function(value) { return !!~self.className.split(/\s+/).indexOf(value); }, item: function(i) { return self.className.split(/\s+/)[i] || null; } }; } }); } })(document, ionic); /** * @ngdoc page * @name tap * @module ionic * @description * On touch devices such as a phone or tablet, some browsers implement a 300ms delay between * the time the user stops touching the display and the moment the browser executes the * click. This delay was initially introduced so the browser can know whether the user wants to * double-tap to zoom in on the webpage. Basically, the browser waits roughly 300ms to see if * the user is double-tapping, or just tapping on the display once. * * Out of the box, Ionic automatically removes the 300ms delay in order to make Ionic apps * feel more "native" like. Resultingly, other solutions such as * [fastclick](https://github.com/ftlabs/fastclick) and Angular's * [ngTouch](https://docs.angularjs.org/api/ngTouch) should not be included, to avoid conflicts. * * Some browsers already remove the delay with certain settings, such as the CSS property * `touch-events: none` or with specific meta tag viewport values. However, each of these * browsers still handle clicks differently, such as when to fire off or cancel the event * (like scrolling when the target is a button, or holding a button down). * For browsers that already remove the 300ms delay, consider Ionic's tap system as a way to * normalize how clicks are handled across the various devices so there's an expected response * no matter what the device, platform or version. Additionally, Ionic will prevent * ghostclicks which even browsers that remove the delay still experience. * * In some cases, third-party libraries may also be working with touch events which can interfere * with the tap system. For example, mapping libraries like Google or Leaflet Maps often implement * a touch detection system which conflicts with Ionic's tap system. * * ### Disabling the tap system * * To disable the tap for an element and all of its children elements, * add the attribute `data-tap-disabled="true"`. * * ```html * <div data-tap-disabled="true"> * <div id="google-map"></div> * </div> * ``` * * ### Additional Notes: * * - Ionic tap works with Ionic's JavaScript scrolling * - Elements can come and go from the DOM and Ionic tap doesn't keep adding and removing * listeners * - No "tap delay" after the first "tap" (you can tap as fast as you want, they all click) * - Minimal events listeners, only being added to document * - Correct focus in/out on each input type (select, textearea, range) on each platform/device * - Shows and hides virtual keyboard correctly for each platform/device * - Works with labels surrounding inputs * - Does not fire off a click if the user moves the pointer too far * - Adds and removes an 'activated' css class * - Multiple [unit tests](https://github.com/driftyco/ionic/blob/master/test/unit/utils/tap.unit.js) for each scenario * */ /* IONIC TAP --------------- - Both touch and mouse events are added to the document.body on DOM ready - If a touch event happens, it does not use mouse event listeners - On touchend, if the distance between start and end was small, trigger a click - In the triggered click event, add a 'isIonicTap' property - The triggered click receives the same x,y coordinates as as the end event - On document.body click listener (with useCapture=true), only allow clicks with 'isIonicTap' - Triggering clicks with mouse events work the same as touch, except with mousedown/mouseup - Tapping inputs is disabled during scrolling */ var tapDoc; // the element which the listeners are on (document.body) var tapActiveEle; // the element which is active (probably has focus) var tapEnabledTouchEvents; var tapMouseResetTimer; var tapPointerMoved; var tapPointerStart; var tapTouchFocusedInput; var tapLastTouchTarget; var tapTouchMoveListener = 'touchmove'; // how much the coordinates can be off between start/end, but still a click var TAP_RELEASE_TOLERANCE = 12; // default tolerance var TAP_RELEASE_BUTTON_TOLERANCE = 50; // button elements should have a larger tolerance var tapEventListeners = { 'click': tapClickGateKeeper, 'mousedown': tapMouseDown, 'mouseup': tapMouseUp, 'mousemove': tapMouseMove, 'touchstart': tapTouchStart, 'touchend': tapTouchEnd, 'touchcancel': tapTouchCancel, 'touchmove': tapTouchMove, 'pointerdown': tapTouchStart, 'pointerup': tapTouchEnd, 'pointercancel': tapTouchCancel, 'pointermove': tapTouchMove, 'MSPointerDown': tapTouchStart, 'MSPointerUp': tapTouchEnd, 'MSPointerCancel': tapTouchCancel, 'MSPointerMove': tapTouchMove, 'focusin': tapFocusIn, 'focusout': tapFocusOut }; ionic.tap = { register: function(ele) { tapDoc = ele; tapEventListener('click', true, true); tapEventListener('mouseup'); tapEventListener('mousedown'); if (window.navigator.pointerEnabled) { tapEventListener('pointerdown'); tapEventListener('pointerup'); tapEventListener('pointercancel'); tapTouchMoveListener = 'pointermove'; } else if (window.navigator.msPointerEnabled) { tapEventListener('MSPointerDown'); tapEventListener('MSPointerUp'); tapEventListener('MSPointerCancel'); tapTouchMoveListener = 'MSPointerMove'; } else { tapEventListener('touchstart'); tapEventListener('touchend'); tapEventListener('touchcancel'); } tapEventListener('focusin'); tapEventListener('focusout'); return function() { for (var type in tapEventListeners) { tapEventListener(type, false); } tapDoc = null; tapActiveEle = null; tapEnabledTouchEvents = false; tapPointerMoved = false; tapPointerStart = null; }; }, ignoreScrollStart: function(e) { return (e.defaultPrevented) || // defaultPrevented has been assigned by another component handling the event (/^(file|range)$/i).test(e.target.type) || (e.target.dataset ? e.target.dataset.preventScroll : e.target.getAttribute('data-prevent-scroll')) == 'true' || // manually set within an elements attributes (!!(/^(object|embed)$/i).test(e.target.tagName)) || // flash/movie/object touches should not try to scroll ionic.tap.isElementTapDisabled(e.target); // check if this element, or an ancestor, has `data-tap-disabled` attribute }, isTextInput: function(ele) { return !!ele && (ele.tagName == 'TEXTAREA' || ele.contentEditable === 'true' || (ele.tagName == 'INPUT' && !(/^(radio|checkbox|range|file|submit|reset|color|image|button)$/i).test(ele.type))); }, isDateInput: function(ele) { return !!ele && (ele.tagName == 'INPUT' && (/^(date|time|datetime-local|month|week)$/i).test(ele.type)); }, isVideo: function(ele) { return !!ele && (ele.tagName == 'VIDEO'); }, isKeyboardElement: function(ele) { if ( !ionic.Platform.isIOS() || ionic.Platform.isIPad() ) { return ionic.tap.isTextInput(ele) && !ionic.tap.isDateInput(ele); } else { return ionic.tap.isTextInput(ele) || ( !!ele && ele.tagName == "SELECT"); } }, isLabelWithTextInput: function(ele) { var container = tapContainingElement(ele, false); return !!container && ionic.tap.isTextInput(tapTargetElement(container)); }, containsOrIsTextInput: function(ele) { return ionic.tap.isTextInput(ele) || ionic.tap.isLabelWithTextInput(ele); }, cloneFocusedInput: function(container) { if (ionic.tap.hasCheckedClone) return; ionic.tap.hasCheckedClone = true; ionic.requestAnimationFrame(function() { var focusInput = container.querySelector(':focus'); if (ionic.tap.isTextInput(focusInput) && !ionic.tap.isDateInput(focusInput)) { var clonedInput = focusInput.cloneNode(true); clonedInput.value = focusInput.value; clonedInput.classList.add('cloned-text-input'); clonedInput.readOnly = true; if (focusInput.isContentEditable) { clonedInput.contentEditable = focusInput.contentEditable; clonedInput.innerHTML = focusInput.innerHTML; } focusInput.parentElement.insertBefore(clonedInput, focusInput); focusInput.classList.add('previous-input-focus'); clonedInput.scrollTop = focusInput.scrollTop; } }); }, hasCheckedClone: false, removeClonedInputs: function(container) { ionic.tap.hasCheckedClone = false; ionic.requestAnimationFrame(function() { var clonedInputs = container.querySelectorAll('.cloned-text-input'); var previousInputFocus = container.querySelectorAll('.previous-input-focus'); var x; for (x = 0; x < clonedInputs.length; x++) { clonedInputs[x].parentElement.removeChild(clonedInputs[x]); } for (x = 0; x < previousInputFocus.length; x++) { previousInputFocus[x].classList.remove('previous-input-focus'); previousInputFocus[x].style.top = ''; if ( ionic.keyboard.isOpen && !ionic.keyboard.isClosing ) previousInputFocus[x].focus(); } }); }, requiresNativeClick: function(ele) { if (ionic.Platform.isWindowsPhone() && (ele.tagName == 'A' || ele.tagName == 'BUTTON' || ele.hasAttribute('ng-click') || (ele.tagName == 'INPUT' && (ele.type == 'button' || ele.type == 'submit')))) { return true; //Windows Phone edge case, prevent ng-click (and similar) events from firing twice on this platform } if (!ele || ele.disabled || (/^(file|range)$/i).test(ele.type) || (/^(object|video)$/i).test(ele.tagName) || ionic.tap.isLabelContainingFileInput(ele)) { return true; } return ionic.tap.isElementTapDisabled(ele); }, isLabelContainingFileInput: function(ele) { var lbl = tapContainingElement(ele); if (lbl.tagName !== 'LABEL') return false; var fileInput = lbl.querySelector('input[type=file]'); if (fileInput && fileInput.disabled === false) return true; return false; }, isElementTapDisabled: function(ele) { if (ele && ele.nodeType === 1) { var element = ele; while (element) { if ((element.dataset ? element.dataset.tapDisabled : element.getAttribute && element.getAttribute('data-tap-disabled')) == 'true') { return true; } element = element.parentElement; } } return false; }, setTolerance: function(releaseTolerance, releaseButtonTolerance) { TAP_RELEASE_TOLERANCE = releaseTolerance; TAP_RELEASE_BUTTON_TOLERANCE = releaseButtonTolerance; }, cancelClick: function() { // used to cancel any simulated clicks which may happen on a touchend/mouseup // gestures uses this method within its tap and hold events tapPointerMoved = true; }, pointerCoord: function(event) { // This method can get coordinates for both a mouse click // or a touch depending on the given event var c = { x: 0, y: 0 }; if (event) { var touches = event.touches && event.touches.length ? event.touches : [event]; var e = (event.changedTouches && event.changedTouches[0]) || touches[0]; if (e) { c.x = e.clientX || e.pageX || 0; c.y = e.clientY || e.pageY || 0; } } return c; } }; function tapEventListener(type, enable, useCapture) { if (enable !== false) { tapDoc.addEventListener(type, tapEventListeners[type], useCapture); } else { tapDoc.removeEventListener(type, tapEventListeners[type]); } } function tapClick(e) { // simulate a normal click by running the element's click method then focus on it var container = tapContainingElement(e.target); var ele = tapTargetElement(container); if (ionic.tap.requiresNativeClick(ele) || tapPointerMoved) return false; var c = ionic.tap.pointerCoord(e); //console.log('tapClick', e.type, ele.tagName, '('+c.x+','+c.y+')'); triggerMouseEvent('click', ele, c.x, c.y); // if it's an input, focus in on the target, otherwise blur tapHandleFocus(ele); } function triggerMouseEvent(type, ele, x, y) { // using initMouseEvent instead of MouseEvent for our Android friends var clickEvent = document.createEvent("MouseEvents"); clickEvent.initMouseEvent(type, true, true, window, 1, 0, 0, x, y, false, false, false, false, 0, null); clickEvent.isIonicTap = true; ele.dispatchEvent(clickEvent); } function tapClickGateKeeper(e) { //console.log('click ' + Date.now() + ' isIonicTap: ' + (e.isIonicTap ? true : false)); if (e.target.type == 'submit' && e.detail === 0) { // do not prevent click if it came from an "Enter" or "Go" keypress submit return null; } // do not allow through any click events that were not created by ionic.tap if ((ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) || (!e.isIonicTap && !ionic.tap.requiresNativeClick(e.target))) { //console.log('clickPrevent', e.target.tagName); e.stopPropagation(); if (!ionic.tap.isLabelWithTextInput(e.target)) { // labels clicks from native should not preventDefault othersize keyboard will not show on input focus e.preventDefault(); } return false; } } // MOUSE function tapMouseDown(e) { //console.log('mousedown ' + Date.now()); if (e.isIonicTap || tapIgnoreEvent(e)) return null; if (tapEnabledTouchEvents) { //console.log('mousedown', 'stop event'); e.stopPropagation(); if (!ionic.Platform.isEdge() && (!ionic.tap.isTextInput(e.target) || tapLastTouchTarget !== e.target) && !isSelectOrOption(e.target.tagName) && !ionic.tap.isVideo(e.target)) { // If you preventDefault on a text input then you cannot move its text caret/cursor. // Allow through only the text input default. However, without preventDefault on an // input the 300ms delay can change focus on inputs after the keyboard shows up. // The focusin event handles the chance of focus changing after the keyboard shows. // Windows Phone - if you preventDefault on a video element then you cannot operate // its native controls. e.preventDefault(); } return false; } tapPointerMoved = false; tapPointerStart = ionic.tap.pointerCoord(e); tapEventListener('mousemove'); ionic.activator.start(e); } function tapMouseUp(e) { //console.log("mouseup " + Date.now()); if (tapEnabledTouchEvents) { e.stopPropagation(); e.preventDefault(); return false; } if (tapIgnoreEvent(e) || isSelectOrOption(e.target.tagName)) return false; if (!tapHasPointerMoved(e)) { tapClick(e); } tapEventListener('mousemove', false); ionic.activator.end(); tapPointerMoved = false; } function tapMouseMove(e) { if (tapHasPointerMoved(e)) { tapEventListener('mousemove', false); ionic.activator.end(); tapPointerMoved = true; return false; } } // TOUCH function tapTouchStart(e) { //console.log("touchstart " + Date.now()); if (tapIgnoreEvent(e)) return; tapPointerMoved = false; tapEnableTouchEvents(); tapPointerStart = ionic.tap.pointerCoord(e); tapEventListener(tapTouchMoveListener); ionic.activator.start(e); if (ionic.Platform.isIOS() && ionic.tap.isLabelWithTextInput(e.target)) { // if the tapped element is a label, which has a child input // then preventDefault so iOS doesn't ugly auto scroll to the input // but do not prevent default on Android or else you cannot move the text caret // and do not prevent default on Android or else no virtual keyboard shows up var textInput = tapTargetElement(tapContainingElement(e.target)); if (textInput !== tapActiveEle) { // don't preventDefault on an already focused input or else iOS's text caret isn't usable //console.log('Would prevent default here'); e.preventDefault(); } } } function tapTouchEnd(e) { //console.log('touchend ' + Date.now()); if (tapIgnoreEvent(e)) return; tapEnableTouchEvents(); if (!tapHasPointerMoved(e)) { tapClick(e); if (isSelectOrOption(e.target.tagName)) { e.preventDefault(); } } tapLastTouchTarget = e.target; tapTouchCancel(); } function tapTouchMove(e) { if (tapHasPointerMoved(e)) { tapPointerMoved = true; tapEventListener(tapTouchMoveListener, false); ionic.activator.end(); return false; } } function tapTouchCancel() { tapEventListener(tapTouchMoveListener, false); ionic.activator.end(); tapPointerMoved = false; } function tapEnableTouchEvents() { tapEnabledTouchEvents = true; clearTimeout(tapMouseResetTimer); tapMouseResetTimer = setTimeout(function() { tapEnabledTouchEvents = false; }, 600); } function tapIgnoreEvent(e) { if (e.isTapHandled) return true; e.isTapHandled = true; if(ionic.tap.isElementTapDisabled(e.target)) { return true; } if (ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) { e.preventDefault(); return true; } } function tapHandleFocus(ele) { tapTouchFocusedInput = null; var triggerFocusIn = false; if (ele.tagName == 'SELECT') { // trick to force Android options to show up triggerMouseEvent('mousedown', ele, 0, 0); ele.focus && ele.focus(); triggerFocusIn = true; } else if (tapActiveElement() === ele) { // already is the active element and has focus triggerFocusIn = true; } else if ((/^(input|textarea|ion-label)$/i).test(ele.tagName) || ele.isContentEditable) { triggerFocusIn = true; ele.focus && ele.focus(); ele.value = ele.value; if (tapEnabledTouchEvents) { tapTouchFocusedInput = ele; } } else { tapFocusOutActive(); } if (triggerFocusIn) { tapActiveElement(ele); ionic.trigger('ionic.focusin', { target: ele }, true); } } function tapFocusOutActive() { var ele = tapActiveElement(); if (ele && ((/^(input|textarea|select)$/i).test(ele.tagName) || ele.isContentEditable)) { //console.log('tapFocusOutActive', ele.tagName); ele.blur(); } tapActiveElement(null); } function tapFocusIn(e) { //console.log('focusin ' + Date.now()); // Because a text input doesn't preventDefault (so the caret still works) there's a chance // that its mousedown event 300ms later will change the focus to another element after // the keyboard shows up. if (tapEnabledTouchEvents && ionic.tap.isTextInput(tapActiveElement()) && ionic.tap.isTextInput(tapTouchFocusedInput) && tapTouchFocusedInput !== e.target) { // 1) The pointer is from touch events // 2) There is an active element which is a text input // 3) A text input was just set to be focused on by a touch event // 4) A new focus has been set, however the target isn't the one the touch event wanted //console.log('focusin', 'tapTouchFocusedInput'); tapTouchFocusedInput.focus(); tapTouchFocusedInput = null; } ionic.scroll.isScrolling = false; } function tapFocusOut() { //console.log("focusout"); tapActiveElement(null); } function tapActiveElement(ele) { if (arguments.length) { tapActiveEle = ele; } return tapActiveEle || document.activeElement; } function tapHasPointerMoved(endEvent) { if (!endEvent || endEvent.target.nodeType !== 1 || !tapPointerStart || (tapPointerStart.x === 0 && tapPointerStart.y === 0)) { return false; } var endCoordinates = ionic.tap.pointerCoord(endEvent); var hasClassList = !!(endEvent.target.classList && endEvent.target.classList.contains && typeof endEvent.target.classList.contains === 'function'); var releaseTolerance = hasClassList && endEvent.target.classList.contains('button') ? TAP_RELEASE_BUTTON_TOLERANCE : TAP_RELEASE_TOLERANCE; return Math.abs(tapPointerStart.x - endCoordinates.x) > releaseTolerance || Math.abs(tapPointerStart.y - endCoordinates.y) > releaseTolerance; } function tapContainingElement(ele, allowSelf) { var climbEle = ele; for (var x = 0; x < 6; x++) { if (!climbEle) break; if (climbEle.tagName === 'LABEL') return climbEle; climbEle = climbEle.parentElement; } if (allowSelf !== false) return ele; } function tapTargetElement(ele) { if (ele && ele.tagName === 'LABEL') { if (ele.control) return ele.control; // older devices do not support the "control" property if (ele.querySelector) { var control = ele.querySelector('input,textarea,select'); if (control) return control; } } return ele; } function isSelectOrOption(tagName){ return (/^(select|option)$/i).test(tagName); } ionic.DomUtil.ready(function() { var ng = typeof angular !== 'undefined' ? angular : null; //do nothing for e2e tests if (!ng || (ng && !ng.scenario)) { ionic.tap.register(document); } }); (function(document, ionic) { 'use strict'; var queueElements = {}; // elements that should get an active state in XX milliseconds var activeElements = {}; // elements that are currently active var keyId = 0; // a counter for unique keys for the above ojects var ACTIVATED_CLASS = 'activated'; ionic.activator = { start: function(e) { var hitX = ionic.tap.pointerCoord(e).x; if (hitX > 0 && hitX < 30) { return; } // when an element is touched/clicked, it climbs up a few // parents to see if it is an .item or .button element ionic.requestAnimationFrame(function() { if ((ionic.scroll && ionic.scroll.isScrolling) || ionic.tap.requiresNativeClick(e.target)) return; var ele = e.target; var eleToActivate; for (var x = 0; x < 6; x++) { if (!ele || ele.nodeType !== 1) break; if (eleToActivate && ele.classList && ele.classList.contains('item')) { eleToActivate = ele; break; } if (ele.tagName == 'A' || ele.tagName == 'BUTTON' || ele.hasAttribute('ng-click')) { eleToActivate = ele; break; } if (ele.classList.contains('button')) { eleToActivate = ele; break; } // no sense climbing past these if (ele.tagName == 'ION-CONTENT' || (ele.classList && ele.classList.contains('pane')) || ele.tagName == 'BODY') { break; } ele = ele.parentElement; } if (eleToActivate) { // queue that this element should be set to active queueElements[keyId] = eleToActivate; // on the next frame, set the queued elements to active ionic.requestAnimationFrame(activateElements); keyId = (keyId > 29 ? 0 : keyId + 1); } }); }, end: function() { // clear out any active/queued elements after XX milliseconds setTimeout(clear, 200); } }; function clear() { // clear out any elements that are queued to be set to active queueElements = {}; // in the next frame, remove the active class from all active elements ionic.requestAnimationFrame(deactivateElements); } function activateElements() { // activate all elements in the queue for (var key in queueElements) { if (queueElements[key]) { queueElements[key].classList.add(ACTIVATED_CLASS); activeElements[key] = queueElements[key]; } } queueElements = {}; } function deactivateElements() { if (ionic.transition && ionic.transition.isActive) { setTimeout(deactivateElements, 400); return; } for (var key in activeElements) { if (activeElements[key]) { activeElements[key].classList.remove(ACTIVATED_CLASS); delete activeElements[key]; } } } })(document, ionic); (function(ionic) { /* for nextUid function below */ var nextId = 0; /** * Various utilities used throughout Ionic * * Some of these are adopted from underscore.js and backbone.js, both also MIT licensed. */ ionic.Utils = { arrayMove: function(arr, oldIndex, newIndex) { if (newIndex >= arr.length) { var k = newIndex - arr.length; while ((k--) + 1) { arr.push(undefined); } } arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]); return arr; }, /** * Return a function that will be called with the given context */ proxy: function(func, context) { var args = Array.prototype.slice.call(arguments, 2); return function() { return func.apply(context, args.concat(Array.prototype.slice.call(arguments))); }; }, /** * Only call a function once in the given interval. * * @param func {Function} the function to call * @param wait {int} how long to wait before/after to allow function calls * @param immediate {boolean} whether to call immediately or after the wait interval */ debounce: function(func, wait, immediate) { var timeout, args, context, timestamp, result; return function() { context = this; args = arguments; timestamp = new Date(); var later = function() { var last = (new Date()) - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) result = func.apply(context, args); } }; var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) result = func.apply(context, args); return result; }; }, /** * Throttle the given fun, only allowing it to be * called at most every `wait` ms. */ throttle: function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : Date.now(); timeout = null; result = func.apply(context, args); }; return function() { var now = Date.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }, // Borrowed from Backbone.js's extend // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. inherit: function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && protoProps.hasOwnProperty('constructor')) { child = protoProps.constructor; } else { child = function() { return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. ionic.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function() { this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate(); // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) ionic.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }, // Extend adapted from Underscore.js extend: function(obj) { var args = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < args.length; i++) { var source = args[i]; if (source) { for (var prop in source) { obj[prop] = source[prop]; } } } return obj; }, nextUid: function() { return 'ion' + (nextId++); }, disconnectScope: function disconnectScope(scope) { if (!scope) return; if (scope.$root === scope) { return; // we can't disconnect the root node; } var parent = scope.$parent; scope.$$disconnected = true; scope.$broadcast('$ionic.disconnectScope', scope); // See Scope.$destroy if (parent.$$childHead === scope) { parent.$$childHead = scope.$$nextSibling; } if (parent.$$childTail === scope) { parent.$$childTail = scope.$$prevSibling; } if (scope.$$prevSibling) { scope.$$prevSibling.$$nextSibling = scope.$$nextSibling; } if (scope.$$nextSibling) { scope.$$nextSibling.$$prevSibling = scope.$$prevSibling; } scope.$$nextSibling = scope.$$prevSibling = null; }, reconnectScope: function reconnectScope(scope) { if (!scope) return; if (scope.$root === scope) { return; // we can't disconnect the root node; } if (!scope.$$disconnected) { return; } var parent = scope.$parent; scope.$$disconnected = false; scope.$broadcast('$ionic.reconnectScope', scope); // See Scope.$new for this logic... scope.$$prevSibling = parent.$$childTail; if (parent.$$childHead) { parent.$$childTail.$$nextSibling = scope; parent.$$childTail = scope; } else { parent.$$childHead = parent.$$childTail = scope; } }, isScopeDisconnected: function(scope) { var climbScope = scope; while (climbScope) { if (climbScope.$$disconnected) return true; climbScope = climbScope.$parent; } return false; } }; // Bind a few of the most useful functions to the ionic scope ionic.inherit = ionic.Utils.inherit; ionic.extend = ionic.Utils.extend; ionic.throttle = ionic.Utils.throttle; ionic.proxy = ionic.Utils.proxy; ionic.debounce = ionic.Utils.debounce; })(window.ionic); /** * @ngdoc page * @name keyboard * @module ionic * @description * On both Android and iOS, Ionic will attempt to prevent the keyboard from * obscuring inputs and focusable elements when it appears by scrolling them * into view. In order for this to work, any focusable elements must be within * a [Scroll View](http://ionicframework.com/docs/api/directive/ionScroll/) * or a directive such as [Content](http://ionicframework.com/docs/api/directive/ionContent/) * that has a Scroll View. * * It will also attempt to prevent the native overflow scrolling on focus, * which can cause layout issues such as pushing headers up and out of view. * * The keyboard fixes work best in conjunction with the * [Ionic Keyboard Plugin](https://github.com/driftyco/ionic-plugins-keyboard), * although it will perform reasonably well without. However, if you are using * Cordova there is no reason not to use the plugin. * * ### Hide when keyboard shows * * To hide an element when the keyboard is open, add the class `hide-on-keyboard-open`. * * ```html * <div class="hide-on-keyboard-open"> * <div id="google-map"></div> * </div> * ``` * * Note: For performance reasons, elements will not be hidden for 400ms after the start of the `native.keyboardshow` event * from the Ionic Keyboard plugin. If you would like them to disappear immediately, you could do something * like: * * ```js * window.addEventListener('native.keyboardshow', function(){ * document.body.classList.add('keyboard-open'); * }); * ``` * This adds the same `keyboard-open` class that is normally added by Ionic 400ms after the keyboard * opens. However, bear in mind that adding this class to the body immediately may cause jank in any * animations on Android that occur when the keyboard opens (for example, scrolling any obscured inputs into view). * * ---------- * * ### Plugin Usage * Information on using the plugin can be found at * [https://github.com/driftyco/ionic-plugins-keyboard](https://github.com/driftyco/ionic-plugins-keyboard). * * ---------- * * ### Android Notes * - If your app is running in fullscreen, i.e. you have * `<preference name="Fullscreen" value="true" />` in your `config.xml` file * you will need to set `ionic.Platform.isFullScreen = true` manually. * * - You can configure the behavior of the web view when the keyboard shows by setting * [android:windowSoftInputMode](http://developer.android.com/reference/android/R.attr.html#windowSoftInputMode) * to either `adjustPan`, `adjustResize` or `adjustNothing` in your app's * activity in `AndroidManifest.xml`. `adjustResize` is the recommended setting * for Ionic, but if for some reason you do use `adjustPan` you will need to * set `ionic.Platform.isFullScreen = true`. * * ```xml * <activity android:windowSoftInputMode="adjustResize"> * * ``` * * ### iOS Notes * - If the content of your app (including the header) is being pushed up and * out of view on input focus, try setting `cordova.plugins.Keyboard.disableScroll(true)`. * This does **not** disable scrolling in the Ionic scroll view, rather it * disables the native overflow scrolling that happens automatically as a * result of focusing on inputs below the keyboard. * */ /** * The current viewport height. */ var keyboardCurrentViewportHeight = 0; /** * The viewport height when in portrait orientation. */ var keyboardPortraitViewportHeight = 0; /** * The viewport height when in landscape orientation. */ var keyboardLandscapeViewportHeight = 0; /** * The currently focused input. */ var keyboardActiveElement; /** * The previously focused input used to reset keyboard after focusing on a * new non-keyboard element */ var lastKeyboardActiveElement; /** * The scroll view containing the currently focused input. */ var scrollView; /** * Timer for the setInterval that polls window.innerHeight to determine whether * the layout has updated for the keyboard showing/hiding. */ var waitForResizeTimer; /** * Sometimes when switching inputs or orientations, focusout will fire before * focusin, so this timer is for the small setTimeout to determine if we should * really focusout/hide the keyboard. */ var keyboardFocusOutTimer; /** * on Android, orientationchange will fire before the keyboard plugin notifies * the browser that the keyboard will show/is showing, so this flag indicates * to nativeShow that there was an orientationChange and we should update * the viewport height with an accurate keyboard height value */ var wasOrientationChange = false; /** * CSS class added to the body indicating the keyboard is open. */ var KEYBOARD_OPEN_CSS = 'keyboard-open'; /** * CSS class that indicates a scroll container. */ var SCROLL_CONTAINER_CSS = 'scroll-content'; /** * Debounced keyboardFocusIn function */ var debouncedKeyboardFocusIn = ionic.debounce(keyboardFocusIn, 200, true); /** * Debounced keyboardNativeShow function */ var debouncedKeyboardNativeShow = ionic.debounce(keyboardNativeShow, 100, true); /** * Ionic keyboard namespace. * @namespace keyboard */ ionic.keyboard = { /** * Whether the keyboard is open or not. */ isOpen: false, /** * Whether the keyboard is closing or not. */ isClosing: false, /** * Whether the keyboard is opening or not. */ isOpening: false, /** * The height of the keyboard in pixels, as reported by the keyboard plugin. * If the plugin is not available, calculated as the difference in * window.innerHeight after the keyboard has shown. */ height: 0, /** * Whether the device is in landscape orientation or not. */ isLandscape: false, /** * Whether the keyboard event listeners have been added or not */ isInitialized: false, /** * Hide the keyboard, if it is open. */ hide: function() { if (keyboardHasPlugin()) { cordova.plugins.Keyboard.close(); } keyboardActiveElement && keyboardActiveElement.blur(); }, /** * An alias for cordova.plugins.Keyboard.show(). If the keyboard plugin * is installed, show the keyboard. */ show: function() { if (keyboardHasPlugin()) { cordova.plugins.Keyboard.show(); } }, /** * Remove all keyboard related event listeners, effectively disabling Ionic's * keyboard adjustments. */ disable: function() { if (keyboardHasPlugin()) { window.removeEventListener('native.keyboardshow', debouncedKeyboardNativeShow ); window.removeEventListener('native.keyboardhide', keyboardFocusOut); } else { document.body.removeEventListener('focusout', keyboardFocusOut); } document.body.removeEventListener('ionic.focusin', debouncedKeyboardFocusIn); document.body.removeEventListener('focusin', debouncedKeyboardFocusIn); window.removeEventListener('orientationchange', keyboardOrientationChange); if ( window.navigator.msPointerEnabled ) { document.removeEventListener("MSPointerDown", keyboardInit); } else { document.removeEventListener('touchstart', keyboardInit); } ionic.keyboard.isInitialized = false; }, /** * Alias for keyboardInit, initialize all keyboard related event listeners. */ enable: function() { keyboardInit(); } }; // Initialize the viewport height (after ionic.keyboard.height has been // defined). keyboardCurrentViewportHeight = getViewportHeight(); /* Event handlers */ /* ------------------------------------------------------------------------- */ /** * Event handler for first touch event, initializes all event listeners * for keyboard related events. Also aliased by ionic.keyboard.enable. */ function keyboardInit() { if (ionic.keyboard.isInitialized) return; if (keyboardHasPlugin()) { window.addEventListener('native.keyboardshow', debouncedKeyboardNativeShow); window.addEventListener('native.keyboardhide', keyboardFocusOut); } else { document.body.addEventListener('focusout', keyboardFocusOut); } document.body.addEventListener('ionic.focusin', debouncedKeyboardFocusIn); document.body.addEventListener('focusin', debouncedKeyboardFocusIn); if (window.navigator.msPointerEnabled) { document.removeEventListener("MSPointerDown", keyboardInit); } else { document.removeEventListener('touchstart', keyboardInit); } ionic.keyboard.isInitialized = true; } /** * Event handler for 'native.keyboardshow' event, sets keyboard.height to the * reported height and keyboard.isOpening to true. Then calls * keyboardWaitForResize with keyboardShow or keyboardUpdateViewportHeight as * the callback depending on whether the event was triggered by a focusin or * an orientationchange. */ function keyboardNativeShow(e) { clearTimeout(keyboardFocusOutTimer); //console.log("keyboardNativeShow fired at: " + Date.now()); //console.log("keyboardNativeshow window.innerHeight: " + window.innerHeight); if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) { ionic.keyboard.isOpening = true; ionic.keyboard.isClosing = false; } ionic.keyboard.height = e.keyboardHeight; //console.log('nativeshow keyboard height:' + e.keyboardHeight); if (wasOrientationChange) { keyboardWaitForResize(keyboardUpdateViewportHeight, true); } else { keyboardWaitForResize(keyboardShow, true); } } /** * Event handler for 'focusin' and 'ionic.focusin' events. Initializes * keyboard state (keyboardActiveElement and keyboard.isOpening) for the * appropriate adjustments once the window has resized. If not using the * keyboard plugin, calls keyboardWaitForResize with keyboardShow as the * callback or keyboardShow right away if the keyboard is already open. If * using the keyboard plugin does nothing and lets keyboardNativeShow handle * adjustments with a more accurate keyboard height. */ function keyboardFocusIn(e) { clearTimeout(keyboardFocusOutTimer); //console.log("keyboardFocusIn from: " + e.type + " at: " + Date.now()); if (!e.target || e.target.readOnly || !ionic.tap.isKeyboardElement(e.target) || !(scrollView = ionic.DomUtil.getParentWithClass(e.target, SCROLL_CONTAINER_CSS))) { if (keyboardActiveElement) { lastKeyboardActiveElement = keyboardActiveElement; } keyboardActiveElement = null; return; } keyboardActiveElement = e.target; // if using JS scrolling, undo the effects of native overflow scroll so the // scroll view is positioned correctly if (!scrollView.classList.contains("overflow-scroll")) { document.body.scrollTop = 0; scrollView.scrollTop = 0; ionic.requestAnimationFrame(function(){ document.body.scrollTop = 0; scrollView.scrollTop = 0; }); // any showing part of the document that isn't within the scroll the user // could touchmove and cause some ugly changes to the app, so disable // any touchmove events while the keyboard is open using e.preventDefault() if (window.navigator.msPointerEnabled) { document.addEventListener("MSPointerMove", keyboardPreventDefault, false); } else { document.addEventListener('touchmove', keyboardPreventDefault, false); } } if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) { ionic.keyboard.isOpening = true; ionic.keyboard.isClosing = false; } // attempt to prevent browser from natively scrolling input into view while // we are trying to do the same (while we are scrolling) if the user taps the // keyboard document.addEventListener('keydown', keyboardOnKeyDown, false); // if we aren't using the plugin and the keyboard isn't open yet, wait for the // window to resize so we can get an accurate estimate of the keyboard size, // otherwise we do nothing and let nativeShow call keyboardShow once we have // an exact keyboard height // if the keyboard is already open, go ahead and scroll the input into view // if necessary if (!ionic.keyboard.isOpen && !keyboardHasPlugin()) { keyboardWaitForResize(keyboardShow, true); } else if (ionic.keyboard.isOpen) { keyboardShow(); } } /** * Event handler for 'focusout' events. Sets keyboard.isClosing to true and * calls keyboardWaitForResize with keyboardHide as the callback after a small * timeout. */ function keyboardFocusOut() { clearTimeout(keyboardFocusOutTimer); //console.log("keyboardFocusOut fired at: " + Date.now()); //console.log("keyboardFocusOut event type: " + e.type); if (ionic.keyboard.isOpen || ionic.keyboard.isOpening) { ionic.keyboard.isClosing = true; ionic.keyboard.isOpening = false; } // Call keyboardHide with a slight delay because sometimes on focus or // orientation change focusin is called immediately after, so we give it time // to cancel keyboardHide keyboardFocusOutTimer = setTimeout(function() { ionic.requestAnimationFrame(function() { // focusOut during or right after an orientationchange, so we didn't get // a chance to update the viewport height yet, do it and keyboardHide //console.log("focusOut, wasOrientationChange: " + wasOrientationChange); if (wasOrientationChange) { keyboardWaitForResize(function(){ keyboardUpdateViewportHeight(); keyboardHide(); }, false); } else { keyboardWaitForResize(keyboardHide, false); } }); }, 50); } /** * Event handler for 'orientationchange' events. If using the keyboard plugin * and the keyboard is open on Android, sets wasOrientationChange to true so * nativeShow can update the viewport height with an accurate keyboard height. * If the keyboard isn't open or keyboard plugin isn't being used, * waits for the window to resize before updating the viewport height. * * On iOS, where orientationchange fires after the keyboard has already shown, * updates the viewport immediately, regardless of if the keyboard is already * open. */ function keyboardOrientationChange() { //console.log("orientationchange fired at: " + Date.now()); //console.log("orientation was: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait")); // toggle orientation ionic.keyboard.isLandscape = !ionic.keyboard.isLandscape; // //console.log("now orientation is: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait")); // no need to wait for resizing on iOS, and orientationchange always fires // after the keyboard has opened, so it doesn't matter if it's open or not if (ionic.Platform.isIOS()) { keyboardUpdateViewportHeight(); } // On Android, if the keyboard isn't open or we aren't using the keyboard // plugin, update the viewport height once everything has resized. If the // keyboard is open and we are using the keyboard plugin do nothing and let // nativeShow handle it using an accurate keyboard height. if ( ionic.Platform.isAndroid()) { if (!ionic.keyboard.isOpen || !keyboardHasPlugin()) { keyboardWaitForResize(keyboardUpdateViewportHeight, false); } else { wasOrientationChange = true; } } } /** * Event handler for 'keydown' event. Tries to prevent browser from natively * scrolling an input into view when a user taps the keyboard while we are * scrolling the input into view ourselves with JS. */ function keyboardOnKeyDown(e) { if (ionic.scroll.isScrolling) { keyboardPreventDefault(e); } } /** * Event for 'touchmove' or 'MSPointerMove'. Prevents native scrolling on * elements outside the scroll view while the keyboard is open. */ function keyboardPreventDefault(e) { if (e.target.tagName !== 'TEXTAREA') { e.preventDefault(); } } /* Private API */ /* -------------------------------------------------------------------------- */ /** * Polls window.innerHeight until it has updated to an expected value (or * sufficient time has passed) before calling the specified callback function. * Only necessary for non-fullscreen Android which sometimes reports multiple * window.innerHeight values during interim layouts while it is resizing. * * On iOS, the window.innerHeight will already be updated, but we use the 50ms * delay as essentially a timeout so that scroll view adjustments happen after * the keyboard has shown so there isn't a white flash from us resizing too * quickly. * * @param {Function} callback the function to call once the window has resized * @param {boolean} isOpening whether the resize is from the keyboard opening * or not */ function keyboardWaitForResize(callback, isOpening) { clearInterval(waitForResizeTimer); var count = 0; var maxCount; var initialHeight = getViewportHeight(); var viewportHeight = initialHeight; //console.log("waitForResize initial viewport height: " + viewportHeight); //var start = Date.now(); //console.log("start: " + start); // want to fail relatively quickly on modern android devices, since it's much // more likely we just have a bad keyboard height if (ionic.Platform.isAndroid() && ionic.Platform.version() < 4.4) { maxCount = 30; } else if (ionic.Platform.isAndroid()) { maxCount = 10; } else { maxCount = 1; } // poll timer waitForResizeTimer = setInterval(function(){ viewportHeight = getViewportHeight(); // height hasn't updated yet, try again in 50ms // if not using plugin, wait for maxCount to ensure we have waited long enough // to get an accurate keyboard height if (++count < maxCount && ((!isPortraitViewportHeight(viewportHeight) && !isLandscapeViewportHeight(viewportHeight)) || !ionic.keyboard.height)) { return; } // infer the keyboard height from the resize if not using the keyboard plugin if (!keyboardHasPlugin()) { ionic.keyboard.height = Math.abs(initialHeight - window.innerHeight); } // set to true if we were waiting for the keyboard to open ionic.keyboard.isOpen = isOpening; clearInterval(waitForResizeTimer); //var end = Date.now(); //console.log("waitForResize count: " + count); //console.log("end: " + end); //console.log("difference: " + ( end - start ) + "ms"); //console.log("callback: " + callback.name); callback(); }, 50); return maxCount; //for tests } /** * On keyboard close sets keyboard state to closed, resets the scroll view, * removes CSS from body indicating keyboard was open, removes any event * listeners for when the keyboard is open and on Android blurs the active * element (which in some cases will still have focus even if the keyboard * is closed and can cause it to reappear on subsequent taps). */ function keyboardHide() { clearTimeout(keyboardFocusOutTimer); //console.log("keyboardHide"); ionic.keyboard.isOpen = false; ionic.keyboard.isClosing = false; if (keyboardActiveElement || lastKeyboardActiveElement) { ionic.trigger('resetScrollView', { target: keyboardActiveElement || lastKeyboardActiveElement }, true); } ionic.requestAnimationFrame(function(){ document.body.classList.remove(KEYBOARD_OPEN_CSS); }); // the keyboard is gone now, remove the touchmove that disables native scroll if (window.navigator.msPointerEnabled) { document.removeEventListener("MSPointerMove", keyboardPreventDefault); } else { document.removeEventListener('touchmove', keyboardPreventDefault); } document.removeEventListener('keydown', keyboardOnKeyDown); if (ionic.Platform.isAndroid()) { // on android closing the keyboard with the back/dismiss button won't remove // focus and keyboard can re-appear on subsequent taps (like scrolling) if (keyboardHasPlugin()) cordova.plugins.Keyboard.close(); keyboardActiveElement && keyboardActiveElement.blur(); } keyboardActiveElement = null; lastKeyboardActiveElement = null; } /** * On keyboard open sets keyboard state to open, adds CSS to the body * indicating the keyboard is open and tells the scroll view to resize and * the currently focused input into view if necessary. */ function keyboardShow() { ionic.keyboard.isOpen = true; ionic.keyboard.isOpening = false; var details = { keyboardHeight: keyboardGetHeight(), viewportHeight: keyboardCurrentViewportHeight }; if (keyboardActiveElement) { details.target = keyboardActiveElement; var elementBounds = keyboardActiveElement.getBoundingClientRect(); details.elementTop = Math.round(elementBounds.top); details.elementBottom = Math.round(elementBounds.bottom); details.windowHeight = details.viewportHeight - details.keyboardHeight; //console.log("keyboardShow viewportHeight: " + details.viewportHeight + //", windowHeight: " + details.windowHeight + //", keyboardHeight: " + details.keyboardHeight); // figure out if the element is under the keyboard details.isElementUnderKeyboard = (details.elementBottom > details.windowHeight); //console.log("isUnderKeyboard: " + details.isElementUnderKeyboard); //console.log("elementBottom: " + details.elementBottom); // send event so the scroll view adjusts ionic.trigger('scrollChildIntoView', details, true); } setTimeout(function(){ document.body.classList.add(KEYBOARD_OPEN_CSS); }, 400); return details; //for testing } /* eslint no-unused-vars:0 */ function keyboardGetHeight() { // check if we already have a keyboard height from the plugin or resize calculations if (ionic.keyboard.height) { return ionic.keyboard.height; } if (ionic.Platform.isAndroid()) { // should be using the plugin, no way to know how big the keyboard is, so guess if ( ionic.Platform.isFullScreen ) { return 275; } // otherwise just calculate it var contentHeight = window.innerHeight; if (contentHeight < keyboardCurrentViewportHeight) { return keyboardCurrentViewportHeight - contentHeight; } else { return 0; } } // fallback for when it's the webview without the plugin // or for just the standard web browser // TODO: have these be based on device if (ionic.Platform.isIOS()) { if (ionic.keyboard.isLandscape) { return 206; } if (!ionic.Platform.isWebView()) { return 216; } return 260; } // safe guess return 275; } function isPortraitViewportHeight(viewportHeight) { return !!(!ionic.keyboard.isLandscape && keyboardPortraitViewportHeight && (Math.abs(keyboardPortraitViewportHeight - viewportHeight) < 2)); } function isLandscapeViewportHeight(viewportHeight) { return !!(ionic.keyboard.isLandscape && keyboardLandscapeViewportHeight && (Math.abs(keyboardLandscapeViewportHeight - viewportHeight) < 2)); } function keyboardUpdateViewportHeight() { wasOrientationChange = false; keyboardCurrentViewportHeight = getViewportHeight(); if (ionic.keyboard.isLandscape && !keyboardLandscapeViewportHeight) { //console.log("saved landscape: " + keyboardCurrentViewportHeight); keyboardLandscapeViewportHeight = keyboardCurrentViewportHeight; } else if (!ionic.keyboard.isLandscape && !keyboardPortraitViewportHeight) { //console.log("saved portrait: " + keyboardCurrentViewportHeight); keyboardPortraitViewportHeight = keyboardCurrentViewportHeight; } if (keyboardActiveElement) { ionic.trigger('resetScrollView', { target: keyboardActiveElement }, true); } if (ionic.keyboard.isOpen && ionic.tap.isTextInput(keyboardActiveElement)) { keyboardShow(); } } function keyboardInitViewportHeight() { var viewportHeight = getViewportHeight(); //console.log("Keyboard init VP: " + viewportHeight + " " + window.innerWidth); // can't just use window.innerHeight in case the keyboard is opened immediately if ((viewportHeight / window.innerWidth) < 1) { ionic.keyboard.isLandscape = true; } //console.log("ionic.keyboard.isLandscape is: " + ionic.keyboard.isLandscape); // initialize or update the current viewport height values keyboardCurrentViewportHeight = viewportHeight; if (ionic.keyboard.isLandscape && !keyboardLandscapeViewportHeight) { keyboardLandscapeViewportHeight = keyboardCurrentViewportHeight; } else if (!ionic.keyboard.isLandscape && !keyboardPortraitViewportHeight) { keyboardPortraitViewportHeight = keyboardCurrentViewportHeight; } } function getViewportHeight() { var windowHeight = window.innerHeight; //console.log('window.innerHeight is: ' + windowHeight); //console.log('kb height is: ' + ionic.keyboard.height); //console.log('kb isOpen: ' + ionic.keyboard.isOpen); //TODO: add iPad undocked/split kb once kb plugin supports it // the keyboard overlays the window on Android fullscreen if (!(ionic.Platform.isAndroid() && ionic.Platform.isFullScreen) && (ionic.keyboard.isOpen || ionic.keyboard.isOpening) && !ionic.keyboard.isClosing) { return windowHeight + keyboardGetHeight(); } return windowHeight; } function keyboardHasPlugin() { return !!(window.cordova && cordova.plugins && cordova.plugins.Keyboard); } ionic.Platform.ready(function() { keyboardInitViewportHeight(); window.addEventListener('orientationchange', keyboardOrientationChange); // if orientation changes while app is in background, update on resuming /* if ( ionic.Platform.isWebView() ) { document.addEventListener('resume', keyboardInitViewportHeight); if (ionic.Platform.isAndroid()) { //TODO: onbackpressed to detect keyboard close without focusout or plugin } } */ // if orientation changes while app is in background, update on resuming /* if ( ionic.Platform.isWebView() ) { document.addEventListener('pause', function() { window.removeEventListener('orientationchange', keyboardOrientationChange); }) document.addEventListener('resume', function() { keyboardInitViewportHeight(); window.addEventListener('orientationchange', keyboardOrientationChange) }); }*/ // Android sometimes reports bad innerHeight on window.load // try it again in a lil bit to play it safe setTimeout(keyboardInitViewportHeight, 999); // only initialize the adjustments for the virtual keyboard // if a touchstart event happens if (window.navigator.msPointerEnabled) { document.addEventListener("MSPointerDown", keyboardInit, false); } else { document.addEventListener('touchstart', keyboardInit, false); } }); var viewportTag; var viewportProperties = {}; ionic.viewport = { orientation: function() { // 0 = Portrait // 90 = Landscape // not using window.orientation because each device has a different implementation return (window.innerWidth > window.innerHeight ? 90 : 0); } }; function viewportLoadTag() { var x; for (x = 0; x < document.head.children.length; x++) { if (document.head.children[x].name == 'viewport') { viewportTag = document.head.children[x]; break; } } if (viewportTag) { var props = viewportTag.content.toLowerCase().replace(/\s+/g, '').split(','); var keyValue; for (x = 0; x < props.length; x++) { if (props[x]) { keyValue = props[x].split('='); viewportProperties[ keyValue[0] ] = (keyValue.length > 1 ? keyValue[1] : '_'); } } viewportUpdate(); } } function viewportUpdate() { // unit tests in viewport.unit.js var initWidth = viewportProperties.width; var initHeight = viewportProperties.height; var p = ionic.Platform; var version = p.version(); var DEVICE_WIDTH = 'device-width'; var DEVICE_HEIGHT = 'device-height'; var orientation = ionic.viewport.orientation(); // Most times we're removing the height and adding the width // So this is the default to start with, then modify per platform/version/oreintation delete viewportProperties.height; viewportProperties.width = DEVICE_WIDTH; if (p.isIPad()) { // iPad if (version > 7) { // iPad >= 7.1 // https://issues.apache.org/jira/browse/CB-4323 delete viewportProperties.width; } else { // iPad <= 7.0 if (p.isWebView()) { // iPad <= 7.0 WebView if (orientation == 90) { // iPad <= 7.0 WebView Landscape viewportProperties.height = '0'; } else if (version == 7) { // iPad <= 7.0 WebView Portait viewportProperties.height = DEVICE_HEIGHT; } } else { // iPad <= 6.1 Browser if (version < 7) { viewportProperties.height = '0'; } } } } else if (p.isIOS()) { // iPhone if (p.isWebView()) { // iPhone WebView if (version > 7) { // iPhone >= 7.1 WebView delete viewportProperties.width; } else if (version < 7) { // iPhone <= 6.1 WebView // if height was set it needs to get removed with this hack for <= 6.1 if (initHeight) viewportProperties.height = '0'; } else if (version == 7) { //iPhone == 7.0 WebView viewportProperties.height = DEVICE_HEIGHT; } } else { // iPhone Browser if (version < 7) { // iPhone <= 6.1 Browser // if height was set it needs to get removed with this hack for <= 6.1 if (initHeight) viewportProperties.height = '0'; } } } // only update the viewport tag if there was a change if (initWidth !== viewportProperties.width || initHeight !== viewportProperties.height) { viewportTagUpdate(); } } function viewportTagUpdate() { var key, props = []; for (key in viewportProperties) { if (viewportProperties[key]) { props.push(key + (viewportProperties[key] == '_' ? '' : '=' + viewportProperties[key])); } } viewportTag.content = props.join(', '); } ionic.Platform.ready(function() { viewportLoadTag(); window.addEventListener("orientationchange", function() { setTimeout(viewportUpdate, 1000); }, false); }); (function(ionic) { 'use strict'; ionic.views.View = function() { this.initialize.apply(this, arguments); }; ionic.views.View.inherit = ionic.inherit; ionic.extend(ionic.views.View.prototype, { initialize: function() {} }); })(window.ionic); /* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ /* jshint eqnull: true */ /** * Generic animation class with support for dropped frames both optional easing and duration. * * Optional duration is useful when the lifetime is defined by another condition than time * e.g. speed of an animating object, etc. * * Dropped frame logic allows to keep using the same updater logic independent from the actual * rendering. This eases a lot of cases where it might be pretty complex to break down a state * based on the pure time difference. */ var zyngaCore = { effect: {} }; (function(global) { var time = Date.now || function() { return +new Date(); }; var desiredFrames = 60; var millisecondsPerSecond = 1000; var running = {}; var counter = 1; zyngaCore.effect.Animate = { /** * A requestAnimationFrame wrapper / polyfill. * * @param callback {Function} The callback to be invoked before the next repaint. * @param root {HTMLElement} The root element for the repaint */ requestAnimationFrame: (function() { // Check for request animation Frame support var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame; var isNative = !!requestFrame; if (requestFrame && !/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(requestFrame.toString())) { isNative = false; } if (isNative) { return function(callback, root) { requestFrame(callback, root); }; } var TARGET_FPS = 60; var requests = {}; var requestCount = 0; var rafHandle = 1; var intervalHandle = null; var lastActive = +new Date(); return function(callback) { var callbackHandle = rafHandle++; // Store callback requests[callbackHandle] = callback; requestCount++; // Create timeout at first request if (intervalHandle === null) { intervalHandle = setInterval(function() { var time = +new Date(); var currentRequests = requests; // Reset data structure before executing callbacks requests = {}; requestCount = 0; for(var key in currentRequests) { if (currentRequests.hasOwnProperty(key)) { currentRequests[key](time); lastActive = time; } } // Disable the timeout when nothing happens for a certain // period of time if (time - lastActive > 2500) { clearInterval(intervalHandle); intervalHandle = null; } }, 1000 / TARGET_FPS); } return callbackHandle; }; })(), /** * Stops the given animation. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation was stopped (aka, was running before) */ stop: function(id) { var cleared = running[id] != null; if (cleared) { running[id] = null; } return cleared; }, /** * Whether the given animation is still running. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation is still running */ isRunning: function(id) { return running[id] != null; }, /** * Start the animation. * * @param stepCallback {Function} Pointer to function which is executed on every step. * Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }` * @param verifyCallback {Function} Executed before every animation step. * Signature of the method should be `function() { return continueWithAnimation; }` * @param completedCallback {Function} * Signature of the method should be `function(droppedFrames, finishedAnimation) {}` * @param duration {Integer} Milliseconds to run the animation * @param easingMethod {Function} Pointer to easing function * Signature of the method should be `function(percent) { return modifiedValue; }` * @param root {Element} Render root, when available. Used for internal * usage of requestAnimationFrame. * @return {Integer} Identifier of animation. Can be used to stop it any time. */ start: function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) { var start = time(); var lastFrame = start; var percent = 0; var dropCounter = 0; var id = counter++; if (!root) { root = document.body; } // Compacting running db automatically every few new animations if (id % 20 === 0) { var newRunning = {}; for (var usedId in running) { newRunning[usedId] = true; } running = newRunning; } // This is the internal step method which is called every few milliseconds var step = function(virtual) { // Normalize virtual value var render = virtual !== true; // Get current time var now = time(); // Verification is executed before next animation step if (!running[id] || (verifyCallback && !verifyCallback(id))) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false); return; } // For the current rendering to apply let's update omitted steps in memory. // This is important to bring internal state variables up-to-date with progress in time. if (render) { var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1; for (var j = 0; j < Math.min(droppedFrames, 4); j++) { step(true); dropCounter++; } } // Compute percent value if (duration) { percent = (now - start) / duration; if (percent > 1) { percent = 1; } } // Execute step callback, then... var value = easingMethod ? easingMethod(percent) : percent; if ((stepCallback(value, now, render) === false || percent === 1) && render) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null); } else if (render) { lastFrame = now; zyngaCore.effect.Animate.requestAnimationFrame(step, root); } }; // Mark as running running[id] = true; // Init first step zyngaCore.effect.Animate.requestAnimationFrame(step, root); // Return unique animation ID return id; } }; })(window); /* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ (function(ionic) { var NOOP = function(){}; // Easing Equations (c) 2003 Robert Penner, all rights reserved. // Open source under the BSD License. /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeOutCubic = function(pos) { return (Math.pow((pos - 1), 3) + 1); }; /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeInOutCubic = function(pos) { if ((pos /= 0.5) < 1) { return 0.5 * Math.pow(pos, 3); } return 0.5 * (Math.pow((pos - 2), 3) + 2); }; /** * ionic.views.Scroll * A powerful scroll view with support for bouncing, pull to refresh, and paging. * @param {Object} options options for the scroll view * @class A scroll view system * @memberof ionic.views */ ionic.views.Scroll = ionic.views.View.inherit({ initialize: function(options) { var self = this; self.__container = options.el; self.__content = options.el.firstElementChild; //Remove any scrollTop attached to these elements; they are virtual scroll now //This also stops on-load-scroll-to-window.location.hash that the browser does setTimeout(function() { if (self.__container && self.__content) { self.__container.scrollTop = 0; self.__content.scrollTop = 0; } }); self.options = { /** Disable scrolling on x-axis by default */ scrollingX: false, scrollbarX: true, /** Enable scrolling on y-axis */ scrollingY: true, scrollbarY: true, startX: 0, startY: 0, /** The amount to dampen mousewheel events */ wheelDampen: 6, /** The minimum size the scrollbars scale to while scrolling */ minScrollbarSizeX: 5, minScrollbarSizeY: 5, /** Scrollbar fading after scrolling */ scrollbarsFade: true, scrollbarFadeDelay: 300, /** The initial fade delay when the pane is resized or initialized */ scrollbarResizeFadeDelay: 1000, /** Enable animations for deceleration, snap back, zooming and scrolling */ animating: true, /** duration for animations triggered by scrollTo/zoomTo */ animationDuration: 250, /** The velocity required to make the scroll view "slide" after touchend */ decelVelocityThreshold: 4, /** The velocity required to make the scroll view "slide" after touchend when using paging */ decelVelocityThresholdPaging: 4, /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */ bouncing: true, /** Enable locking to the main axis if user moves only slightly on one of them at start */ locking: true, /** Enable pagination mode (switching between full page content panes) */ paging: false, /** Enable snapping of content to a configured pixel grid */ snapping: false, /** Enable zooming of content via API, fingers and mouse wheel */ zooming: false, /** Minimum zoom level */ minZoom: 0.5, /** Maximum zoom level */ maxZoom: 3, /** Multiply or decrease scrolling speed **/ speedMultiplier: 1, deceleration: 0.97, /** Whether to prevent default on a scroll operation to capture drag events **/ preventDefault: false, /** Callback that is fired on the later of touch end or deceleration end, provided that another scrolling action has not begun. Used to know when to fade out a scrollbar. */ scrollingComplete: NOOP, /** This configures the amount of change applied to deceleration when reaching boundaries **/ penetrationDeceleration: 0.03, /** This configures the amount of change applied to acceleration when reaching boundaries **/ penetrationAcceleration: 0.08, // The ms interval for triggering scroll events scrollEventInterval: 10, freeze: false, getContentWidth: function() { return Math.max(self.__content.scrollWidth, self.__content.offsetWidth); }, getContentHeight: function() { return Math.max(self.__content.scrollHeight, self.__content.offsetHeight + (self.__content.offsetTop * 2)); } }; for (var key in options) { self.options[key] = options[key]; } self.hintResize = ionic.debounce(function() { self.resize(); }, 1000, true); self.onScroll = function() { if (!ionic.scroll.isScrolling) { setTimeout(self.setScrollStart, 50); } else { clearTimeout(self.scrollTimer); self.scrollTimer = setTimeout(self.setScrollStop, 80); } }; self.freeze = function(shouldFreeze) { if (arguments.length) { self.options.freeze = shouldFreeze; } return self.options.freeze; }; // We can just use the standard freeze pop in our mouth self.freezeShut = self.freeze; self.setScrollStart = function() { ionic.scroll.isScrolling = Math.abs(ionic.scroll.lastTop - self.__scrollTop) > 1; clearTimeout(self.scrollTimer); self.scrollTimer = setTimeout(self.setScrollStop, 80); }; self.setScrollStop = function() { ionic.scroll.isScrolling = false; ionic.scroll.lastTop = self.__scrollTop; }; self.triggerScrollEvent = ionic.throttle(function() { self.onScroll(); ionic.trigger('scroll', { scrollTop: self.__scrollTop, scrollLeft: self.__scrollLeft, target: self.__container }); }, self.options.scrollEventInterval); self.triggerScrollEndEvent = function() { ionic.trigger('scrollend', { scrollTop: self.__scrollTop, scrollLeft: self.__scrollLeft, target: self.__container }); }; self.__scrollLeft = self.options.startX; self.__scrollTop = self.options.startY; // Get the render update function, initialize event handlers, // and calculate the size of the scroll container self.__callback = self.getRenderFn(); self.__initEventHandlers(); self.__createScrollbars(); }, run: function() { this.resize(); // Fade them out this.__fadeScrollbars('out', this.options.scrollbarResizeFadeDelay); }, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: STATUS --------------------------------------------------------------------------- */ /** Whether only a single finger is used in touch handling */ __isSingleTouch: false, /** Whether a touch event sequence is in progress */ __isTracking: false, /** Whether a deceleration animation went to completion. */ __didDecelerationComplete: false, /** * Whether a gesture zoom/rotate event is in progress. Activates when * a gesturestart event happens. This has higher priority than dragging. */ __isGesturing: false, /** * Whether the user has moved by such a distance that we have enabled * dragging mode. Hint: It's only enabled after some pixels of movement to * not interrupt with clicks etc. */ __isDragging: false, /** * Not touching and dragging anymore, and smoothly animating the * touch sequence using deceleration. */ __isDecelerating: false, /** * Smoothly animating the currently configured change */ __isAnimating: false, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DIMENSIONS --------------------------------------------------------------------------- */ /** Available outer left position (from document perspective) */ __clientLeft: 0, /** Available outer top position (from document perspective) */ __clientTop: 0, /** Available outer width */ __clientWidth: 0, /** Available outer height */ __clientHeight: 0, /** Outer width of content */ __contentWidth: 0, /** Outer height of content */ __contentHeight: 0, /** Snapping width for content */ __snapWidth: 100, /** Snapping height for content */ __snapHeight: 100, /** Height to assign to refresh area */ __refreshHeight: null, /** Whether the refresh process is enabled when the event is released now */ __refreshActive: false, /** Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */ __refreshActivate: null, /** Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */ __refreshDeactivate: null, /** Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */ __refreshStart: null, /** Zoom level */ __zoomLevel: 1, /** Scroll position on x-axis */ __scrollLeft: 0, /** Scroll position on y-axis */ __scrollTop: 0, /** Maximum allowed scroll position on x-axis */ __maxScrollLeft: 0, /** Maximum allowed scroll position on y-axis */ __maxScrollTop: 0, /* Scheduled left position (final position when animating) */ __scheduledLeft: 0, /* Scheduled top position (final position when animating) */ __scheduledTop: 0, /* Scheduled zoom level (final scale when animating) */ __scheduledZoom: 0, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: LAST POSITIONS --------------------------------------------------------------------------- */ /** Left position of finger at start */ __lastTouchLeft: null, /** Top position of finger at start */ __lastTouchTop: null, /** Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */ __lastTouchMove: null, /** List of positions, uses three indexes for each state: left, top, timestamp */ __positions: null, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DECELERATION SUPPORT --------------------------------------------------------------------------- */ /** Minimum left scroll position during deceleration */ __minDecelerationScrollLeft: null, /** Minimum top scroll position during deceleration */ __minDecelerationScrollTop: null, /** Maximum left scroll position during deceleration */ __maxDecelerationScrollLeft: null, /** Maximum top scroll position during deceleration */ __maxDecelerationScrollTop: null, /** Current factor to modify horizontal scroll position with on every step */ __decelerationVelocityX: null, /** Current factor to modify vertical scroll position with on every step */ __decelerationVelocityY: null, /** the browser-specific property to use for transforms */ __transformProperty: null, __perspectiveProperty: null, /** scrollbar indicators */ __indicatorX: null, __indicatorY: null, /** Timeout for scrollbar fading */ __scrollbarFadeTimeout: null, /** whether we've tried to wait for size already */ __didWaitForSize: null, __sizerTimeout: null, __initEventHandlers: function() { var self = this; // Event Handler var container = self.__container; // save height when scroll view is shrunk so we don't need to reflow var scrollViewOffsetHeight; /** * Shrink the scroll view when the keyboard is up if necessary and if the * focused input is below the bottom of the shrunk scroll view, scroll it * into view. */ self.scrollChildIntoView = function(e) { //console.log("scrollChildIntoView at: " + Date.now()); // D var scrollBottomOffsetToTop = container.getBoundingClientRect().bottom; // D - A scrollViewOffsetHeight = container.offsetHeight; var alreadyShrunk = self.isShrunkForKeyboard; var isModal = container.parentNode.classList.contains('modal'); // 680px is when the media query for 60% modal width kicks in var isInsetModal = isModal && window.innerWidth >= 680; /* * _______ * |---A---| <- top of scroll view * | | * |---B---| <- keyboard * | C | <- input * |---D---| <- initial bottom of scroll view * |___E___| <- bottom of viewport * * All commented calculations relative to the top of the viewport (ie E * is the viewport height, not 0) */ if (!alreadyShrunk) { // shrink scrollview so we can actually scroll if the input is hidden // if it isn't shrink so we can scroll to inputs under the keyboard // inset modals won't shrink on Android on their own when the keyboard appears if ( ionic.Platform.isIOS() || ionic.Platform.isFullScreen || isInsetModal ) { // if there are things below the scroll view account for them and // subtract them from the keyboard height when resizing // E - D E D var scrollBottomOffsetToBottom = e.detail.viewportHeight - scrollBottomOffsetToTop; // 0 or D - B if D > B E - B E - D var keyboardOffset = Math.max(0, e.detail.keyboardHeight - scrollBottomOffsetToBottom); ionic.requestAnimationFrame(function(){ // D - A or B - A if D > B D - A max(0, D - B) scrollViewOffsetHeight = scrollViewOffsetHeight - keyboardOffset; container.style.height = scrollViewOffsetHeight + "px"; container.style.overflow = "visible"; //update scroll view self.resize(); }); } self.isShrunkForKeyboard = true; } /* * _______ * |---A---| <- top of scroll view * | * | <- where we want to scroll to * |--B-D--| <- keyboard, bottom of scroll view * | C | <- input * | | * |___E___| <- bottom of viewport * * All commented calculations relative to the top of the viewport (ie E * is the viewport height, not 0) */ // if the element is positioned under the keyboard scroll it into view if (e.detail.isElementUnderKeyboard) { ionic.requestAnimationFrame(function(){ container.scrollTop = 0; // update D if we shrunk if (self.isShrunkForKeyboard && !alreadyShrunk) { scrollBottomOffsetToTop = container.getBoundingClientRect().bottom; } // middle of the scrollview, this is where we want to scroll to // (D - A) / 2 var scrollMidpointOffset = scrollViewOffsetHeight * 0.5; //console.log("container.offsetHeight: " + scrollViewOffsetHeight); // middle of the input we want to scroll into view // C var inputMidpoint = ((e.detail.elementBottom + e.detail.elementTop) / 2); // distance from middle of input to the bottom of the scroll view // C - D C D var inputMidpointOffsetToScrollBottom = inputMidpoint - scrollBottomOffsetToTop; //C - D + (D - A)/2 C - D (D - A)/ 2 var scrollTop = inputMidpointOffsetToScrollBottom + scrollMidpointOffset; if ( scrollTop > 0) { if (ionic.Platform.isIOS()) ionic.tap.cloneFocusedInput(container, self); self.scrollBy(0, scrollTop, true); self.onScroll(); } }); } // Only the first scrollView parent of the element that broadcasted this event // (the active element that needs to be shown) should receive this event e.stopPropagation(); }; self.resetScrollView = function() { //return scrollview to original height once keyboard has hidden if ( self.isShrunkForKeyboard ) { self.isShrunkForKeyboard = false; container.style.height = ""; container.style.overflow = ""; } self.resize(); }; //Broadcasted when keyboard is shown on some platforms. //See js/utils/keyboard.js container.addEventListener('scrollChildIntoView', self.scrollChildIntoView); // Listen on document because container may not have had the last // keyboardActiveElement, for example after closing a modal with a focused // input and returning to a previously resized scroll view in an ion-content. // Since we can only resize scroll views that are currently visible, just resize // the current scroll view when the keyboard is closed. document.addEventListener('resetScrollView', self.resetScrollView); function getEventTouches(e) { return e.touches && e.touches.length ? e.touches : [{ pageX: e.pageX, pageY: e.pageY }]; } self.touchStart = function(e) { self.startCoordinates = ionic.tap.pointerCoord(e); if ( ionic.tap.ignoreScrollStart(e) ) { return; } self.__isDown = true; if ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) { // do not start if the target is a text input // if there is a touchmove on this input, then we can start the scroll self.__hasStarted = false; return; } self.__isSelectable = true; self.__enableScrollY = true; self.__hasStarted = true; self.doTouchStart(getEventTouches(e), e.timeStamp); e.preventDefault(); }; self.touchMove = function(e) { if (self.options.freeze || !self.__isDown || (!self.__isDown && e.defaultPrevented) || (e.target.tagName === 'TEXTAREA' && e.target.parentElement.querySelector(':focus')) ) { return; } if ( !self.__hasStarted && ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) ) { // the target is a text input and scroll has started // since the text input doesn't start on touchStart, do it here self.__hasStarted = true; self.doTouchStart(getEventTouches(e), e.timeStamp); e.preventDefault(); return; } if (self.startCoordinates) { // we have start coordinates, so get this touch move's current coordinates var currentCoordinates = ionic.tap.pointerCoord(e); if ( self.__isSelectable && ionic.tap.isTextInput(e.target) && Math.abs(self.startCoordinates.x - currentCoordinates.x) > 20 ) { // user slid the text input's caret on its x axis, disable any future y scrolling self.__enableScrollY = false; self.__isSelectable = true; } if ( self.__enableScrollY && Math.abs(self.startCoordinates.y - currentCoordinates.y) > 10 ) { // user scrolled the entire view on the y axis // disabled being able to select text on an input // hide the input which has focus, and show a cloned one that doesn't have focus self.__isSelectable = false; ionic.tap.cloneFocusedInput(container, self); } } self.doTouchMove(getEventTouches(e), e.timeStamp, e.scale); self.__isDown = true; }; self.touchMoveBubble = function(e) { if(self.__isDown && self.options.preventDefault) { e.preventDefault(); } }; self.touchEnd = function(e) { if (!self.__isDown) return; self.doTouchEnd(e, e.timeStamp); self.__isDown = false; self.__hasStarted = false; self.__isSelectable = true; self.__enableScrollY = true; if ( !self.__isDragging && !self.__isDecelerating && !self.__isAnimating ) { ionic.tap.removeClonedInputs(container, self); } }; self.mouseWheel = ionic.animationFrameThrottle(function(e) { var scrollParent = ionic.DomUtil.getParentOrSelfWithClass(e.target, 'ionic-scroll'); if (!self.options.freeze && scrollParent === self.__container) { self.hintResize(); self.scrollBy( (e.wheelDeltaX || e.deltaX || 0) / self.options.wheelDampen, (-e.wheelDeltaY || e.deltaY || 0) / self.options.wheelDampen ); self.__fadeScrollbars('in'); clearTimeout(self.__wheelHideBarTimeout); self.__wheelHideBarTimeout = setTimeout(function() { self.__fadeScrollbars('out'); }, 100); } }); if ('ontouchstart' in window) { // Touch Events container.addEventListener("touchstart", self.touchStart, false); if(self.options.preventDefault) container.addEventListener("touchmove", self.touchMoveBubble, false); document.addEventListener("touchmove", self.touchMove, false); document.addEventListener("touchend", self.touchEnd, false); document.addEventListener("touchcancel", self.touchEnd, false); document.addEventListener("wheel", self.mouseWheel, false); } else if (window.navigator.pointerEnabled) { // Pointer Events container.addEventListener("pointerdown", self.touchStart, false); if(self.options.preventDefault) container.addEventListener("pointermove", self.touchMoveBubble, false); document.addEventListener("pointermove", self.touchMove, false); document.addEventListener("pointerup", self.touchEnd, false); document.addEventListener("pointercancel", self.touchEnd, false); document.addEventListener("wheel", self.mouseWheel, false); } else if (window.navigator.msPointerEnabled) { // IE10, WP8 (Pointer Events) container.addEventListener("MSPointerDown", self.touchStart, false); if(self.options.preventDefault) container.addEventListener("MSPointerMove", self.touchMoveBubble, false); document.addEventListener("MSPointerMove", self.touchMove, false); document.addEventListener("MSPointerUp", self.touchEnd, false); document.addEventListener("MSPointerCancel", self.touchEnd, false); document.addEventListener("wheel", self.mouseWheel, false); } else { // Mouse Events var mousedown = false; self.mouseDown = function(e) { if ( ionic.tap.ignoreScrollStart(e) || e.target.tagName === 'SELECT' ) { return; } self.doTouchStart(getEventTouches(e), e.timeStamp); if ( !ionic.tap.isTextInput(e.target) ) { e.preventDefault(); } mousedown = true; }; self.mouseMove = function(e) { if (self.options.freeze || !mousedown || (!mousedown && e.defaultPrevented)) { return; } self.doTouchMove(getEventTouches(e), e.timeStamp); mousedown = true; }; self.mouseMoveBubble = function(e) { if (mousedown && self.options.preventDefault) { e.preventDefault(); } }; self.mouseUp = function(e) { if (!mousedown) { return; } self.doTouchEnd(e, e.timeStamp); mousedown = false; }; container.addEventListener("mousedown", self.mouseDown, false); if(self.options.preventDefault) container.addEventListener("mousemove", self.mouseMoveBubble, false); document.addEventListener("mousemove", self.mouseMove, false); document.addEventListener("mouseup", self.mouseUp, false); document.addEventListener('mousewheel', self.mouseWheel, false); document.addEventListener('wheel', self.mouseWheel, false); } }, __cleanup: function() { var self = this; var container = self.__container; container.removeEventListener('touchstart', self.touchStart); container.removeEventListener('touchmove', self.touchMoveBubble); document.removeEventListener('touchmove', self.touchMove); document.removeEventListener('touchend', self.touchEnd); document.removeEventListener('touchcancel', self.touchEnd); container.removeEventListener("pointerdown", self.touchStart); container.removeEventListener("pointermove", self.touchMoveBubble); document.removeEventListener("pointermove", self.touchMove); document.removeEventListener("pointerup", self.touchEnd); document.removeEventListener("pointercancel", self.touchEnd); container.removeEventListener("MSPointerDown", self.touchStart); container.removeEventListener("MSPointerMove", self.touchMoveBubble); document.removeEventListener("MSPointerMove", self.touchMove); document.removeEventListener("MSPointerUp", self.touchEnd); document.removeEventListener("MSPointerCancel", self.touchEnd); container.removeEventListener("mousedown", self.mouseDown); container.removeEventListener("mousemove", self.mouseMoveBubble); document.removeEventListener("mousemove", self.mouseMove); document.removeEventListener("mouseup", self.mouseUp); document.removeEventListener('mousewheel', self.mouseWheel); document.removeEventListener('wheel', self.mouseWheel); container.removeEventListener('scrollChildIntoView', self.scrollChildIntoView); document.removeEventListener('resetScrollView', self.resetScrollView); ionic.tap.removeClonedInputs(container, self); delete self.__container; delete self.__content; delete self.__indicatorX; delete self.__indicatorY; delete self.options.el; self.__callback = self.scrollChildIntoView = self.resetScrollView = NOOP; self.mouseMove = self.mouseDown = self.mouseUp = self.mouseWheel = self.touchStart = self.touchMove = self.touchEnd = self.touchCancel = NOOP; self.resize = self.scrollTo = self.zoomTo = self.__scrollingComplete = NOOP; container = null; }, /** Create a scroll bar div with the given direction **/ __createScrollbar: function(direction) { var bar = document.createElement('div'), indicator = document.createElement('div'); indicator.className = 'scroll-bar-indicator scroll-bar-fade-out'; if (direction == 'h') { bar.className = 'scroll-bar scroll-bar-h'; } else { bar.className = 'scroll-bar scroll-bar-v'; } bar.appendChild(indicator); return bar; }, __createScrollbars: function() { var self = this; var indicatorX, indicatorY; if (self.options.scrollingX) { indicatorX = { el: self.__createScrollbar('h'), sizeRatio: 1 }; indicatorX.indicator = indicatorX.el.children[0]; if (self.options.scrollbarX) { self.__container.appendChild(indicatorX.el); } self.__indicatorX = indicatorX; } if (self.options.scrollingY) { indicatorY = { el: self.__createScrollbar('v'), sizeRatio: 1 }; indicatorY.indicator = indicatorY.el.children[0]; if (self.options.scrollbarY) { self.__container.appendChild(indicatorY.el); } self.__indicatorY = indicatorY; } }, __resizeScrollbars: function() { var self = this; // Update horiz bar if (self.__indicatorX) { var width = Math.max(Math.round(self.__clientWidth * self.__clientWidth / (self.__contentWidth)), 20); if (width > self.__contentWidth) { width = 0; } if (width !== self.__indicatorX.size) { ionic.requestAnimationFrame(function(){ self.__indicatorX.indicator.style.width = width + 'px'; }); } self.__indicatorX.size = width; self.__indicatorX.minScale = self.options.minScrollbarSizeX / width; self.__indicatorX.maxPos = self.__clientWidth - width; self.__indicatorX.sizeRatio = self.__maxScrollLeft ? self.__indicatorX.maxPos / self.__maxScrollLeft : 1; } // Update vert bar if (self.__indicatorY) { var height = Math.max(Math.round(self.__clientHeight * self.__clientHeight / (self.__contentHeight)), 20); if (height > self.__contentHeight) { height = 0; } if (height !== self.__indicatorY.size) { ionic.requestAnimationFrame(function(){ self.__indicatorY && (self.__indicatorY.indicator.style.height = height + 'px'); }); } self.__indicatorY.size = height; self.__indicatorY.minScale = self.options.minScrollbarSizeY / height; self.__indicatorY.maxPos = self.__clientHeight - height; self.__indicatorY.sizeRatio = self.__maxScrollTop ? self.__indicatorY.maxPos / self.__maxScrollTop : 1; } }, /** * Move and scale the scrollbars as the page scrolls. */ __repositionScrollbars: function() { var self = this, heightScale, widthScale, widthDiff, heightDiff, x, y, xstop = 0, ystop = 0; if (self.__indicatorX) { // Handle the X scrollbar // Don't go all the way to the right if we have a vertical scrollbar as well if (self.__indicatorY) xstop = 10; x = Math.round(self.__indicatorX.sizeRatio * self.__scrollLeft) || 0; // The the difference between the last content X position, and our overscrolled one widthDiff = self.__scrollLeft - (self.__maxScrollLeft - xstop); if (self.__scrollLeft < 0) { widthScale = Math.max(self.__indicatorX.minScale, (self.__indicatorX.size - Math.abs(self.__scrollLeft)) / self.__indicatorX.size); // Stay at left x = 0; // Make sure scale is transformed from the left/center origin point self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'left center'; } else if (widthDiff > 0) { widthScale = Math.max(self.__indicatorX.minScale, (self.__indicatorX.size - widthDiff) / self.__indicatorX.size); // Stay at the furthest x for the scrollable viewport x = self.__indicatorX.maxPos - xstop; // Make sure scale is transformed from the right/center origin point self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'right center'; } else { // Normal motion x = Math.min(self.__maxScrollLeft, Math.max(0, x)); widthScale = 1; } var translate3dX = 'translate3d(' + x + 'px, 0, 0) scaleX(' + widthScale + ')'; if (self.__indicatorX.transformProp !== translate3dX) { self.__indicatorX.indicator.style[self.__transformProperty] = translate3dX; self.__indicatorX.transformProp = translate3dX; } } if (self.__indicatorY) { y = Math.round(self.__indicatorY.sizeRatio * self.__scrollTop) || 0; // Don't go all the way to the right if we have a vertical scrollbar as well if (self.__indicatorX) ystop = 10; heightDiff = self.__scrollTop - (self.__maxScrollTop - ystop); if (self.__scrollTop < 0) { heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - Math.abs(self.__scrollTop)) / self.__indicatorY.size); // Stay at top y = 0; // Make sure scale is transformed from the center/top origin point if (self.__indicatorY.originProp !== 'center top') { self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center top'; self.__indicatorY.originProp = 'center top'; } } else if (heightDiff > 0) { heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - heightDiff) / self.__indicatorY.size); // Stay at bottom of scrollable viewport y = self.__indicatorY.maxPos - ystop; // Make sure scale is transformed from the center/bottom origin point if (self.__indicatorY.originProp !== 'center bottom') { self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center bottom'; self.__indicatorY.originProp = 'center bottom'; } } else { // Normal motion y = Math.min(self.__maxScrollTop, Math.max(0, y)); heightScale = 1; } var translate3dY = 'translate3d(0,' + y + 'px, 0) scaleY(' + heightScale + ')'; if (self.__indicatorY.transformProp !== translate3dY) { self.__indicatorY.indicator.style[self.__transformProperty] = translate3dY; self.__indicatorY.transformProp = translate3dY; } } }, __fadeScrollbars: function(direction, delay) { var self = this; if (!self.options.scrollbarsFade) { return; } var className = 'scroll-bar-fade-out'; if (self.options.scrollbarsFade === true) { clearTimeout(self.__scrollbarFadeTimeout); if (direction == 'in') { if (self.__indicatorX) { self.__indicatorX.indicator.classList.remove(className); } if (self.__indicatorY) { self.__indicatorY.indicator.classList.remove(className); } } else { self.__scrollbarFadeTimeout = setTimeout(function() { if (self.__indicatorX) { self.__indicatorX.indicator.classList.add(className); } if (self.__indicatorY) { self.__indicatorY.indicator.classList.add(className); } }, delay || self.options.scrollbarFadeDelay); } } }, __scrollingComplete: function() { this.options.scrollingComplete(); ionic.tap.removeClonedInputs(this.__container, this); this.__fadeScrollbars('out'); }, resize: function(continueScrolling) { var self = this; if (!self.__container || !self.options) return; // Update Scroller dimensions for changed content // Add padding to bottom of content self.setDimensions( self.__container.clientWidth, self.__container.clientHeight, self.options.getContentWidth(), self.options.getContentHeight(), continueScrolling ); }, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ getRenderFn: function() { var self = this; var content = self.__content; var docStyle = document.documentElement.style; var engine; if ('MozAppearance' in docStyle) { engine = 'gecko'; } else if ('WebkitAppearance' in docStyle) { engine = 'webkit'; } else if (typeof navigator.cpuClass === 'string') { engine = 'trident'; } var vendorPrefix = { trident: 'ms', gecko: 'Moz', webkit: 'Webkit', presto: 'O' }[engine]; var helperElem = document.createElement("div"); var undef; var perspectiveProperty = vendorPrefix + "Perspective"; var transformProperty = vendorPrefix + "Transform"; var transformOriginProperty = vendorPrefix + 'TransformOrigin'; self.__perspectiveProperty = transformProperty; self.__transformProperty = transformProperty; self.__transformOriginProperty = transformOriginProperty; if (helperElem.style[perspectiveProperty] !== undef) { return function(left, top, zoom, wasResize) { var translate3d = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0) scale(' + zoom + ')'; if (translate3d !== self.contentTransform) { content.style[transformProperty] = translate3d; self.contentTransform = translate3d; } self.__repositionScrollbars(); if (!wasResize) { self.triggerScrollEvent(); } }; } else if (helperElem.style[transformProperty] !== undef) { return function(left, top, zoom, wasResize) { content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px) scale(' + zoom + ')'; self.__repositionScrollbars(); if (!wasResize) { self.triggerScrollEvent(); } }; } else { return function(left, top, zoom, wasResize) { content.style.marginLeft = left ? (-left / zoom) + 'px' : ''; content.style.marginTop = top ? (-top / zoom) + 'px' : ''; content.style.zoom = zoom || ''; self.__repositionScrollbars(); if (!wasResize) { self.triggerScrollEvent(); } }; } }, /** * Configures the dimensions of the client (outer) and content (inner) elements. * Requires the available space for the outer element and the outer size of the inner element. * All values which are falsy (null or zero etc.) are ignored and the old value is kept. * * @param clientWidth {Integer} Inner width of outer element * @param clientHeight {Integer} Inner height of outer element * @param contentWidth {Integer} Outer width of inner element * @param contentHeight {Integer} Outer height of inner element */ setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight, continueScrolling) { var self = this; if (!clientWidth && !clientHeight && !contentWidth && !contentHeight) { // this scrollview isn't rendered, don't bother return; } // Only update values which are defined if (clientWidth === +clientWidth) { self.__clientWidth = clientWidth; } if (clientHeight === +clientHeight) { self.__clientHeight = clientHeight; } if (contentWidth === +contentWidth) { self.__contentWidth = contentWidth; } if (contentHeight === +contentHeight) { self.__contentHeight = contentHeight; } // Refresh maximums self.__computeScrollMax(); self.__resizeScrollbars(); // Refresh scroll position if (!continueScrolling) { self.scrollTo(self.__scrollLeft, self.__scrollTop, true, null, true); } }, /** * Sets the client coordinates in relation to the document. * * @param left {Integer} Left position of outer element * @param top {Integer} Top position of outer element */ setPosition: function(left, top) { this.__clientLeft = left || 0; this.__clientTop = top || 0; }, /** * Configures the snapping (when snapping is active) * * @param width {Integer} Snapping width * @param height {Integer} Snapping height */ setSnapSize: function(width, height) { this.__snapWidth = width; this.__snapHeight = height; }, /** * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever * the user event is released during visibility of this zone. This was introduced by some apps on iOS like * the official Twitter client. * * @param height {Integer} Height of pull-to-refresh zone on top of rendered list * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release. * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled. * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh. * @param showCallback {Function} Callback to execute when the refresher should be shown. This is for showing the refresher during a negative scrollTop. * @param hideCallback {Function} Callback to execute when the refresher should be hidden. This is for hiding the refresher when it's behind the nav bar. * @param tailCallback {Function} Callback to execute just before the refresher returns to it's original state. This is for zooming out the refresher. * @param pullProgressCallback Callback to state the progress while pulling to refresh */ activatePullToRefresh: function(height, refresherMethods) { var self = this; self.__refreshHeight = height; self.__refreshActivate = function() { ionic.requestAnimationFrame(refresherMethods.activate); }; self.__refreshDeactivate = function() { ionic.requestAnimationFrame(refresherMethods.deactivate); }; self.__refreshStart = function() { ionic.requestAnimationFrame(refresherMethods.start); }; self.__refreshShow = function() { ionic.requestAnimationFrame(refresherMethods.show); }; self.__refreshHide = function() { ionic.requestAnimationFrame(refresherMethods.hide); }; self.__refreshTail = function() { ionic.requestAnimationFrame(refresherMethods.tail); }; self.__refreshTailTime = 100; self.__minSpinTime = 600; }, /** * Starts pull-to-refresh manually. */ triggerPullToRefresh: function() { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true); var d = new Date(); this.refreshStartTime = d.getTime(); if (this.__refreshStart) { this.__refreshStart(); } }, /** * Signalizes that pull-to-refresh is finished. */ finishPullToRefresh: function() { var self = this; // delay to make sure the spinner has a chance to spin for a split second before it's dismissed var d = new Date(); var delay = 0; if (self.refreshStartTime + self.__minSpinTime > d.getTime()) { delay = self.refreshStartTime + self.__minSpinTime - d.getTime(); } setTimeout(function() { if (self.__refreshTail) { self.__refreshTail(); } setTimeout(function() { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } if (self.__refreshHide) { self.__refreshHide(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, self.__refreshTailTime); }, delay); }, /** * Returns the scroll position and zooming values * * @return {Map} `left` and `top` scroll position and `zoom` level */ getValues: function() { return { left: this.__scrollLeft, top: this.__scrollTop, zoom: this.__zoomLevel }; }, /** * Returns the maximum scroll values * * @return {Map} `left` and `top` maximum scroll values */ getScrollMax: function() { return { left: this.__maxScrollLeft, top: this.__maxScrollTop }; }, /** * Zooms to the given level. Supports optional animation. Zooms * the center when no coordinates are given. * * @param level {Number} Level to zoom to * @param animate {Boolean} Whether to use animation * @param originLeft {Number} Zoom in at given left coordinate * @param originTop {Number} Zoom in at given top coordinate */ zoomTo: function(level, animate, originLeft, originTop) { var self = this; if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } var oldLevel = self.__zoomLevel; // Normalize input origin to center of viewport if not defined if (originLeft == null) { originLeft = self.__clientWidth / 2; } if (originTop == null) { originTop = self.__clientHeight / 2; } // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(level); // Recompute left and top coordinates based on new zoom level var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft; var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop; // Limit x-axis if (left > self.__maxScrollLeft) { left = self.__maxScrollLeft; } else if (left < 0) { left = 0; } // Limit y-axis if (top > self.__maxScrollTop) { top = self.__maxScrollTop; } else if (top < 0) { top = 0; } // Push values out self.__publish(left, top, level, animate); }, /** * Zooms the content by the given factor. * * @param factor {Number} Zoom by given factor * @param animate {Boolean} Whether to use animation * @param originLeft {Number} Zoom in at given left coordinate * @param originTop {Number} Zoom in at given top coordinate */ zoomBy: function(factor, animate, originLeft, originTop) { this.zoomTo(this.__zoomLevel * factor, animate, originLeft, originTop); }, /** * Scrolls to the given position. Respect limitations and snapping automatically. * * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code> * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code> * @param animate {Boolean} Whether the scrolling should happen using an animation * @param zoom {Number} Zoom level to go to */ scrollTo: function(left, top, animate, zoom, wasResize) { var self = this; // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } // Correct coordinates based on new zoom level if (zoom != null && zoom !== self.__zoomLevel) { if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } left *= zoom; top *= zoom; // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(zoom); } else { // Keep zoom when not defined zoom = self.__zoomLevel; } if (!self.options.scrollingX) { left = self.__scrollLeft; } else { if (self.options.paging) { left = Math.round(left / self.__clientWidth) * self.__clientWidth; } else if (self.options.snapping) { left = Math.round(left / self.__snapWidth) * self.__snapWidth; } } if (!self.options.scrollingY) { top = self.__scrollTop; } else { if (self.options.paging) { top = Math.round(top / self.__clientHeight) * self.__clientHeight; } else if (self.options.snapping) { top = Math.round(top / self.__snapHeight) * self.__snapHeight; } } // Limit for allowed ranges left = Math.max(Math.min(self.__maxScrollLeft, left), 0); top = Math.max(Math.min(self.__maxScrollTop, top), 0); // Don't animate when no change detected, still call publish to make sure // that rendered position is really in-sync with internal data if (left === self.__scrollLeft && top === self.__scrollTop) { animate = false; } // Publish new values self.__publish(left, top, zoom, animate, wasResize); }, /** * Scroll by the given offset * * @param left {Number} Scroll x-axis by given offset * @param top {Number} Scroll y-axis by given offset * @param animate {Boolean} Whether to animate the given change */ scrollBy: function(left, top, animate) { var self = this; var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft; var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop; self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate); }, /* --------------------------------------------------------------------------- EVENT CALLBACKS --------------------------------------------------------------------------- */ /** * Mouse wheel handler for zooming support */ doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) { var change = wheelDelta > 0 ? 0.97 : 1.03; return this.zoomTo(this.__zoomLevel * change, false, pageX - this.__clientLeft, pageY - this.__clientTop); }, /** * Touch start handler for scrolling support */ doTouchStart: function(touches, timeStamp) { var self = this; // remember if the deceleration was just stopped self.__decStopped = !!(self.__isDecelerating || self.__isAnimating); self.hintResize(); if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { timeStamp = Date.now(); } // Reset interruptedAnimation flag self.__interruptedAnimation = true; // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; self.__interruptedAnimation = true; } // Stop animation if (self.__isAnimating) { zyngaCore.effect.Animate.stop(self.__isAnimating); self.__isAnimating = false; self.__interruptedAnimation = true; } // Use center point when dealing with two fingers var currentTouchLeft, currentTouchTop; var isSingleTouch = touches.length === 1; if (isSingleTouch) { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } else { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } // Store initial positions self.__initialTouchLeft = currentTouchLeft; self.__initialTouchTop = currentTouchTop; // Store initial touchList for scale calculation self.__initialTouches = touches; // Store current zoom level self.__zoomLevelStart = self.__zoomLevel; // Store initial touch positions self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; // Store initial move time stamp self.__lastTouchMove = timeStamp; // Reset initial scale self.__lastScale = 1; // Reset locking flags self.__enableScrollX = !isSingleTouch && self.options.scrollingX; self.__enableScrollY = !isSingleTouch && self.options.scrollingY; // Reset tracking flag self.__isTracking = true; // Reset deceleration complete flag self.__didDecelerationComplete = false; // Dragging starts directly with two fingers, otherwise lazy with an offset self.__isDragging = !isSingleTouch; // Some features are disabled in multi touch scenarios self.__isSingleTouch = isSingleTouch; // Clearing data structure self.__positions = []; }, /** * Touch move handler for scrolling support */ doTouchMove: function(touches, timeStamp, scale) { if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { timeStamp = Date.now(); } var self = this; // Ignore event when tracking is not enabled (event might be outside of element) if (!self.__isTracking) { return; } var currentTouchLeft, currentTouchTop; // Compute move based around of center of fingers if (touches.length === 2) { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; // Calculate scale when not present and only when touches are used if (!scale && self.options.zooming) { scale = self.__getScale(self.__initialTouches, touches); } } else { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } var positions = self.__positions; // Are we already is dragging mode? if (self.__isDragging) { self.__decStopped = false; // Compute move distance var moveX = currentTouchLeft - self.__lastTouchLeft; var moveY = currentTouchTop - self.__lastTouchTop; // Read previous scroll position and zooming var scrollLeft = self.__scrollLeft; var scrollTop = self.__scrollTop; var level = self.__zoomLevel; // Work with scaling if (scale != null && self.options.zooming) { var oldLevel = level; // Recompute level based on previous scale and new scale level = level / self.__lastScale * scale; // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Only do further compution when change happened if (oldLevel !== level) { // Compute relative event position to container var currentTouchLeftRel = currentTouchLeft - self.__clientLeft; var currentTouchTopRel = currentTouchTop - self.__clientTop; // Recompute left and top coordinates based on new zoom level scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel; scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel; // Recompute max scroll values self.__computeScrollMax(level); } } if (self.__enableScrollX) { scrollLeft -= moveX * self.options.speedMultiplier; var maxScrollLeft = self.__maxScrollLeft; if (scrollLeft > maxScrollLeft || scrollLeft < 0) { // Slow down on the edges if (self.options.bouncing) { scrollLeft += (moveX / 2 * self.options.speedMultiplier); } else if (scrollLeft > maxScrollLeft) { scrollLeft = maxScrollLeft; } else { scrollLeft = 0; } } } // Compute new vertical scroll position if (self.__enableScrollY) { scrollTop -= moveY * self.options.speedMultiplier; var maxScrollTop = self.__maxScrollTop; if (scrollTop > maxScrollTop || scrollTop < 0) { // Slow down on the edges if (self.options.bouncing || (self.__refreshHeight && scrollTop < 0)) { scrollTop += (moveY / 2 * self.options.speedMultiplier); // Support pull-to-refresh (only when only y is scrollable) if (!self.__enableScrollX && self.__refreshHeight != null) { // hide the refresher when it's behind the header bar in case of header transparency if (scrollTop < 0) { self.__refreshHidden = false; self.__refreshShow(); } else { self.__refreshHide(); self.__refreshHidden = true; } if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) { self.__refreshActive = true; if (self.__refreshActivate) { self.__refreshActivate(); } } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } else if (scrollTop > maxScrollTop) { scrollTop = maxScrollTop; } else { scrollTop = 0; } } else if (self.__refreshHeight && !self.__refreshHidden) { // if a positive scroll value and the refresher is still not hidden, hide it self.__refreshHide(); self.__refreshHidden = true; } } // Keep list from growing infinitely (holding min 10, max 20 measure points) if (positions.length > 60) { positions.splice(0, 30); } // Track scroll movement for decleration positions.push(scrollLeft, scrollTop, timeStamp); // Sync scroll position self.__publish(scrollLeft, scrollTop, level); // Otherwise figure out whether we are switching into dragging mode now. } else { var minimumTrackingForScroll = self.options.locking ? 3 : 0; var minimumTrackingForDrag = 5; var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft); var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop); self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll; self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll; positions.push(self.__scrollLeft, self.__scrollTop, timeStamp); self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag); if (self.__isDragging) { self.__interruptedAnimation = false; self.__fadeScrollbars('in'); } } // Update last touch positions and time stamp for next event self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; self.__lastTouchMove = timeStamp; self.__lastScale = scale; }, /** * Touch end handler for scrolling support */ doTouchEnd: function(e, timeStamp) { if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { timeStamp = Date.now(); } var self = this; // Ignore event when tracking is not enabled (no touchstart event on element) // This is required as this listener ('touchmove') sits on the document and not on the element itself. if (!self.__isTracking) { return; } // Not touching anymore (when two finger hit the screen there are two touch end events) self.__isTracking = false; // Be sure to reset the dragging flag now. Here we also detect whether // the finger has moved fast enough to switch into a deceleration animation. if (self.__isDragging) { // Reset dragging flag self.__isDragging = false; // Start deceleration // Verify that the last move detected was in some relevant time frame if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) { // Then figure out what the scroll position was about 100ms ago var positions = self.__positions; var endPos = positions.length - 1; var startPos = endPos; // Move pointer to position measured 100ms ago for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) { startPos = i; } // If start and stop position is identical in a 100ms timeframe, // we cannot compute any useful deceleration. if (startPos !== endPos) { // Compute relative movement between these two points var timeOffset = positions[endPos] - positions[startPos]; var movedLeft = self.__scrollLeft - positions[startPos - 2]; var movedTop = self.__scrollTop - positions[startPos - 1]; // Based on 50ms compute the movement to apply for each render step self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60); self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60); // How much velocity is required to start the deceleration var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? self.options.decelVelocityThresholdPaging : self.options.decelVelocityThreshold; // Verify that we have enough velocity to start deceleration if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) { // Deactivate pull-to-refresh when decelerating if (!self.__refreshActive) { self.__startDeceleration(timeStamp); } } } else { self.__scrollingComplete(); } } else if ((timeStamp - self.__lastTouchMove) > 100) { self.__scrollingComplete(); } } else if (self.__decStopped) { // the deceleration was stopped // user flicked the scroll fast, and stop dragging, then did a touchstart to stop the srolling // tell the touchend event code to do nothing, we don't want to actually send a click e.isTapHandled = true; self.__decStopped = false; } // If this was a slower move it is per default non decelerated, but this // still means that we want snap back to the bounds which is done here. // This is placed outside the condition above to improve edge case stability // e.g. touchend fired without enabled dragging. This should normally do not // have modified the scroll positions or even showed the scrollbars though. if (!self.__isDecelerating) { if (self.__refreshActive && self.__refreshStart) { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true); var d = new Date(); self.refreshStartTime = d.getTime(); if (self.__refreshStart) { self.__refreshStart(); } // for iOS-ey style scrolling if (!ionic.Platform.isAndroid())self.__startDeceleration(); } else { if (self.__interruptedAnimation || self.__isDragging) { self.__scrollingComplete(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel); // Directly signalize deactivation (nothing todo on refresh?) if (self.__refreshActive) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } // Fully cleanup list self.__positions.length = 0; }, /* --------------------------------------------------------------------------- PRIVATE API --------------------------------------------------------------------------- */ /** * Applies the scroll position to the content element * * @param left {Number} Left scroll position * @param top {Number} Top scroll position * @param animate {Boolean} Whether animation should be used to move to the new coordinates */ __publish: function(left, top, zoom, animate, wasResize) { var self = this; // Remember whether we had an animation, then we try to continue based on the current "drive" of the animation var wasAnimating = self.__isAnimating; if (wasAnimating) { zyngaCore.effect.Animate.stop(wasAnimating); self.__isAnimating = false; } if (animate && self.options.animating) { // Keep scheduled positions for scrollBy/zoomBy functionality self.__scheduledLeft = left; self.__scheduledTop = top; self.__scheduledZoom = zoom; var oldLeft = self.__scrollLeft; var oldTop = self.__scrollTop; var oldZoom = self.__zoomLevel; var diffLeft = left - oldLeft; var diffTop = top - oldTop; var diffZoom = zoom - oldZoom; var step = function(percent, now, render) { if (render) { self.__scrollLeft = oldLeft + (diffLeft * percent); self.__scrollTop = oldTop + (diffTop * percent); self.__zoomLevel = oldZoom + (diffZoom * percent); // Push values out if (self.__callback) { self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel, wasResize); } } }; var verify = function(id) { return self.__isAnimating === id; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { if (animationId === self.__isAnimating) { self.__isAnimating = false; } if (self.__didDecelerationComplete || wasFinished) { self.__scrollingComplete(); } if (self.options.zooming) { self.__computeScrollMax(); } }; // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out self.__isAnimating = zyngaCore.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic); } else { self.__scheduledLeft = self.__scrollLeft = left; self.__scheduledTop = self.__scrollTop = top; self.__scheduledZoom = self.__zoomLevel = zoom; // Push values out if (self.__callback) { self.__callback(left, top, zoom, wasResize); } // Fix max scroll ranges if (self.options.zooming) { self.__computeScrollMax(); } } }, /** * Recomputes scroll minimum values based on client dimensions and content dimensions. */ __computeScrollMax: function(zoomLevel) { var self = this; if (zoomLevel == null) { zoomLevel = self.__zoomLevel; } self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0); self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0); if (!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) { self.__didWaitForSize = true; self.__waitForSize(); } }, /** * If the scroll view isn't sized correctly on start, wait until we have at least some size */ __waitForSize: function() { var self = this; clearTimeout(self.__sizerTimeout); var sizer = function() { self.resize(true); }; sizer(); self.__sizerTimeout = setTimeout(sizer, 500); }, /* --------------------------------------------------------------------------- ANIMATION (DECELERATION) SUPPORT --------------------------------------------------------------------------- */ /** * Called when a touch sequence end and the speed of the finger was high enough * to switch into deceleration mode. */ __startDeceleration: function() { var self = this; if (self.options.paging) { var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0); var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0); var clientWidth = self.__clientWidth; var clientHeight = self.__clientHeight; // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area. // Each page should have exactly the size of the client area. self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth; self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight; self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth; self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight; } else { self.__minDecelerationScrollLeft = 0; self.__minDecelerationScrollTop = 0; self.__maxDecelerationScrollLeft = self.__maxScrollLeft; self.__maxDecelerationScrollTop = self.__maxScrollTop; if (self.__refreshActive) self.__minDecelerationScrollTop = self.__refreshHeight * -1; } // Wrap class method var step = function(percent, now, render) { self.__stepThroughDeceleration(render); }; // How much velocity is required to keep the deceleration running self.__minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1; // Detect whether it's still worth to continue animating steps // If we are already slow enough to not being user perceivable anymore, we stop the whole process here. var verify = function() { var shouldContinue = Math.abs(self.__decelerationVelocityX) >= self.__minVelocityToKeepDecelerating || Math.abs(self.__decelerationVelocityY) >= self.__minVelocityToKeepDecelerating; if (!shouldContinue) { self.__didDecelerationComplete = true; //Make sure the scroll values are within the boundaries after a bounce, //not below 0 or above maximum if (self.options.bouncing && !self.__refreshActive) { self.scrollTo( Math.min( Math.max(self.__scrollLeft, 0), self.__maxScrollLeft ), Math.min( Math.max(self.__scrollTop, 0), self.__maxScrollTop ), self.__refreshActive ); } } return shouldContinue; }; var completed = function() { self.__isDecelerating = false; if (self.__didDecelerationComplete) { self.__scrollingComplete(); } // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions if (self.options.paging) { self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping); } }; // Start animation and switch on flag self.__isDecelerating = zyngaCore.effect.Animate.start(step, verify, completed); }, /** * Called on every step of the animation * * @param inMemory {Boolean} Whether to not render the current step, but keep it in memory only. Used internally only! */ __stepThroughDeceleration: function(render) { var self = this; // // COMPUTE NEXT SCROLL POSITION // // Add deceleration to scroll position var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX;// * self.options.deceleration); var scrollTop = self.__scrollTop + self.__decelerationVelocityY;// * self.options.deceleration); // // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE // if (!self.options.bouncing) { var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft); if (scrollLeftFixed !== scrollLeft) { scrollLeft = scrollLeftFixed; self.__decelerationVelocityX = 0; } var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop); if (scrollTopFixed !== scrollTop) { scrollTop = scrollTopFixed; self.__decelerationVelocityY = 0; } } // // UPDATE SCROLL POSITION // if (render) { self.__publish(scrollLeft, scrollTop, self.__zoomLevel); } else { self.__scrollLeft = scrollLeft; self.__scrollTop = scrollTop; } // // SLOW DOWN // // Slow down velocity on every iteration if (!self.options.paging) { // This is the factor applied to every iteration of the animation // to slow down the process. This should emulate natural behavior where // objects slow down when the initiator of the movement is removed var frictionFactor = self.options.deceleration; self.__decelerationVelocityX *= frictionFactor; self.__decelerationVelocityY *= frictionFactor; } // // BOUNCING SUPPORT // if (self.options.bouncing) { var scrollOutsideX = 0; var scrollOutsideY = 0; // This configures the amount of change applied to deceleration/acceleration when reaching boundaries var penetrationDeceleration = self.options.penetrationDeceleration; var penetrationAcceleration = self.options.penetrationAcceleration; // Check limits if (scrollLeft < self.__minDecelerationScrollLeft) { scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft; } else if (scrollLeft > self.__maxDecelerationScrollLeft) { scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft; } if (scrollTop < self.__minDecelerationScrollTop) { scrollOutsideY = self.__minDecelerationScrollTop - scrollTop; } else if (scrollTop > self.__maxDecelerationScrollTop) { scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop; } // Slow down until slow enough, then flip back to snap position if (scrollOutsideX !== 0) { var isHeadingOutwardsX = scrollOutsideX * self.__decelerationVelocityX <= self.__minDecelerationScrollLeft; if (isHeadingOutwardsX) { self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration; } var isStoppedX = Math.abs(self.__decelerationVelocityX) <= self.__minVelocityToKeepDecelerating; //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds if (!isHeadingOutwardsX || isStoppedX) { self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration; } } if (scrollOutsideY !== 0) { var isHeadingOutwardsY = scrollOutsideY * self.__decelerationVelocityY <= self.__minDecelerationScrollTop; if (isHeadingOutwardsY) { self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration; } var isStoppedY = Math.abs(self.__decelerationVelocityY) <= self.__minVelocityToKeepDecelerating; //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds if (!isHeadingOutwardsY || isStoppedY) { self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration; } } } }, /** * calculate the distance between two touches * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} distance */ __getDistance: function getDistance(touch1, touch2) { var x = touch2.pageX - touch1.pageX, y = touch2.pageY - touch1.pageY; return Math.sqrt((x * x) + (y * y)); }, /** * calculate the scale factor between two touchLists (fingers) * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start * @param {Array} end * @returns {Number} scale */ __getScale: function getScale(start, end) { // need two fingers... if (start.length >= 2 && end.length >= 2) { return this.__getDistance(end[0], end[1]) / this.__getDistance(start[0], start[1]); } return 1; } }); ionic.scroll = { isScrolling: false, lastTop: 0 }; })(ionic); (function(ionic) { var NOOP = function() {}; var deprecated = function(name) { console.error('Method not available in native scrolling: ' + name); }; ionic.views.ScrollNative = ionic.views.View.inherit({ initialize: function(options) { var self = this; self.__container = self.el = options.el; self.__content = options.el.firstElementChild; // Whether scrolling is frozen or not self.__frozen = false; self.isNative = true; self.__scrollTop = self.el.scrollTop; self.__scrollLeft = self.el.scrollLeft; self.__clientHeight = self.__content.clientHeight; self.__clientWidth = self.__content.clientWidth; self.__maxScrollTop = Math.max((self.__contentHeight) - self.__clientHeight, 0); self.__maxScrollLeft = Math.max((self.__contentWidth) - self.__clientWidth, 0); if(options.startY >= 0 || options.startX >= 0) { ionic.requestAnimationFrame(function() { self.el.scrollTop = options.startY || 0; self.el.scrollLeft = options.startX || 0; self.__scrollTop = self.el.scrollTop; self.__scrollLeft = self.el.scrollLeft; }); } self.options = { freeze: false, getContentWidth: function() { return Math.max(self.__content.scrollWidth, self.__content.offsetWidth); }, getContentHeight: function() { return Math.max(self.__content.scrollHeight, self.__content.offsetHeight + (self.__content.offsetTop * 2)); } }; for (var key in options) { self.options[key] = options[key]; } /** * Sets isScrolling to true, and automatically deactivates if not called again in 80ms. */ self.onScroll = function() { if (!ionic.scroll.isScrolling) { ionic.scroll.isScrolling = true; } clearTimeout(self.scrollTimer); self.scrollTimer = setTimeout(function() { ionic.scroll.isScrolling = false; }, 80); }; self.freeze = function(shouldFreeze) { self.__frozen = shouldFreeze; }; // A more powerful freeze pop that dominates all other freeze pops self.freezeShut = function(shouldFreezeShut) { self.__frozenShut = shouldFreezeShut; }; self.__initEventHandlers(); }, /** Methods not used in native scrolling */ __callback: function() { deprecated('__callback'); }, zoomTo: function() { deprecated('zoomTo'); }, zoomBy: function() { deprecated('zoomBy'); }, activatePullToRefresh: function() { deprecated('activatePullToRefresh'); }, /** * Returns the scroll position and zooming values * * @return {Map} `left` and `top` scroll position and `zoom` level */ resize: function(continueScrolling) { var self = this; if (!self.__container || !self.options) return; // Update Scroller dimensions for changed content // Add padding to bottom of content self.setDimensions( self.__container.clientWidth, self.__container.clientHeight, self.options.getContentWidth(), self.options.getContentHeight(), continueScrolling ); }, /** * Initialize the scrollview * In native scrolling, this only means we need to gather size information */ run: function() { this.resize(); }, /** * Returns the scroll position and zooming values * * @return {Map} `left` and `top` scroll position and `zoom` level */ getValues: function() { var self = this; self.update(); return { left: self.__scrollLeft, top: self.__scrollTop, zoom: 1 }; }, /** * Updates the __scrollLeft and __scrollTop values to el's current value */ update: function() { var self = this; self.__scrollLeft = self.el.scrollLeft; self.__scrollTop = self.el.scrollTop; }, /** * Configures the dimensions of the client (outer) and content (inner) elements. * Requires the available space for the outer element and the outer size of the inner element. * All values which are falsy (null or zero etc.) are ignored and the old value is kept. * * @param clientWidth {Integer} Inner width of outer element * @param clientHeight {Integer} Inner height of outer element * @param contentWidth {Integer} Outer width of inner element * @param contentHeight {Integer} Outer height of inner element */ setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) { var self = this; if (!clientWidth && !clientHeight && !contentWidth && !contentHeight) { // this scrollview isn't rendered, don't bother return; } // Only update values which are defined if (clientWidth === +clientWidth) { self.__clientWidth = clientWidth; } if (clientHeight === +clientHeight) { self.__clientHeight = clientHeight; } if (contentWidth === +contentWidth) { self.__contentWidth = contentWidth; } if (contentHeight === +contentHeight) { self.__contentHeight = contentHeight; } // Refresh maximums self.__computeScrollMax(); }, /** * Returns the maximum scroll values * * @return {Map} `left` and `top` maximum scroll values */ getScrollMax: function() { return { left: this.__maxScrollLeft, top: this.__maxScrollTop }; }, /** * Scrolls by the given amount in px. * * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code> * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code> * @param animate {Boolean} Whether the scrolling should happen using an animation */ scrollBy: function(left, top, animate) { var self = this; // update scroll vars before refferencing them self.update(); var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft; var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop; self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate); }, /** * Scrolls to the given position in px. * * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code> * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code> * @param animate {Boolean} Whether the scrolling should happen using an animation */ scrollTo: function(left, top, animate) { var self = this; if (!animate) { self.el.scrollTop = top; self.el.scrollLeft = left; self.resize(); return; } var oldOverflowX = self.el.style.overflowX; var oldOverflowY = self.el.style.overflowY; clearTimeout(self.__scrollToCleanupTimeout); self.__scrollToCleanupTimeout = setTimeout(function() { self.el.style.overflowX = oldOverflowX; self.el.style.overflowY = oldOverflowY; }, 500); self.el.style.overflowY = 'hidden'; self.el.style.overflowX = 'hidden'; animateScroll(top, left); function animateScroll(Y, X) { // scroll animation loop w/ easing // credit https://gist.github.com/dezinezync/5487119 var start = Date.now(), duration = 250, //milliseconds fromY = self.el.scrollTop, fromX = self.el.scrollLeft; if (fromY === Y && fromX === X) { self.el.style.overflowX = oldOverflowX; self.el.style.overflowY = oldOverflowY; self.resize(); return; /* Prevent scrolling to the Y point if already there */ } // decelerating to zero velocity function easeOutCubic(t) { return (--t) * t * t + 1; } // scroll loop function animateScrollStep() { var currentTime = Date.now(), time = Math.min(1, ((currentTime - start) / duration)), // where .5 would be 50% of time on a linear scale easedT gives a // fraction based on the easing method easedT = easeOutCubic(time); if (fromY != Y) { self.el.scrollTop = parseInt((easedT * (Y - fromY)) + fromY, 10); } if (fromX != X) { self.el.scrollLeft = parseInt((easedT * (X - fromX)) + fromX, 10); } if (time < 1) { ionic.requestAnimationFrame(animateScrollStep); } else { // done ionic.tap.removeClonedInputs(self.__container, self); self.el.style.overflowX = oldOverflowX; self.el.style.overflowY = oldOverflowY; self.resize(); } } // start scroll loop ionic.requestAnimationFrame(animateScrollStep); } }, /* --------------------------------------------------------------------------- PRIVATE API --------------------------------------------------------------------------- */ /** * If the scroll view isn't sized correctly on start, wait until we have at least some size */ __waitForSize: function() { var self = this; clearTimeout(self.__sizerTimeout); var sizer = function() { self.resize(true); }; sizer(); self.__sizerTimeout = setTimeout(sizer, 500); }, /** * Recomputes scroll minimum values based on client dimensions and content dimensions. */ __computeScrollMax: function() { var self = this; self.__maxScrollLeft = Math.max((self.__contentWidth) - self.__clientWidth, 0); self.__maxScrollTop = Math.max((self.__contentHeight) - self.__clientHeight, 0); if (!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) { self.__didWaitForSize = true; self.__waitForSize(); } }, __initEventHandlers: function() { var self = this; // Event Handler var container = self.__container; // save height when scroll view is shrunk so we don't need to reflow var scrollViewOffsetHeight; var lastKeyboardHeight; /** * Shrink the scroll view when the keyboard is up if necessary and if the * focused input is below the bottom of the shrunk scroll view, scroll it * into view. */ self.scrollChildIntoView = function(e) { var rect = container.getBoundingClientRect(); if(!self.__originalContainerHeight) { self.__originalContainerHeight = rect.height; } // D //var scrollBottomOffsetToTop = rect.bottom; // D - A scrollViewOffsetHeight = self.__originalContainerHeight; //console.log('Scroll view offset height', scrollViewOffsetHeight); //console.dir(container); var alreadyShrunk = self.isShrunkForKeyboard; var isModal = container.parentNode.classList.contains('modal'); var isPopover = container.parentNode.classList.contains('popover'); // 680px is when the media query for 60% modal width kicks in var isInsetModal = isModal && window.innerWidth >= 680; /* * _______ * |---A---| <- top of scroll view * | | * |---B---| <- keyboard * | C | <- input * |---D---| <- initial bottom of scroll view * |___E___| <- bottom of viewport * * All commented calculations relative to the top of the viewport (ie E * is the viewport height, not 0) */ var changedKeyboardHeight = lastKeyboardHeight && (lastKeyboardHeight !== e.detail.keyboardHeight); if (!alreadyShrunk || changedKeyboardHeight) { // shrink scrollview so we can actually scroll if the input is hidden // if it isn't shrink so we can scroll to inputs under the keyboard // inset modals won't shrink on Android on their own when the keyboard appears if ( !isPopover && (ionic.Platform.isIOS() || ionic.Platform.isFullScreen || isInsetModal) ) { // if there are things below the scroll view account for them and // subtract them from the keyboard height when resizing // E - D E D //var scrollBottomOffsetToBottom = e.detail.viewportHeight - scrollBottomOffsetToTop; // 0 or D - B if D > B E - B E - D //var keyboardOffset = e.detail.keyboardHeight - scrollBottomOffsetToBottom; ionic.requestAnimationFrame(function(){ // D - A or B - A if D > B D - A max(0, D - B) scrollViewOffsetHeight = Math.max(0, Math.min(self.__originalContainerHeight, self.__originalContainerHeight - (e.detail.keyboardHeight - 43)));//keyboardOffset >= 0 ? scrollViewOffsetHeight - keyboardOffset : scrollViewOffsetHeight + keyboardOffset; //console.log('Old container height', self.__originalContainerHeight, 'New container height', scrollViewOffsetHeight, 'Keyboard height', e.detail.keyboardHeight); container.style.height = scrollViewOffsetHeight + "px"; /* if (ionic.Platform.isIOS()) { // Force redraw to avoid disappearing content var disp = container.style.display; container.style.display = 'none'; var trick = container.offsetHeight; container.style.display = disp; } */ container.classList.add('keyboard-up'); //update scroll view self.resize(); }); } self.isShrunkForKeyboard = true; } lastKeyboardHeight = e.detail.keyboardHeight; /* * _______ * |---A---| <- top of scroll view * | * | <- where we want to scroll to * |--B-D--| <- keyboard, bottom of scroll view * | C | <- input * | | * |___E___| <- bottom of viewport * * All commented calculations relative to the top of the viewport (ie E * is the viewport height, not 0) */ // if the element is positioned under the keyboard scroll it into view if (e.detail.isElementUnderKeyboard) { ionic.requestAnimationFrame(function(){ var pos = ionic.DomUtil.getOffsetTop(e.detail.target); setTimeout(function() { if (ionic.Platform.isIOS()) { ionic.tap.cloneFocusedInput(container, self); } // Scroll the input into view, with a 100px buffer self.scrollTo(0, pos - (rect.top + 100), true); self.onScroll(); }, 32); /* // update D if we shrunk if (self.isShrunkForKeyboard && !alreadyShrunk) { scrollBottomOffsetToTop = container.getBoundingClientRect().bottom; console.log('Scroll bottom', scrollBottomOffsetToTop); } // middle of the scrollview, this is where we want to scroll to // (D - A) / 2 var scrollMidpointOffset = scrollViewOffsetHeight * 0.5; console.log('Midpoint', scrollMidpointOffset); //console.log("container.offsetHeight: " + scrollViewOffsetHeight); // middle of the input we want to scroll into view // C var inputMidpoint = ((e.detail.elementBottom + e.detail.elementTop) / 2); console.log('Input midpoint'); // distance from middle of input to the bottom of the scroll view // C - D C D var inputMidpointOffsetToScrollBottom = inputMidpoint - scrollBottomOffsetToTop; console.log('Input midpoint offset', inputMidpointOffsetToScrollBottom); //C - D + (D - A)/2 C - D (D - A)/ 2 var scrollTop = inputMidpointOffsetToScrollBottom + scrollMidpointOffset; console.log('Scroll top', scrollTop); if ( scrollTop > 0) { if (ionic.Platform.isIOS()) { //just shrank scroll view, give it some breathing room before scrolling setTimeout(function(){ ionic.tap.cloneFocusedInput(container, self); self.scrollBy(0, scrollTop, true); self.onScroll(); }, 32); } else { self.scrollBy(0, scrollTop, true); self.onScroll(); } } */ }); } // Only the first scrollView parent of the element that broadcasted this event // (the active element that needs to be shown) should receive this event e.stopPropagation(); }; self.resetScrollView = function() { //return scrollview to original height once keyboard has hidden if (self.isShrunkForKeyboard) { self.isShrunkForKeyboard = false; container.style.height = ""; /* if (ionic.Platform.isIOS()) { // Force redraw to avoid disappearing content var disp = container.style.display; container.style.display = 'none'; var trick = container.offsetHeight; container.style.display = disp; } */ self.__originalContainerHeight = container.getBoundingClientRect().height; if (ionic.Platform.isIOS()) { ionic.requestAnimationFrame(function() { container.classList.remove('keyboard-up'); }); } } self.resize(); }; self.handleTouchMove = function(e) { if(self.__frozenShut) { e.preventDefault(); e.stopPropagation(); return false; } }; container.addEventListener('scroll', self.onScroll); //Broadcasted when keyboard is shown on some platforms. //See js/utils/keyboard.js container.addEventListener('scrollChildIntoView', self.scrollChildIntoView); container.addEventListener(ionic.EVENTS.touchstart, self.handleTouchMove); container.addEventListener(ionic.EVENTS.touchmove, self.handleTouchMove); // Listen on document because container may not have had the last // keyboardActiveElement, for example after closing a modal with a focused // input and returning to a previously resized scroll view in an ion-content. // Since we can only resize scroll views that are currently visible, just resize // the current scroll view when the keyboard is closed. document.addEventListener('resetScrollView', self.resetScrollView); }, __cleanup: function() { var self = this; var container = self.__container; container.removeEventListener('resetScrollView', self.resetScrollView); container.removeEventListener('scroll', self.onScroll); container.removeEventListener('scrollChildIntoView', self.scrollChildIntoView); container.removeEventListener('resetScrollView', self.resetScrollView); container.removeEventListener(ionic.EVENTS.touchstart, self.handleTouchMove); container.removeEventListener(ionic.EVENTS.touchmove, self.handleTouchMove); ionic.tap.removeClonedInputs(container, self); delete self.__container; delete self.__content; delete self.__indicatorX; delete self.__indicatorY; delete self.options.el; self.resize = self.scrollTo = self.onScroll = self.resetScrollView = NOOP; self.scrollChildIntoView = NOOP; container = null; } }); })(ionic); (function(ionic) { 'use strict'; var ITEM_CLASS = 'item'; var ITEM_CONTENT_CLASS = 'item-content'; var ITEM_SLIDING_CLASS = 'item-sliding'; var ITEM_OPTIONS_CLASS = 'item-options'; var ITEM_PLACEHOLDER_CLASS = 'item-placeholder'; var ITEM_REORDERING_CLASS = 'item-reordering'; var ITEM_REORDER_BTN_CLASS = 'item-reorder'; var DragOp = function() {}; DragOp.prototype = { start: function(){}, drag: function(){}, end: function(){}, isSameItem: function() { return false; } }; var SlideDrag = function(opts) { this.dragThresholdX = opts.dragThresholdX || 10; this.el = opts.el; this.item = opts.item; this.canSwipe = opts.canSwipe; }; SlideDrag.prototype = new DragOp(); SlideDrag.prototype.start = function(e) { var content, buttons, offsetX, buttonsWidth; if (!this.canSwipe()) { return; } if (e.target.classList.contains(ITEM_CONTENT_CLASS)) { content = e.target; } else if (e.target.classList.contains(ITEM_CLASS)) { content = e.target.querySelector('.' + ITEM_CONTENT_CLASS); } else { content = ionic.DomUtil.getParentWithClass(e.target, ITEM_CONTENT_CLASS); } // If we don't have a content area as one of our children (or ourselves), skip if (!content) { return; } // Make sure we aren't animating as we slide content.classList.remove(ITEM_SLIDING_CLASS); // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start) offsetX = parseFloat(content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0; // Grab the buttons buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS); if (!buttons) { return; } buttons.classList.remove('invisible'); buttonsWidth = buttons.offsetWidth; this._currentDrag = { buttons: buttons, buttonsWidth: buttonsWidth, content: content, startOffsetX: offsetX }; }; /** * Check if this is the same item that was previously dragged. */ SlideDrag.prototype.isSameItem = function(op) { if (op._lastDrag && this._currentDrag) { return this._currentDrag.content == op._lastDrag.content; } return false; }; SlideDrag.prototype.clean = function(isInstant) { var lastDrag = this._lastDrag; if (!lastDrag || !lastDrag.content) return; lastDrag.content.style[ionic.CSS.TRANSITION] = ''; lastDrag.content.style[ionic.CSS.TRANSFORM] = ''; if (isInstant) { lastDrag.content.style[ionic.CSS.TRANSITION] = 'none'; makeInvisible(); ionic.requestAnimationFrame(function() { lastDrag.content.style[ionic.CSS.TRANSITION] = ''; }); } else { ionic.requestAnimationFrame(function() { setTimeout(makeInvisible, 250); }); } function makeInvisible() { lastDrag.buttons && lastDrag.buttons.classList.add('invisible'); } }; SlideDrag.prototype.drag = ionic.animationFrameThrottle(function(e) { var buttonsWidth; // We really aren't dragging if (!this._currentDrag) { return; } // Check if we should start dragging. Check if we've dragged past the threshold, // or we are starting from the open state. if (!this._isDragging && ((Math.abs(e.gesture.deltaX) > this.dragThresholdX) || (Math.abs(this._currentDrag.startOffsetX) > 0))) { this._isDragging = true; } if (this._isDragging) { buttonsWidth = this._currentDrag.buttonsWidth; // Grab the new X point, capping it at zero var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX); // If the new X position is past the buttons, we need to slow down the drag (rubber band style) if (newX < -buttonsWidth) { // Calculate the new X position, capped at the top of the buttons newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4))); } this._currentDrag.content.$$ionicOptionsOpen = newX !== 0; this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + newX + 'px, 0, 0)'; this._currentDrag.content.style[ionic.CSS.TRANSITION] = 'none'; } }); SlideDrag.prototype.end = function(e, doneCallback) { var self = this; // There is no drag, just end immediately if (!self._currentDrag) { doneCallback && doneCallback(); return; } // If we are currently dragging, we want to snap back into place // The final resting point X will be the width of the exposed buttons var restingPoint = -self._currentDrag.buttonsWidth; // Check if the drag didn't clear the buttons mid-point // and we aren't moving fast enough to swipe open if (e.gesture.deltaX > -(self._currentDrag.buttonsWidth / 2)) { // If we are going left but too slow, or going right, go back to resting if (e.gesture.direction == "left" && Math.abs(e.gesture.velocityX) < 0.3) { restingPoint = 0; } else if (e.gesture.direction == "right") { restingPoint = 0; } } ionic.requestAnimationFrame(function() { if (restingPoint === 0) { self._currentDrag.content.style[ionic.CSS.TRANSFORM] = ''; var buttons = self._currentDrag.buttons; setTimeout(function() { buttons && buttons.classList.add('invisible'); }, 250); } else { self._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + restingPoint + 'px,0,0)'; } self._currentDrag.content.style[ionic.CSS.TRANSITION] = ''; // Kill the current drag if (!self._lastDrag) { self._lastDrag = {}; } ionic.extend(self._lastDrag, self._currentDrag); if (self._currentDrag) { self._currentDrag.buttons = null; self._currentDrag.content = null; } self._currentDrag = null; // We are done, notify caller doneCallback && doneCallback(); }); }; var ReorderDrag = function(opts) { var self = this; self.dragThresholdY = opts.dragThresholdY || 0; self.onReorder = opts.onReorder; self.listEl = opts.listEl; self.el = self.item = opts.el; self.scrollEl = opts.scrollEl; self.scrollView = opts.scrollView; // Get the True Top of the list el http://www.quirksmode.org/js/findpos.html self.listElTrueTop = 0; if (self.listEl.offsetParent) { var obj = self.listEl; do { self.listElTrueTop += obj.offsetTop; obj = obj.offsetParent; } while (obj); } }; ReorderDrag.prototype = new DragOp(); ReorderDrag.prototype._moveElement = function(e) { var y = e.gesture.center.pageY + this.scrollView.getValues().top - (this._currentDrag.elementHeight / 2) - this.listElTrueTop; this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(0, ' + y + 'px, 0)'; }; ReorderDrag.prototype.deregister = function() { this.listEl = this.el = this.scrollEl = this.scrollView = null; }; ReorderDrag.prototype.start = function(e) { var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase()); var elementHeight = this.el.scrollHeight; var placeholder = this.el.cloneNode(true); placeholder.classList.add(ITEM_PLACEHOLDER_CLASS); this.el.parentNode.insertBefore(placeholder, this.el); this.el.classList.add(ITEM_REORDERING_CLASS); this._currentDrag = { elementHeight: elementHeight, startIndex: startIndex, placeholder: placeholder, scrollHeight: scroll, list: placeholder.parentNode }; this._moveElement(e); }; ReorderDrag.prototype.drag = ionic.animationFrameThrottle(function(e) { // We really aren't dragging var self = this; if (!this._currentDrag) { return; } var scrollY = 0; var pageY = e.gesture.center.pageY; var offset = this.listElTrueTop; //If we have a scrollView, check scroll boundaries for dragged element and scroll if necessary if (this.scrollView) { var container = this.scrollView.__container; scrollY = this.scrollView.getValues().top; var containerTop = container.offsetTop; var pixelsPastTop = containerTop - pageY + this._currentDrag.elementHeight / 2; var pixelsPastBottom = pageY + this._currentDrag.elementHeight / 2 - containerTop - container.offsetHeight; if (e.gesture.deltaY < 0 && pixelsPastTop > 0 && scrollY > 0) { this.scrollView.scrollBy(null, -pixelsPastTop); //Trigger another drag so the scrolling keeps going ionic.requestAnimationFrame(function() { self.drag(e); }); } if (e.gesture.deltaY > 0 && pixelsPastBottom > 0) { if (scrollY < this.scrollView.getScrollMax().top) { this.scrollView.scrollBy(null, pixelsPastBottom); //Trigger another drag so the scrolling keeps going ionic.requestAnimationFrame(function() { self.drag(e); }); } } } // Check if we should start dragging. Check if we've dragged past the threshold, // or we are starting from the open state. if (!this._isDragging && Math.abs(e.gesture.deltaY) > this.dragThresholdY) { this._isDragging = true; } if (this._isDragging) { this._moveElement(e); this._currentDrag.currentY = scrollY + pageY - offset; // this._reorderItems(); } }); // When an item is dragged, we need to reorder any items for sorting purposes ReorderDrag.prototype._getReorderIndex = function() { var self = this; var siblings = Array.prototype.slice.call(self._currentDrag.placeholder.parentNode.children) .filter(function(el) { return el.nodeName === self.el.nodeName && el !== self.el; }); var dragOffsetTop = self._currentDrag.currentY; var el; for (var i = 0, len = siblings.length; i < len; i++) { el = siblings[i]; if (i === len - 1) { if (dragOffsetTop > el.offsetTop) { return i; } } else if (i === 0) { if (dragOffsetTop < el.offsetTop + el.offsetHeight) { return i; } } else if (dragOffsetTop > el.offsetTop - el.offsetHeight / 2 && dragOffsetTop < el.offsetTop + el.offsetHeight) { return i; } } return self._currentDrag.startIndex; }; ReorderDrag.prototype.end = function(e, doneCallback) { if (!this._currentDrag) { doneCallback && doneCallback(); return; } var placeholder = this._currentDrag.placeholder; var finalIndex = this._getReorderIndex(); // Reposition the element this.el.classList.remove(ITEM_REORDERING_CLASS); this.el.style[ionic.CSS.TRANSFORM] = ''; placeholder.parentNode.insertBefore(this.el, placeholder); placeholder.parentNode.removeChild(placeholder); this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalIndex); this._currentDrag = { placeholder: null, content: null }; this._currentDrag = null; doneCallback && doneCallback(); }; /** * The ListView handles a list of items. It will process drag animations, edit mode, * and other operations that are common on mobile lists or table views. */ ionic.views.ListView = ionic.views.View.inherit({ initialize: function(opts) { var self = this; opts = ionic.extend({ onReorder: function() {}, virtualRemoveThreshold: -200, virtualAddThreshold: 200, canSwipe: function() { return true; } }, opts); ionic.extend(self, opts); if (!self.itemHeight && self.listEl) { self.itemHeight = self.listEl.children[0] && parseInt(self.listEl.children[0].style.height, 10); } self.onRefresh = opts.onRefresh || function() {}; self.onRefreshOpening = opts.onRefreshOpening || function() {}; self.onRefreshHolding = opts.onRefreshHolding || function() {}; var gestureOpts = {}; // don't prevent native scrolling if (ionic.DomUtil.getParentOrSelfWithClass(self.el, 'overflow-scroll')) { gestureOpts.prevent_default_directions = ['left', 'right']; } window.ionic.onGesture('release', function(e) { self._handleEndDrag(e); }, self.el, gestureOpts); window.ionic.onGesture('drag', function(e) { self._handleDrag(e); }, self.el, gestureOpts); // Start the drag states self._initDrag(); }, /** * Be sure to cleanup references. */ deregister: function() { this.el = this.listEl = this.scrollEl = this.scrollView = null; // ensure no scrolls have been left frozen if (this.isScrollFreeze) { self.scrollView.freeze(false); } }, /** * Called to tell the list to stop refreshing. This is useful * if you are refreshing the list and are done with refreshing. */ stopRefreshing: function() { var refresher = this.el.querySelector('.list-refresher'); refresher.style.height = '0'; }, /** * If we scrolled and have virtual mode enabled, compute the window * of active elements in order to figure out the viewport to render. */ didScroll: function(e) { var self = this; if (self.isVirtual) { var itemHeight = self.itemHeight; // Grab the total height of the list var scrollHeight = e.target.scrollHeight; // Get the viewport height var viewportHeight = self.el.parentNode.offsetHeight; // High water is the pixel position of the first element to include (everything before // that will be removed) var highWater = Math.max(0, e.scrollTop + self.virtualRemoveThreshold); // Low water is the pixel position of the last element to include (everything after // that will be removed) var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + self.virtualAddThreshold); // Get the first and last elements in the list based on how many can fit // between the pixel range of lowWater and highWater var first = parseInt(Math.abs(highWater / itemHeight), 10); var last = parseInt(Math.abs(lowWater / itemHeight), 10); // Get the items we need to remove self._virtualItemsToRemove = Array.prototype.slice.call(self.listEl.children, 0, first); self.renderViewport && self.renderViewport(highWater, lowWater, first, last); } }, didStopScrolling: function() { if (this.isVirtual) { for (var i = 0; i < this._virtualItemsToRemove.length; i++) { //el.parentNode.removeChild(el); this.didHideItem && this.didHideItem(i); } // Once scrolling stops, check if we need to remove old items } }, /** * Clear any active drag effects on the list. */ clearDragEffects: function(isInstant) { if (this._lastDragOp) { this._lastDragOp.clean && this._lastDragOp.clean(isInstant); this._lastDragOp.deregister && this._lastDragOp.deregister(); this._lastDragOp = null; } }, _initDrag: function() { // Store the last one if (this._lastDragOp) { this._lastDragOp.deregister && this._lastDragOp.deregister(); } this._lastDragOp = this._dragOp; this._dragOp = null; }, // Return the list item from the given target _getItem: function(target) { while (target) { if (target.classList && target.classList.contains(ITEM_CLASS)) { return target; } target = target.parentNode; } return null; }, _startDrag: function(e) { var self = this; self._isDragging = false; var lastDragOp = self._lastDragOp; var item; // If we have an open SlideDrag and we're scrolling the list. Clear it. if (self._didDragUpOrDown && lastDragOp instanceof SlideDrag) { lastDragOp.clean && lastDragOp.clean(); } // Check if this is a reorder drag if (ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_REORDER_BTN_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) { item = self._getItem(e.target); if (item) { self._dragOp = new ReorderDrag({ listEl: self.el, el: item, scrollEl: self.scrollEl, scrollView: self.scrollView, onReorder: function(el, start, end) { self.onReorder && self.onReorder(el, start, end); } }); self._dragOp.start(e); e.preventDefault(); } } // Or check if this is a swipe to the side drag else if (!self._didDragUpOrDown && (e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) { // Make sure this is an item with buttons item = self._getItem(e.target); if (item && item.querySelector('.item-options')) { self._dragOp = new SlideDrag({ el: self.el, item: item, canSwipe: self.canSwipe }); self._dragOp.start(e); e.preventDefault(); self.isScrollFreeze = self.scrollView.freeze(true); } } // If we had a last drag operation and this is a new one on a different item, clean that last one if (lastDragOp && self._dragOp && !self._dragOp.isSameItem(lastDragOp) && e.defaultPrevented) { lastDragOp.clean && lastDragOp.clean(); } }, _handleEndDrag: function(e) { var self = this; if (self.scrollView) { self.isScrollFreeze = self.scrollView.freeze(false); } self._didDragUpOrDown = false; if (!self._dragOp) { return; } self._dragOp.end(e, function() { self._initDrag(); }); }, /** * Process the drag event to move the item to the left or right. */ _handleDrag: function(e) { var self = this; if (Math.abs(e.gesture.deltaY) > 5) { self._didDragUpOrDown = true; } // If we get a drag event, make sure we aren't in another drag, then check if we should // start one if (!self.isDragging && !self._dragOp) { self._startDrag(e); } // No drag still, pass it up if (!self._dragOp) { return; } e.gesture.srcEvent.preventDefault(); self._dragOp.drag(e); } }); })(ionic); (function(ionic) { 'use strict'; ionic.views.Modal = ionic.views.View.inherit({ initialize: function(opts) { opts = ionic.extend({ focusFirstInput: false, unfocusOnHide: true, focusFirstDelay: 600, backdropClickToClose: true, hardwareBackButtonClose: true, }, opts); ionic.extend(this, opts); this.el = opts.el; }, show: function() { var self = this; if(self.focusFirstInput) { // Let any animations run first window.setTimeout(function() { var input = self.el.querySelector('input, textarea'); input && input.focus && input.focus(); }, self.focusFirstDelay); } }, hide: function() { // Unfocus all elements if(this.unfocusOnHide) { var inputs = this.el.querySelectorAll('input, textarea'); // Let any animations run first window.setTimeout(function() { for(var i = 0; i < inputs.length; i++) { inputs[i].blur && inputs[i].blur(); } }); } } }); })(ionic); (function(ionic) { 'use strict'; /** * The side menu view handles one of the side menu's in a Side Menu Controller * configuration. * It takes a DOM reference to that side menu element. */ ionic.views.SideMenu = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.isEnabled = (typeof opts.isEnabled === 'undefined') ? true : opts.isEnabled; this.setWidth(opts.width); }, getFullWidth: function() { return this.width; }, setWidth: function(width) { this.width = width; this.el.style.width = width + 'px'; }, setIsEnabled: function(isEnabled) { this.isEnabled = isEnabled; }, bringUp: function() { if(this.el.style.zIndex !== '0') { this.el.style.zIndex = '0'; } }, pushDown: function() { if(this.el.style.zIndex !== '-1') { this.el.style.zIndex = '-1'; } } }); ionic.views.SideMenuContent = ionic.views.View.inherit({ initialize: function(opts) { ionic.extend(this, { animationClass: 'menu-animated', onDrag: function() {}, onEndDrag: function() {} }, opts); ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el); ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el); }, _onDrag: function(e) { this.onDrag && this.onDrag(e); }, _onEndDrag: function(e) { this.onEndDrag && this.onEndDrag(e); }, disableAnimation: function() { this.el.classList.remove(this.animationClass); }, enableAnimation: function() { this.el.classList.add(this.animationClass); }, getTranslateX: function() { return parseFloat(this.el.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]); }, setTranslateX: ionic.animationFrameThrottle(function(x) { this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(' + x + 'px, 0, 0)'; }) }); })(ionic); /* * Adapted from Swipe.js 2.0 * * Brad Birdsall * Copyright 2013, MIT License * */ (function(ionic) { 'use strict'; ionic.views.Slider = ionic.views.View.inherit({ initialize: function (options) { var slider = this; var touchStartEvent, touchMoveEvent, touchEndEvent; if (window.navigator.pointerEnabled) { touchStartEvent = 'pointerdown'; touchMoveEvent = 'pointermove'; touchEndEvent = 'pointerup'; } else if (window.navigator.msPointerEnabled) { touchStartEvent = 'MSPointerDown'; touchMoveEvent = 'MSPointerMove'; touchEndEvent = 'MSPointerUp'; } else { touchStartEvent = 'touchstart'; touchMoveEvent = 'touchmove'; touchEndEvent = 'touchend'; } var mouseStartEvent = 'mousedown'; var mouseMoveEvent = 'mousemove'; var mouseEndEvent = 'mouseup'; // utilities var noop = function() {}; // simple no operation function var offloadFn = function(fn) { setTimeout(fn || noop, 0); }; // offload a functions execution // check browser capabilities var browser = { addEventListener: !!window.addEventListener, transitions: (function(temp) { var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition']; for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true; return false; })(document.createElement('swipe')) }; var container = options.el; // quit if no root element if (!container) return; var element = container.children[0]; var slides, slidePos, width, length; options = options || {}; var index = parseInt(options.startSlide, 10) || 0; var speed = options.speed || 300; options.continuous = options.continuous !== undefined ? options.continuous : true; function setup() { // do not setup if the container has no width if (!container.offsetWidth) { return; } // cache slides slides = element.children; length = slides.length; // set continuous to false if only one slide if (slides.length < 2) options.continuous = false; //special case if two slides if (browser.transitions && options.continuous && slides.length < 3) { element.appendChild(slides[0].cloneNode(true)); element.appendChild(element.children[1].cloneNode(true)); slides = element.children; } // create an array to store current positions of each slide slidePos = new Array(slides.length); // determine width of each slide width = container.offsetWidth || container.getBoundingClientRect().width; element.style.width = (slides.length * width) + 'px'; // stack elements var pos = slides.length; while(pos--) { var slide = slides[pos]; slide.style.width = width + 'px'; slide.setAttribute('data-index', pos); if (browser.transitions) { slide.style.left = (pos * -width) + 'px'; move(pos, index > pos ? -width : (index < pos ? width : 0), 0); } } // reposition elements before and after index if (options.continuous && browser.transitions) { move(circle(index - 1), -width, 0); move(circle(index + 1), width, 0); } if (!browser.transitions) element.style.left = (index * -width) + 'px'; container.style.visibility = 'visible'; options.slidesChanged && options.slidesChanged(); } function prev(slideSpeed) { if (options.continuous) slide(index - 1, slideSpeed); else if (index) slide(index - 1, slideSpeed); } function next(slideSpeed) { if (options.continuous) slide(index + 1, slideSpeed); else if (index < slides.length - 1) slide(index + 1, slideSpeed); } function circle(index) { // a simple positive modulo using slides.length return (slides.length + (index % slides.length)) % slides.length; } function slide(to, slideSpeed) { // do nothing if already on requested slide if (index == to) return; if (!slides) { index = to; return; } if (browser.transitions) { var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward // get the actual position of the slide if (options.continuous) { var naturalDirection = direction; direction = -slidePos[circle(to)] / width; // if going forward but to < index, use to = slides.length + to // if going backward but to > index, use to = -slides.length + to if (direction !== naturalDirection) to = -direction * slides.length + to; } var diff = Math.abs(index - to) - 1; // move all the slides between index and to in the right direction while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0); to = circle(to); move(index, width * direction, slideSpeed || speed); move(to, 0, slideSpeed || speed); if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place } else { to = circle(to); animate(index * -width, to * -width, slideSpeed || speed); //no fallback for a circular continuous if the browser does not accept transitions } index = to; offloadFn(options.callback && options.callback(index, slides[index])); } function move(index, dist, speed) { translate(index, dist, speed); slidePos[index] = dist; } function translate(index, dist, speed) { var slide = slides[index]; var style = slide && slide.style; if (!style) return; style.webkitTransitionDuration = style.MozTransitionDuration = style.msTransitionDuration = style.OTransitionDuration = style.transitionDuration = speed + 'ms'; style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)'; style.msTransform = style.MozTransform = style.OTransform = 'translateX(' + dist + 'px)'; } function animate(from, to, speed) { // if not an animation, just reposition if (!speed) { element.style.left = to + 'px'; return; } var start = +new Date(); var timer = setInterval(function() { var timeElap = +new Date() - start; if (timeElap > speed) { element.style.left = to + 'px'; if (delay) begin(); options.transitionEnd && options.transitionEnd.call(event, index, slides[index]); clearInterval(timer); return; } element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px'; }, 4); } // setup auto slideshow var delay = options.auto || 0; var interval; function begin() { interval = setTimeout(next, delay); } function stop() { delay = options.auto || 0; clearTimeout(interval); } // setup initial vars var start = {}; var delta = {}; var isScrolling; // setup event capturing var events = { handleEvent: function(event) { if(!event.touches && event.pageX && event.pageY) { event.touches = [{ pageX: event.pageX, pageY: event.pageY }]; } switch (event.type) { case touchStartEvent: this.start(event); break; case mouseStartEvent: this.start(event); break; case touchMoveEvent: this.touchmove(event); break; case mouseMoveEvent: this.touchmove(event); break; case touchEndEvent: offloadFn(this.end(event)); break; case mouseEndEvent: offloadFn(this.end(event)); break; case 'webkitTransitionEnd': case 'msTransitionEnd': case 'oTransitionEnd': case 'otransitionend': case 'transitionend': offloadFn(this.transitionEnd(event)); break; case 'resize': offloadFn(setup); break; } if (options.stopPropagation) event.stopPropagation(); }, start: function(event) { // prevent to start if there is no valid event if (!event.touches) { return; } var touches = event.touches[0]; // measure start values start = { // get initial touch coords x: touches.pageX, y: touches.pageY, // store time to determine touch duration time: +new Date() }; // used for testing first move event isScrolling = undefined; // reset delta and end measurements delta = {}; // attach touchmove and touchend listeners element.addEventListener(touchMoveEvent, this, false); element.addEventListener(mouseMoveEvent, this, false); element.addEventListener(touchEndEvent, this, false); element.addEventListener(mouseEndEvent, this, false); document.addEventListener(touchEndEvent, this, false); document.addEventListener(mouseEndEvent, this, false); }, touchmove: function(event) { // ensure there is a valid event // ensure swiping with one touch and not pinching // ensure sliding is enabled if (!event.touches || event.touches.length > 1 || event.scale && event.scale !== 1 || slider.slideIsDisabled) { return; } if (options.disableScroll) event.preventDefault(); var touches = event.touches[0]; // measure change in x and y delta = { x: touches.pageX - start.x, y: touches.pageY - start.y }; // determine if scrolling test has run - one time test if ( typeof isScrolling == 'undefined') { isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) ); } // if user is not trying to scroll vertically if (!isScrolling) { // prevent native scrolling event.preventDefault(); // stop slideshow stop(); // increase resistance if first or last slide if (options.continuous) { // we don't add resistance at the end translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0); translate(index, delta.x + slidePos[index], 0); translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0); } else { // If the slider bounces, do the bounce! if(options.bouncing) { delta.x = delta.x / ( (!index && delta.x > 0 || // if first slide and sliding left index == slides.length - 1 && // or if last slide and sliding right delta.x < 0 // and if sliding at all ) ? ( Math.abs(delta.x) / width + 1 ) // determine resistance level : 1 ); // no resistance if false } else { if(width * index - delta.x < 0) { //We are trying scroll past left boundary delta.x = Math.min(delta.x, width * index); //Set delta.x so we don't go past left screen } if(Math.abs(delta.x) > width * (slides.length - index - 1)){ //We are trying to scroll past right bondary delta.x = Math.max( -width * (slides.length - index - 1), delta.x); //Set delta.x so we don't go past right screen } } // translate 1:1 translate(index - 1, delta.x + slidePos[index - 1], 0); translate(index, delta.x + slidePos[index], 0); translate(index + 1, delta.x + slidePos[index + 1], 0); } options.onDrag && options.onDrag(); } }, end: function() { // measure duration var duration = +new Date() - start.time; // determine if slide attempt triggers next/prev slide var isValidSlide = Number(duration) < 250 && // if slide duration is less than 250ms Math.abs(delta.x) > 20 || // and if slide amt is greater than 20px Math.abs(delta.x) > width / 2; // or if slide amt is greater than half the width // determine if slide attempt is past start and end var isPastBounds = (!index && delta.x > 0) || // if first slide and slide amt is greater than 0 (index == slides.length - 1 && delta.x < 0); // or if last slide and slide amt is less than 0 if (options.continuous) isPastBounds = false; // determine direction of swipe (true:right, false:left) var direction = delta.x < 0; // if not scrolling vertically if (!isScrolling) { if (isValidSlide && !isPastBounds) { if (direction) { if (options.continuous) { // we need to get the next in this direction in place move(circle(index - 1), -width, 0); move(circle(index + 2), width, 0); } else { move(index - 1, -width, 0); } move(index, slidePos[index] - width, speed); move(circle(index + 1), slidePos[circle(index + 1)] - width, speed); index = circle(index + 1); } else { if (options.continuous) { // we need to get the next in this direction in place move(circle(index + 1), width, 0); move(circle(index - 2), -width, 0); } else { move(index + 1, width, 0); } move(index, slidePos[index] + width, speed); move(circle(index - 1), slidePos[circle(index - 1)] + width, speed); index = circle(index - 1); } options.callback && options.callback(index, slides[index]); } else { if (options.continuous) { move(circle(index - 1), -width, speed); move(index, 0, speed); move(circle(index + 1), width, speed); } else { move(index - 1, -width, speed); move(index, 0, speed); move(index + 1, width, speed); } } } // kill touchmove and touchend event listeners until touchstart called again element.removeEventListener(touchMoveEvent, events, false); element.removeEventListener(mouseMoveEvent, events, false); element.removeEventListener(touchEndEvent, events, false); element.removeEventListener(mouseEndEvent, events, false); document.removeEventListener(touchEndEvent, events, false); document.removeEventListener(mouseEndEvent, events, false); options.onDragEnd && options.onDragEnd(); }, transitionEnd: function(event) { if (parseInt(event.target.getAttribute('data-index'), 10) == index) { if (delay) begin(); options.transitionEnd && options.transitionEnd.call(event, index, slides[index]); } } }; // Public API this.update = function() { setTimeout(setup); }; this.setup = function() { setup(); }; this.loop = function(value) { if (arguments.length) options.continuous = !!value; return options.continuous; }; this.enableSlide = function(shouldEnable) { if (arguments.length) { this.slideIsDisabled = !shouldEnable; } return !this.slideIsDisabled; }; this.slide = this.select = function(to, speed) { // cancel slideshow stop(); slide(to, speed); }; this.prev = this.previous = function() { // cancel slideshow stop(); prev(); }; this.next = function() { // cancel slideshow stop(); next(); }; this.stop = function() { // cancel slideshow stop(); }; this.start = function() { begin(); }; this.autoPlay = function(newDelay) { if (!delay || delay < 0) { stop(); } else { delay = newDelay; begin(); } }; this.currentIndex = this.selected = function() { // return current index position return index; }; this.slidesCount = this.count = function() { // return total number of slides return length; }; this.kill = function() { // cancel slideshow stop(); // reset element element.style.width = ''; element.style.left = ''; // reset slides so no refs are held on to slides && (slides = []); // removed event listeners if (browser.addEventListener) { // remove current event listeners element.removeEventListener(touchStartEvent, events, false); element.removeEventListener(mouseStartEvent, events, false); element.removeEventListener('webkitTransitionEnd', events, false); element.removeEventListener('msTransitionEnd', events, false); element.removeEventListener('oTransitionEnd', events, false); element.removeEventListener('otransitionend', events, false); element.removeEventListener('transitionend', events, false); window.removeEventListener('resize', events, false); } else { window.onresize = null; } }; this.load = function() { // trigger setup setup(); // start auto slideshow if applicable if (delay) begin(); // add event listeners if (browser.addEventListener) { // set touchstart event on element element.addEventListener(touchStartEvent, events, false); element.addEventListener(mouseStartEvent, events, false); if (browser.transitions) { element.addEventListener('webkitTransitionEnd', events, false); element.addEventListener('msTransitionEnd', events, false); element.addEventListener('oTransitionEnd', events, false); element.addEventListener('otransitionend', events, false); element.addEventListener('transitionend', events, false); } // set resize event on window window.addEventListener('resize', events, false); } else { window.onresize = function () { setup(); }; // to play nice with old IE } }; } }); })(ionic); /*eslint space-after-keywords: 0*/ /** * Swiper 3.2.7 * Most modern mobile touch slider and framework with hardware accelerated transitions * * http://www.idangero.us/swiper/ * * Copyright 2015, Vladimir Kharlampidi * The iDangero.us * http://www.idangero.us/ * * Licensed under MIT * * Released on: December 7, 2015 */ (function () { 'use strict'; var $; /*=========================== Swiper ===========================*/ var Swiper = function (container, params, _scope, $compile) { if (!(this instanceof Swiper)) return new Swiper(container, params); var defaults = { direction: 'horizontal', touchEventsTarget: 'container', initialSlide: 0, speed: 300, // autoplay autoplay: false, autoplayDisableOnInteraction: true, // To support iOS's swipe-to-go-back gesture (when being used in-app, with UIWebView). iOSEdgeSwipeDetection: false, iOSEdgeSwipeThreshold: 20, // Free mode freeMode: false, freeModeMomentum: true, freeModeMomentumRatio: 1, freeModeMomentumBounce: true, freeModeMomentumBounceRatio: 1, freeModeSticky: false, freeModeMinimumVelocity: 0.02, // Autoheight autoHeight: false, // Set wrapper width setWrapperSize: false, // Virtual Translate virtualTranslate: false, // Effects effect: 'slide', // 'slide' or 'fade' or 'cube' or 'coverflow' coverflow: { rotate: 50, stretch: 0, depth: 100, modifier: 1, slideShadows : true }, cube: { slideShadows: true, shadow: true, shadowOffset: 20, shadowScale: 0.94 }, fade: { crossFade: false }, // Parallax parallax: false, // Scrollbar scrollbar: null, scrollbarHide: true, scrollbarDraggable: false, scrollbarSnapOnRelease: false, // Keyboard Mousewheel keyboardControl: false, mousewheelControl: false, mousewheelReleaseOnEdges: false, mousewheelInvert: false, mousewheelForceToAxis: false, mousewheelSensitivity: 1, // Hash Navigation hashnav: false, // Breakpoints breakpoints: undefined, // Slides grid spaceBetween: 0, slidesPerView: 1, slidesPerColumn: 1, slidesPerColumnFill: 'column', slidesPerGroup: 1, centeredSlides: false, slidesOffsetBefore: 0, // in px slidesOffsetAfter: 0, // in px // Round length roundLengths: false, // Touches touchRatio: 1, touchAngle: 45, simulateTouch: true, shortSwipes: true, longSwipes: true, longSwipesRatio: 0.5, longSwipesMs: 300, followFinger: true, onlyExternal: false, threshold: 0, touchMoveStopPropagation: true, // Pagination pagination: null, paginationElement: 'span', paginationClickable: false, paginationHide: false, paginationBulletRender: null, // Resistance resistance: true, resistanceRatio: 0.85, // Next/prev buttons nextButton: null, prevButton: null, // Progress watchSlidesProgress: false, watchSlidesVisibility: false, // Cursor grabCursor: false, // Clicks preventClicks: true, preventClicksPropagation: true, slideToClickedSlide: false, // Lazy Loading lazyLoading: false, lazyLoadingInPrevNext: false, lazyLoadingOnTransitionStart: false, // Images preloadImages: true, updateOnImagesReady: true, // loop loop: false, loopAdditionalSlides: 0, loopedSlides: null, // Control control: undefined, controlInverse: false, controlBy: 'slide', //or 'container' // Swiping/no swiping allowSwipeToPrev: true, allowSwipeToNext: true, swipeHandler: null, //'.swipe-handler', noSwiping: true, noSwipingClass: 'swiper-no-swiping', // NS slideClass: 'swiper-slide', slideActiveClass: 'swiper-slide-active', slideVisibleClass: 'swiper-slide-visible', slideDuplicateClass: 'swiper-slide-duplicate', slideNextClass: 'swiper-slide-next', slidePrevClass: 'swiper-slide-prev', wrapperClass: 'swiper-wrapper', bulletClass: 'swiper-pagination-bullet', bulletActiveClass: 'swiper-pagination-bullet-active', buttonDisabledClass: 'swiper-button-disabled', paginationHiddenClass: 'swiper-pagination-hidden', // Observer observer: false, observeParents: false, // Accessibility a11y: false, prevSlideMessage: 'Previous slide', nextSlideMessage: 'Next slide', firstSlideMessage: 'This is the first slide', lastSlideMessage: 'This is the last slide', paginationBulletMessage: 'Go to slide {{index}}', // Callbacks runCallbacksOnInit: true /* Callbacks: onInit: function (swiper) onDestroy: function (swiper) onClick: function (swiper, e) onTap: function (swiper, e) onDoubleTap: function (swiper, e) onSliderMove: function (swiper, e) onSlideChangeStart: function (swiper) onSlideChangeEnd: function (swiper) onTransitionStart: function (swiper) onTransitionEnd: function (swiper) onImagesReady: function (swiper) onProgress: function (swiper, progress) onTouchStart: function (swiper, e) onTouchMove: function (swiper, e) onTouchMoveOpposite: function (swiper, e) onTouchEnd: function (swiper, e) onReachBeginning: function (swiper) onReachEnd: function (swiper) onSetTransition: function (swiper, duration) onSetTranslate: function (swiper, translate) onAutoplayStart: function (swiper) onAutoplayStop: function (swiper), onLazyImageLoad: function (swiper, slide, image) onLazyImageReady: function (swiper, slide, image) */ }; var initialVirtualTranslate = params && params.virtualTranslate; params = params || {}; var originalParams = {}; for (var param in params) { if (typeof params[param] === 'object' && !(params[param].nodeType || params[param] === window || params[param] === document || (typeof Dom7 !== 'undefined' && params[param] instanceof Dom7) || (typeof jQuery !== 'undefined' && params[param] instanceof jQuery))) { originalParams[param] = {}; for (var deepParam in params[param]) { originalParams[param][deepParam] = params[param][deepParam]; } } else { originalParams[param] = params[param]; } } for (var def in defaults) { if (typeof params[def] === 'undefined') { params[def] = defaults[def]; } else if (typeof params[def] === 'object') { for (var deepDef in defaults[def]) { if (typeof params[def][deepDef] === 'undefined') { params[def][deepDef] = defaults[def][deepDef]; } } } } // Swiper var s = this; // Params s.params = params; s.originalParams = originalParams; // Classname s.classNames = []; /*========================= Dom Library and plugins ===========================*/ if (typeof $ !== 'undefined' && typeof Dom7 !== 'undefined'){ $ = Dom7; } if (typeof $ === 'undefined') { if (typeof Dom7 === 'undefined') { $ = window.Dom7 || window.Zepto || window.jQuery; } else { $ = Dom7; } if (!$) return; } // Export it to Swiper instance s.$ = $; /*========================= Breakpoints ===========================*/ s.currentBreakpoint = undefined; s.getActiveBreakpoint = function () { //Get breakpoint for window width if (!s.params.breakpoints) return false; var breakpoint = false; var points = [], point; for ( point in s.params.breakpoints ) { if (s.params.breakpoints.hasOwnProperty(point)) { points.push(point); } } points.sort(function (a, b) { return parseInt(a, 10) > parseInt(b, 10); }); for (var i = 0; i < points.length; i++) { point = points[i]; if (point >= window.innerWidth && !breakpoint) { breakpoint = point; } } return breakpoint || 'max'; }; s.setBreakpoint = function () { //Set breakpoint for window width and update parameters var breakpoint = s.getActiveBreakpoint(); if (breakpoint && s.currentBreakpoint !== breakpoint) { var breakPointsParams = breakpoint in s.params.breakpoints ? s.params.breakpoints[breakpoint] : s.originalParams; for ( var param in breakPointsParams ) { s.params[param] = breakPointsParams[param]; } s.currentBreakpoint = breakpoint; } }; // Set breakpoint on load if (s.params.breakpoints) { s.setBreakpoint(); } /*========================= Preparation - Define Container, Wrapper and Pagination ===========================*/ s.container = $(container); if (s.container.length === 0) return; if (s.container.length > 1) { s.container.each(function () { new Swiper(this, params); }); return; } // Save instance in container HTML Element and in data s.container[0].swiper = s; s.container.data('swiper', s); s.classNames.push('swiper-container-' + s.params.direction); if (s.params.freeMode) { s.classNames.push('swiper-container-free-mode'); } if (!s.support.flexbox) { s.classNames.push('swiper-container-no-flexbox'); s.params.slidesPerColumn = 1; } if (s.params.autoHeight) { s.classNames.push('swiper-container-autoheight'); } // Enable slides progress when required if (s.params.parallax || s.params.watchSlidesVisibility) { s.params.watchSlidesProgress = true; } // Coverflow / 3D if (['cube', 'coverflow'].indexOf(s.params.effect) >= 0) { if (s.support.transforms3d) { s.params.watchSlidesProgress = true; s.classNames.push('swiper-container-3d'); } else { s.params.effect = 'slide'; } } if (s.params.effect !== 'slide') { s.classNames.push('swiper-container-' + s.params.effect); } if (s.params.effect === 'cube') { s.params.resistanceRatio = 0; s.params.slidesPerView = 1; s.params.slidesPerColumn = 1; s.params.slidesPerGroup = 1; s.params.centeredSlides = false; s.params.spaceBetween = 0; s.params.virtualTranslate = true; s.params.setWrapperSize = false; } if (s.params.effect === 'fade') { s.params.slidesPerView = 1; s.params.slidesPerColumn = 1; s.params.slidesPerGroup = 1; s.params.watchSlidesProgress = true; s.params.spaceBetween = 0; if (typeof initialVirtualTranslate === 'undefined') { s.params.virtualTranslate = true; } } // Grab Cursor if (s.params.grabCursor && s.support.touch) { s.params.grabCursor = false; } // Wrapper s.wrapper = s.container.children('.' + s.params.wrapperClass); // Pagination if (s.params.pagination) { s.paginationContainer = $(s.params.pagination); if (s.params.paginationClickable) { s.paginationContainer.addClass('swiper-pagination-clickable'); } } // Is Horizontal function isH() { return s.params.direction === 'horizontal'; } // RTL s.rtl = isH() && (s.container[0].dir.toLowerCase() === 'rtl' || s.container.css('direction') === 'rtl'); if (s.rtl) { s.classNames.push('swiper-container-rtl'); } // Wrong RTL support if (s.rtl) { s.wrongRTL = s.wrapper.css('display') === '-webkit-box'; } // Columns if (s.params.slidesPerColumn > 1) { s.classNames.push('swiper-container-multirow'); } // Check for Android if (s.device.android) { s.classNames.push('swiper-container-android'); } // Add classes s.container.addClass(s.classNames.join(' ')); // Translate s.translate = 0; // Progress s.progress = 0; // Velocity s.velocity = 0; /*========================= Locks, unlocks ===========================*/ s.lockSwipeToNext = function () { s.params.allowSwipeToNext = false; }; s.lockSwipeToPrev = function () { s.params.allowSwipeToPrev = false; }; s.lockSwipes = function () { s.params.allowSwipeToNext = s.params.allowSwipeToPrev = false; }; s.unlockSwipeToNext = function () { s.params.allowSwipeToNext = true; }; s.unlockSwipeToPrev = function () { s.params.allowSwipeToPrev = true; }; s.unlockSwipes = function () { s.params.allowSwipeToNext = s.params.allowSwipeToPrev = true; }; /*========================= Round helper ===========================*/ function round(a) { return Math.floor(a); } /*========================= Set grab cursor ===========================*/ if (s.params.grabCursor) { s.container[0].style.cursor = 'move'; s.container[0].style.cursor = '-webkit-grab'; s.container[0].style.cursor = '-moz-grab'; s.container[0].style.cursor = 'grab'; } /*========================= Update on Images Ready ===========================*/ s.imagesToLoad = []; s.imagesLoaded = 0; s.loadImage = function (imgElement, src, srcset, checkForComplete, callback) { var image; function onReady () { if (callback) callback(); } if (!imgElement.complete || !checkForComplete) { if (src) { image = new window.Image(); image.onload = onReady; image.onerror = onReady; if (srcset) { image.srcset = srcset; } if (src) { image.src = src; } } else { onReady(); } } else {//image already loaded... onReady(); } }; s.preloadImages = function () { s.imagesToLoad = s.container.find('img'); function _onReady() { if (typeof s === 'undefined' || s === null) return; if (s.imagesLoaded !== undefined) s.imagesLoaded++; if (s.imagesLoaded === s.imagesToLoad.length) { if (s.params.updateOnImagesReady) s.update(); s.emit('onImagesReady', s); } } for (var i = 0; i < s.imagesToLoad.length; i++) { s.loadImage(s.imagesToLoad[i], (s.imagesToLoad[i].currentSrc || s.imagesToLoad[i].getAttribute('src')), (s.imagesToLoad[i].srcset || s.imagesToLoad[i].getAttribute('srcset')), true, _onReady); } }; /*========================= Autoplay ===========================*/ s.autoplayTimeoutId = undefined; s.autoplaying = false; s.autoplayPaused = false; function autoplay() { s.autoplayTimeoutId = setTimeout(function () { if (s.params.loop) { s.fixLoop(); s._slideNext(); } else { if (!s.isEnd) { s._slideNext(); } else { if (!params.autoplayStopOnLast) { s._slideTo(0); } else { s.stopAutoplay(); } } } }, s.params.autoplay); } s.startAutoplay = function () { if (typeof s.autoplayTimeoutId !== 'undefined') return false; if (!s.params.autoplay) return false; if (s.autoplaying) return false; s.autoplaying = true; s.emit('onAutoplayStart', s); autoplay(); }; s.stopAutoplay = function (internal) { if (!s.autoplayTimeoutId) return; if (s.autoplayTimeoutId) clearTimeout(s.autoplayTimeoutId); s.autoplaying = false; s.autoplayTimeoutId = undefined; s.emit('onAutoplayStop', s); }; s.pauseAutoplay = function (speed) { if (s.autoplayPaused) return; if (s.autoplayTimeoutId) clearTimeout(s.autoplayTimeoutId); s.autoplayPaused = true; if (speed === 0) { s.autoplayPaused = false; autoplay(); } else { s.wrapper.transitionEnd(function () { if (!s) return; s.autoplayPaused = false; if (!s.autoplaying) { s.stopAutoplay(); } else { autoplay(); } }); } }; /*========================= Min/Max Translate ===========================*/ s.minTranslate = function () { return (-s.snapGrid[0]); }; s.maxTranslate = function () { return (-s.snapGrid[s.snapGrid.length - 1]); }; /*========================= Slider/slides sizes ===========================*/ s.updateAutoHeight = function () { // Update Height var newHeight = s.slides.eq(s.activeIndex)[0].offsetHeight; if (newHeight) s.wrapper.css('height', s.slides.eq(s.activeIndex)[0].offsetHeight + 'px'); }; s.updateContainerSize = function () { var width, height; if (typeof s.params.width !== 'undefined') { width = s.params.width; } else { width = s.container[0].clientWidth; } if (typeof s.params.height !== 'undefined') { height = s.params.height; } else { height = s.container[0].clientHeight; } if (width === 0 && isH() || height === 0 && !isH()) { return; } //Subtract paddings width = width - parseInt(s.container.css('padding-left'), 10) - parseInt(s.container.css('padding-right'), 10); height = height - parseInt(s.container.css('padding-top'), 10) - parseInt(s.container.css('padding-bottom'), 10); // Store values s.width = width; s.height = height; s.size = isH() ? s.width : s.height; }; s.updateSlidesSize = function () { s.slides = s.wrapper.children('.' + s.params.slideClass); s.snapGrid = []; s.slidesGrid = []; s.slidesSizesGrid = []; var spaceBetween = s.params.spaceBetween, slidePosition = -s.params.slidesOffsetBefore, i, prevSlideSize = 0, index = 0; if (typeof spaceBetween === 'string' && spaceBetween.indexOf('%') >= 0) { spaceBetween = parseFloat(spaceBetween.replace('%', '')) / 100 * s.size; } s.virtualSize = -spaceBetween; // reset margins if (s.rtl) s.slides.css({marginLeft: '', marginTop: ''}); else s.slides.css({marginRight: '', marginBottom: ''}); var slidesNumberEvenToRows; if (s.params.slidesPerColumn > 1) { if (Math.floor(s.slides.length / s.params.slidesPerColumn) === s.slides.length / s.params.slidesPerColumn) { slidesNumberEvenToRows = s.slides.length; } else { slidesNumberEvenToRows = Math.ceil(s.slides.length / s.params.slidesPerColumn) * s.params.slidesPerColumn; } if (s.params.slidesPerView !== 'auto' && s.params.slidesPerColumnFill === 'row') { slidesNumberEvenToRows = Math.max(slidesNumberEvenToRows, s.params.slidesPerView * s.params.slidesPerColumn); } } // Calc slides var slideSize; var slidesPerColumn = s.params.slidesPerColumn; var slidesPerRow = slidesNumberEvenToRows / slidesPerColumn; var numFullColumns = slidesPerRow - (s.params.slidesPerColumn * slidesPerRow - s.slides.length); for (i = 0; i < s.slides.length; i++) { slideSize = 0; var slide = s.slides.eq(i); if (s.params.slidesPerColumn > 1) { // Set slides order var newSlideOrderIndex; var column, row; if (s.params.slidesPerColumnFill === 'column') { column = Math.floor(i / slidesPerColumn); row = i - column * slidesPerColumn; if (column > numFullColumns || (column === numFullColumns && row === slidesPerColumn-1)) { if (++row >= slidesPerColumn) { row = 0; column++; } } newSlideOrderIndex = column + row * slidesNumberEvenToRows / slidesPerColumn; slide .css({ '-webkit-box-ordinal-group': newSlideOrderIndex, '-moz-box-ordinal-group': newSlideOrderIndex, '-ms-flex-order': newSlideOrderIndex, '-webkit-order': newSlideOrderIndex, 'order': newSlideOrderIndex }); } else { row = Math.floor(i / slidesPerRow); column = i - row * slidesPerRow; } slide .css({ 'margin-top': (row !== 0 && s.params.spaceBetween) && (s.params.spaceBetween + 'px') }) .attr('data-swiper-column', column) .attr('data-swiper-row', row); } if (slide.css('display') === 'none') continue; if (s.params.slidesPerView === 'auto') { slideSize = isH() ? slide.outerWidth(true) : slide.outerHeight(true); if (s.params.roundLengths) slideSize = round(slideSize); } else { slideSize = (s.size - (s.params.slidesPerView - 1) * spaceBetween) / s.params.slidesPerView; if (s.params.roundLengths) slideSize = round(slideSize); if (isH()) { s.slides[i].style.width = slideSize + 'px'; } else { s.slides[i].style.height = slideSize + 'px'; } } s.slides[i].swiperSlideSize = slideSize; s.slidesSizesGrid.push(slideSize); if (s.params.centeredSlides) { slidePosition = slidePosition + slideSize / 2 + prevSlideSize / 2 + spaceBetween; if (i === 0) slidePosition = slidePosition - s.size / 2 - spaceBetween; if (Math.abs(slidePosition) < 1 / 1000) slidePosition = 0; if ((index) % s.params.slidesPerGroup === 0) s.snapGrid.push(slidePosition); s.slidesGrid.push(slidePosition); } else { if ((index) % s.params.slidesPerGroup === 0) s.snapGrid.push(slidePosition); s.slidesGrid.push(slidePosition); slidePosition = slidePosition + slideSize + spaceBetween; } s.virtualSize += slideSize + spaceBetween; prevSlideSize = slideSize; index ++; } s.virtualSize = Math.max(s.virtualSize, s.size) + s.params.slidesOffsetAfter; var newSlidesGrid; if ( s.rtl && s.wrongRTL && (s.params.effect === 'slide' || s.params.effect === 'coverflow')) { s.wrapper.css({width: s.virtualSize + s.params.spaceBetween + 'px'}); } if (!s.support.flexbox || s.params.setWrapperSize) { if (isH()) s.wrapper.css({width: s.virtualSize + s.params.spaceBetween + 'px'}); else s.wrapper.css({height: s.virtualSize + s.params.spaceBetween + 'px'}); } if (s.params.slidesPerColumn > 1) { s.virtualSize = (slideSize + s.params.spaceBetween) * slidesNumberEvenToRows; s.virtualSize = Math.ceil(s.virtualSize / s.params.slidesPerColumn) - s.params.spaceBetween; s.wrapper.css({width: s.virtualSize + s.params.spaceBetween + 'px'}); if (s.params.centeredSlides) { newSlidesGrid = []; for (i = 0; i < s.snapGrid.length; i++) { if (s.snapGrid[i] < s.virtualSize + s.snapGrid[0]) newSlidesGrid.push(s.snapGrid[i]); } s.snapGrid = newSlidesGrid; } } // Remove last grid elements depending on width if (!s.params.centeredSlides) { newSlidesGrid = []; for (i = 0; i < s.snapGrid.length; i++) { if (s.snapGrid[i] <= s.virtualSize - s.size) { newSlidesGrid.push(s.snapGrid[i]); } } s.snapGrid = newSlidesGrid; if (Math.floor(s.virtualSize - s.size) > Math.floor(s.snapGrid[s.snapGrid.length - 1])) { s.snapGrid.push(s.virtualSize - s.size); } } if (s.snapGrid.length === 0) s.snapGrid = [0]; if (s.params.spaceBetween !== 0) { if (isH()) { if (s.rtl) s.slides.css({marginLeft: spaceBetween + 'px'}); else s.slides.css({marginRight: spaceBetween + 'px'}); } else s.slides.css({marginBottom: spaceBetween + 'px'}); } if (s.params.watchSlidesProgress) { s.updateSlidesOffset(); } }; s.updateSlidesOffset = function () { for (var i = 0; i < s.slides.length; i++) { s.slides[i].swiperSlideOffset = isH() ? s.slides[i].offsetLeft : s.slides[i].offsetTop; } }; /*========================= Slider/slides progress ===========================*/ s.updateSlidesProgress = function (translate) { if (typeof translate === 'undefined') { translate = s.translate || 0; } if (s.slides.length === 0) return; if (typeof s.slides[0].swiperSlideOffset === 'undefined') s.updateSlidesOffset(); var offsetCenter = -translate; if (s.rtl) offsetCenter = translate; // Visible Slides s.slides.removeClass(s.params.slideVisibleClass); for (var i = 0; i < s.slides.length; i++) { var slide = s.slides[i]; var slideProgress = (offsetCenter - slide.swiperSlideOffset) / (slide.swiperSlideSize + s.params.spaceBetween); if (s.params.watchSlidesVisibility) { var slideBefore = -(offsetCenter - slide.swiperSlideOffset); var slideAfter = slideBefore + s.slidesSizesGrid[i]; var isVisible = (slideBefore >= 0 && slideBefore < s.size) || (slideAfter > 0 && slideAfter <= s.size) || (slideBefore <= 0 && slideAfter >= s.size); if (isVisible) { s.slides.eq(i).addClass(s.params.slideVisibleClass); } } slide.progress = s.rtl ? -slideProgress : slideProgress; } }; s.updateProgress = function (translate) { if (typeof translate === 'undefined') { translate = s.translate || 0; } var translatesDiff = s.maxTranslate() - s.minTranslate(); var wasBeginning = s.isBeginning; var wasEnd = s.isEnd; if (translatesDiff === 0) { s.progress = 0; s.isBeginning = s.isEnd = true; } else { s.progress = (translate - s.minTranslate()) / (translatesDiff); s.isBeginning = s.progress <= 0; s.isEnd = s.progress >= 1; } if (s.isBeginning && !wasBeginning) s.emit('onReachBeginning', s); if (s.isEnd && !wasEnd) s.emit('onReachEnd', s); if (s.params.watchSlidesProgress) s.updateSlidesProgress(translate); s.emit('onProgress', s, s.progress); }; s.updateActiveIndex = function () { var translate = s.rtl ? s.translate : -s.translate; var newActiveIndex, i, snapIndex; for (i = 0; i < s.slidesGrid.length; i ++) { if (typeof s.slidesGrid[i + 1] !== 'undefined') { if (translate >= s.slidesGrid[i] && translate < s.slidesGrid[i + 1] - (s.slidesGrid[i + 1] - s.slidesGrid[i]) / 2) { newActiveIndex = i; } else if (translate >= s.slidesGrid[i] && translate < s.slidesGrid[i + 1]) { newActiveIndex = i + 1; } } else { if (translate >= s.slidesGrid[i]) { newActiveIndex = i; } } } // Normalize slideIndex if (newActiveIndex < 0 || typeof newActiveIndex === 'undefined') newActiveIndex = 0; // for (i = 0; i < s.slidesGrid.length; i++) { // if (- translate >= s.slidesGrid[i]) { // newActiveIndex = i; // } // } snapIndex = Math.floor(newActiveIndex / s.params.slidesPerGroup); if (snapIndex >= s.snapGrid.length) snapIndex = s.snapGrid.length - 1; if (newActiveIndex === s.activeIndex) { return; } s.snapIndex = snapIndex; s.previousIndex = s.activeIndex; s.activeIndex = newActiveIndex; s.updateClasses(); }; /*========================= Classes ===========================*/ s.updateClasses = function () { s.slides.removeClass(s.params.slideActiveClass + ' ' + s.params.slideNextClass + ' ' + s.params.slidePrevClass); var activeSlide = s.slides.eq(s.activeIndex); // Active classes activeSlide.addClass(s.params.slideActiveClass); activeSlide.next('.' + s.params.slideClass).addClass(s.params.slideNextClass); activeSlide.prev('.' + s.params.slideClass).addClass(s.params.slidePrevClass); // Pagination if (s.bullets && s.bullets.length > 0) { s.bullets.removeClass(s.params.bulletActiveClass); var bulletIndex; if (s.params.loop) { bulletIndex = Math.ceil(s.activeIndex - s.loopedSlides)/s.params.slidesPerGroup; if (bulletIndex > s.slides.length - 1 - s.loopedSlides * 2) { bulletIndex = bulletIndex - (s.slides.length - s.loopedSlides * 2); } if (bulletIndex > s.bullets.length - 1) bulletIndex = bulletIndex - s.bullets.length; } else { if (typeof s.snapIndex !== 'undefined') { bulletIndex = s.snapIndex; } else { bulletIndex = s.activeIndex || 0; } } if (s.paginationContainer.length > 1) { s.bullets.each(function () { if ($(this).index() === bulletIndex) $(this).addClass(s.params.bulletActiveClass); }); } else { s.bullets.eq(bulletIndex).addClass(s.params.bulletActiveClass); } } // Next/active buttons if (!s.params.loop) { if (s.params.prevButton) { if (s.isBeginning) { $(s.params.prevButton).addClass(s.params.buttonDisabledClass); if (s.params.a11y && s.a11y) s.a11y.disable($(s.params.prevButton)); } else { $(s.params.prevButton).removeClass(s.params.buttonDisabledClass); if (s.params.a11y && s.a11y) s.a11y.enable($(s.params.prevButton)); } } if (s.params.nextButton) { if (s.isEnd) { $(s.params.nextButton).addClass(s.params.buttonDisabledClass); if (s.params.a11y && s.a11y) s.a11y.disable($(s.params.nextButton)); } else { $(s.params.nextButton).removeClass(s.params.buttonDisabledClass); if (s.params.a11y && s.a11y) s.a11y.enable($(s.params.nextButton)); } } } }; /*========================= Pagination ===========================*/ s.updatePagination = function () { if (!s.params.pagination) return; if (s.paginationContainer && s.paginationContainer.length > 0) { var bulletsHTML = ''; var numberOfBullets = s.params.loop ? Math.ceil((s.slides.length - s.loopedSlides * 2) / s.params.slidesPerGroup) : s.snapGrid.length; for (var i = 0; i < numberOfBullets; i++) { if (s.params.paginationBulletRender) { bulletsHTML += s.params.paginationBulletRender(i, s.params.bulletClass); } else { bulletsHTML += '<' + s.params.paginationElement+' class="' + s.params.bulletClass + '"></' + s.params.paginationElement + '>'; } } s.paginationContainer.html(bulletsHTML); s.bullets = s.paginationContainer.find('.' + s.params.bulletClass); if (s.params.paginationClickable && s.params.a11y && s.a11y) { s.a11y.initPagination(); } } }; /*========================= Common update method ===========================*/ s.update = function (updateTranslate) { s.updateContainerSize(); s.updateSlidesSize(); s.updateProgress(); s.updatePagination(); s.updateClasses(); if (s.params.scrollbar && s.scrollbar) { s.scrollbar.set(); } function forceSetTranslate() { newTranslate = Math.min(Math.max(s.translate, s.maxTranslate()), s.minTranslate()); s.setWrapperTranslate(newTranslate); s.updateActiveIndex(); s.updateClasses(); } if (updateTranslate) { var translated, newTranslate; if (s.controller && s.controller.spline) { s.controller.spline = undefined; } if (s.params.freeMode) { forceSetTranslate(); if (s.params.autoHeight) { s.updateAutoHeight(); } } else { if ((s.params.slidesPerView === 'auto' || s.params.slidesPerView > 1) && s.isEnd && !s.params.centeredSlides) { translated = s.slideTo(s.slides.length - 1, 0, false, true); } else { translated = s.slideTo(s.activeIndex, 0, false, true); } if (!translated) { forceSetTranslate(); } } } else if (s.params.autoHeight) { s.updateAutoHeight(); } }; /*========================= Resize Handler ===========================*/ s.onResize = function (forceUpdatePagination) { //Breakpoints if (s.params.breakpoints) { s.setBreakpoint(); } // Disable locks on resize var allowSwipeToPrev = s.params.allowSwipeToPrev; var allowSwipeToNext = s.params.allowSwipeToNext; s.params.allowSwipeToPrev = s.params.allowSwipeToNext = true; s.updateContainerSize(); s.updateSlidesSize(); if (s.params.slidesPerView === 'auto' || s.params.freeMode || forceUpdatePagination) s.updatePagination(); if (s.params.scrollbar && s.scrollbar) { s.scrollbar.set(); } if (s.controller && s.controller.spline) { s.controller.spline = undefined; } if (s.params.freeMode) { var newTranslate = Math.min(Math.max(s.translate, s.maxTranslate()), s.minTranslate()); s.setWrapperTranslate(newTranslate); s.updateActiveIndex(); s.updateClasses(); if (s.params.autoHeight) { s.updateAutoHeight(); } } else { s.updateClasses(); if ((s.params.slidesPerView === 'auto' || s.params.slidesPerView > 1) && s.isEnd && !s.params.centeredSlides) { s.slideTo(s.slides.length - 1, 0, false, true); } else { s.slideTo(s.activeIndex, 0, false, true); } } // Return locks after resize s.params.allowSwipeToPrev = allowSwipeToPrev; s.params.allowSwipeToNext = allowSwipeToNext; }; /*========================= Events ===========================*/ //Define Touch Events var desktopEvents = ['mousedown', 'mousemove', 'mouseup']; if (window.navigator.pointerEnabled) desktopEvents = ['pointerdown', 'pointermove', 'pointerup']; else if (window.navigator.msPointerEnabled) desktopEvents = ['MSPointerDown', 'MSPointerMove', 'MSPointerUp']; s.touchEvents = { start : s.support.touch || !s.params.simulateTouch ? 'touchstart' : desktopEvents[0], move : s.support.touch || !s.params.simulateTouch ? 'touchmove' : desktopEvents[1], end : s.support.touch || !s.params.simulateTouch ? 'touchend' : desktopEvents[2] }; // WP8 Touch Events Fix if (window.navigator.pointerEnabled || window.navigator.msPointerEnabled) { (s.params.touchEventsTarget === 'container' ? s.container : s.wrapper).addClass('swiper-wp8-' + s.params.direction); } // Attach/detach events s.initEvents = function (detach) { var actionDom = detach ? 'off' : 'on'; var action = detach ? 'removeEventListener' : 'addEventListener'; var touchEventsTarget = s.params.touchEventsTarget === 'container' ? s.container[0] : s.wrapper[0]; var target = s.support.touch ? touchEventsTarget : document; var moveCapture = s.params.nested ? true : false; //Touch Events if (s.browser.ie) { touchEventsTarget[action](s.touchEvents.start, s.onTouchStart, false); target[action](s.touchEvents.move, s.onTouchMove, moveCapture); target[action](s.touchEvents.end, s.onTouchEnd, false); } else { if (s.support.touch) { touchEventsTarget[action](s.touchEvents.start, s.onTouchStart, false); touchEventsTarget[action](s.touchEvents.move, s.onTouchMove, moveCapture); touchEventsTarget[action](s.touchEvents.end, s.onTouchEnd, false); } if (params.simulateTouch && !s.device.ios && !s.device.android) { touchEventsTarget[action]('mousedown', s.onTouchStart, false); document[action]('mousemove', s.onTouchMove, moveCapture); document[action]('mouseup', s.onTouchEnd, false); } } window[action]('resize', s.onResize); // Next, Prev, Index if (s.params.nextButton) { $(s.params.nextButton)[actionDom]('click', s.onClickNext); if (s.params.a11y && s.a11y) $(s.params.nextButton)[actionDom]('keydown', s.a11y.onEnterKey); } if (s.params.prevButton) { $(s.params.prevButton)[actionDom]('click', s.onClickPrev); if (s.params.a11y && s.a11y) $(s.params.prevButton)[actionDom]('keydown', s.a11y.onEnterKey); } if (s.params.pagination && s.params.paginationClickable) { $(s.paginationContainer)[actionDom]('click', '.' + s.params.bulletClass, s.onClickIndex); if (s.params.a11y && s.a11y) $(s.paginationContainer)[actionDom]('keydown', '.' + s.params.bulletClass, s.a11y.onEnterKey); } // Prevent Links Clicks if (s.params.preventClicks || s.params.preventClicksPropagation) touchEventsTarget[action]('click', s.preventClicks, true); }; s.attachEvents = function (detach) { s.initEvents(); }; s.detachEvents = function () { s.initEvents(true); }; /*========================= Handle Clicks ===========================*/ // Prevent Clicks s.allowClick = true; s.preventClicks = function (e) { if (!s.allowClick) { if (s.params.preventClicks) e.preventDefault(); if (s.params.preventClicksPropagation && s.animating) { e.stopPropagation(); e.stopImmediatePropagation(); } } }; // Clicks s.onClickNext = function (e) { e.preventDefault(); if (s.isEnd && !s.params.loop) return; s.slideNext(); }; s.onClickPrev = function (e) { e.preventDefault(); if (s.isBeginning && !s.params.loop) return; s.slidePrev(); }; s.onClickIndex = function (e) { e.preventDefault(); var index = $(this).index() * s.params.slidesPerGroup; if (s.params.loop) index = index + s.loopedSlides; s.slideTo(index); }; /*========================= Handle Touches ===========================*/ function findElementInEvent(e, selector) { var el = $(e.target); if (!el.is(selector)) { if (typeof selector === 'string') { el = el.parents(selector); } else if (selector.nodeType) { var found; el.parents().each(function (index, _el) { if (_el === selector) found = selector; }); if (!found) return undefined; else return selector; } } if (el.length === 0) { return undefined; } return el[0]; } s.updateClickedSlide = function (e) { var slide = findElementInEvent(e, '.' + s.params.slideClass); var slideFound = false; if (slide) { for (var i = 0; i < s.slides.length; i++) { if (s.slides[i] === slide) slideFound = true; } } if (slide && slideFound) { s.clickedSlide = slide; s.clickedIndex = $(slide).index(); } else { s.clickedSlide = undefined; s.clickedIndex = undefined; return; } if (s.params.slideToClickedSlide && s.clickedIndex !== undefined && s.clickedIndex !== s.activeIndex) { var slideToIndex = s.clickedIndex, realIndex, duplicatedSlides; if (s.params.loop) { if (s.animating) return; realIndex = $(s.clickedSlide).attr('data-swiper-slide-index'); if (s.params.centeredSlides) { if ((slideToIndex < s.loopedSlides - s.params.slidesPerView/2) || (slideToIndex > s.slides.length - s.loopedSlides + s.params.slidesPerView/2)) { s.fixLoop(); slideToIndex = s.wrapper.children('.' + s.params.slideClass + '[data-swiper-slide-index="' + realIndex + '"]:not(.swiper-slide-duplicate)').eq(0).index(); setTimeout(function () { s.slideTo(slideToIndex); }, 0); } else { s.slideTo(slideToIndex); } } else { if (slideToIndex > s.slides.length - s.params.slidesPerView) { s.fixLoop(); slideToIndex = s.wrapper.children('.' + s.params.slideClass + '[data-swiper-slide-index="' + realIndex + '"]:not(.swiper-slide-duplicate)').eq(0).index(); setTimeout(function () { s.slideTo(slideToIndex); }, 0); } else { s.slideTo(slideToIndex); } } } else { s.slideTo(slideToIndex); } } }; var isTouched, isMoved, allowTouchCallbacks, touchStartTime, isScrolling, currentTranslate, startTranslate, allowThresholdMove, // Form elements to match formElements = 'input, select, textarea, button', // Last click time lastClickTime = Date.now(), clickTimeout, //Velocities velocities = [], allowMomentumBounce; // Animating Flag s.animating = false; // Touches information s.touches = { startX: 0, startY: 0, currentX: 0, currentY: 0, diff: 0 }; // Touch handlers var isTouchEvent, startMoving; s.onTouchStart = function (e) { if (e.originalEvent) e = e.originalEvent; isTouchEvent = e.type === 'touchstart'; if (!isTouchEvent && 'which' in e && e.which === 3) return; if (s.params.noSwiping && findElementInEvent(e, '.' + s.params.noSwipingClass)) { s.allowClick = true; return; } if (s.params.swipeHandler) { if (!findElementInEvent(e, s.params.swipeHandler)) return; } var startX = s.touches.currentX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX; var startY = s.touches.currentY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY; // Do NOT start if iOS edge swipe is detected. Otherwise iOS app (UIWebView) cannot swipe-to-go-back anymore if(s.device.ios && s.params.iOSEdgeSwipeDetection && startX <= s.params.iOSEdgeSwipeThreshold) { return; } isTouched = true; isMoved = false; allowTouchCallbacks = true; isScrolling = undefined; startMoving = undefined; s.touches.startX = startX; s.touches.startY = startY; touchStartTime = Date.now(); s.allowClick = true; s.updateContainerSize(); s.swipeDirection = undefined; if (s.params.threshold > 0) allowThresholdMove = false; if (e.type !== 'touchstart') { var preventDefault = true; if ($(e.target).is(formElements)) preventDefault = false; if (document.activeElement && $(document.activeElement).is(formElements)) { document.activeElement.blur(); } if (preventDefault) { e.preventDefault(); } } s.emit('onTouchStart', s, e); }; s.onTouchMove = function (e) { if (e.originalEvent) e = e.originalEvent; if (isTouchEvent && e.type === 'mousemove') return; if (e.preventedByNestedSwiper) return; if (s.params.onlyExternal) { // isMoved = true; s.allowClick = false; if (isTouched) { s.touches.startX = s.touches.currentX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX; s.touches.startY = s.touches.currentY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY; touchStartTime = Date.now(); } return; } if (isTouchEvent && document.activeElement) { if (e.target === document.activeElement && $(e.target).is(formElements)) { isMoved = true; s.allowClick = false; return; } } if (allowTouchCallbacks) { s.emit('onTouchMove', s, e); } if (e.targetTouches && e.targetTouches.length > 1) return; s.touches.currentX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX; s.touches.currentY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY; if (typeof isScrolling === 'undefined') { var touchAngle = Math.atan2(Math.abs(s.touches.currentY - s.touches.startY), Math.abs(s.touches.currentX - s.touches.startX)) * 180 / Math.PI; isScrolling = isH() ? touchAngle > s.params.touchAngle : (90 - touchAngle > s.params.touchAngle); } if (isScrolling) { s.emit('onTouchMoveOpposite', s, e); } if (typeof startMoving === 'undefined' && s.browser.ieTouch) { if (s.touches.currentX !== s.touches.startX || s.touches.currentY !== s.touches.startY) { startMoving = true; } } if (!isTouched) return; if (isScrolling) { isTouched = false; return; } if (!startMoving && s.browser.ieTouch) { return; } s.allowClick = false; s.emit('onSliderMove', s, e); e.preventDefault(); if (s.params.touchMoveStopPropagation && !s.params.nested) { e.stopPropagation(); } if (!isMoved) { if (params.loop) { s.fixLoop(); } startTranslate = s.getWrapperTranslate(); s.setWrapperTransition(0); if (s.animating) { s.wrapper.trigger('webkitTransitionEnd transitionend oTransitionEnd MSTransitionEnd msTransitionEnd'); } if (s.params.autoplay && s.autoplaying) { if (s.params.autoplayDisableOnInteraction) { s.stopAutoplay(); } else { s.pauseAutoplay(); } } allowMomentumBounce = false; //Grab Cursor if (s.params.grabCursor) { s.container[0].style.cursor = 'move'; s.container[0].style.cursor = '-webkit-grabbing'; s.container[0].style.cursor = '-moz-grabbin'; s.container[0].style.cursor = 'grabbing'; } } isMoved = true; var diff = s.touches.diff = isH() ? s.touches.currentX - s.touches.startX : s.touches.currentY - s.touches.startY; diff = diff * s.params.touchRatio; if (s.rtl) diff = -diff; s.swipeDirection = diff > 0 ? 'prev' : 'next'; currentTranslate = diff + startTranslate; var disableParentSwiper = true; if ((diff > 0 && currentTranslate > s.minTranslate())) { disableParentSwiper = false; if (s.params.resistance) currentTranslate = s.minTranslate() - 1 + Math.pow(-s.minTranslate() + startTranslate + diff, s.params.resistanceRatio); } else if (diff < 0 && currentTranslate < s.maxTranslate()) { disableParentSwiper = false; if (s.params.resistance) currentTranslate = s.maxTranslate() + 1 - Math.pow(s.maxTranslate() - startTranslate - diff, s.params.resistanceRatio); } if (disableParentSwiper) { e.preventedByNestedSwiper = true; } // Directions locks if (!s.params.allowSwipeToNext && s.swipeDirection === 'next' && currentTranslate < startTranslate) { currentTranslate = startTranslate; } if (!s.params.allowSwipeToPrev && s.swipeDirection === 'prev' && currentTranslate > startTranslate) { currentTranslate = startTranslate; } if (!s.params.followFinger) return; // Threshold if (s.params.threshold > 0) { if (Math.abs(diff) > s.params.threshold || allowThresholdMove) { if (!allowThresholdMove) { allowThresholdMove = true; s.touches.startX = s.touches.currentX; s.touches.startY = s.touches.currentY; currentTranslate = startTranslate; s.touches.diff = isH() ? s.touches.currentX - s.touches.startX : s.touches.currentY - s.touches.startY; return; } } else { currentTranslate = startTranslate; return; } } // Update active index in free mode if (s.params.freeMode || s.params.watchSlidesProgress) { s.updateActiveIndex(); } if (s.params.freeMode) { //Velocity if (velocities.length === 0) { velocities.push({ position: s.touches[isH() ? 'startX' : 'startY'], time: touchStartTime }); } velocities.push({ position: s.touches[isH() ? 'currentX' : 'currentY'], time: (new window.Date()).getTime() }); } // Update progress s.updateProgress(currentTranslate); // Update translate s.setWrapperTranslate(currentTranslate); }; s.onTouchEnd = function (e) { if (e.originalEvent) e = e.originalEvent; if (allowTouchCallbacks) { s.emit('onTouchEnd', s, e); } allowTouchCallbacks = false; if (!isTouched) return; //Return Grab Cursor if (s.params.grabCursor && isMoved && isTouched) { s.container[0].style.cursor = 'move'; s.container[0].style.cursor = '-webkit-grab'; s.container[0].style.cursor = '-moz-grab'; s.container[0].style.cursor = 'grab'; } // Time diff var touchEndTime = Date.now(); var timeDiff = touchEndTime - touchStartTime; // Tap, doubleTap, Click if (s.allowClick) { s.updateClickedSlide(e); s.emit('onTap', s, e); if (timeDiff < 300 && (touchEndTime - lastClickTime) > 300) { if (clickTimeout) clearTimeout(clickTimeout); clickTimeout = setTimeout(function () { if (!s) return; if (s.params.paginationHide && s.paginationContainer.length > 0 && !$(e.target).hasClass(s.params.bulletClass)) { s.paginationContainer.toggleClass(s.params.paginationHiddenClass); } s.emit('onClick', s, e); }, 300); } if (timeDiff < 300 && (touchEndTime - lastClickTime) < 300) { if (clickTimeout) clearTimeout(clickTimeout); s.emit('onDoubleTap', s, e); } } lastClickTime = Date.now(); setTimeout(function () { if (s) s.allowClick = true; }, 0); if (!isTouched || !isMoved || !s.swipeDirection || s.touches.diff === 0 || currentTranslate === startTranslate) { isTouched = isMoved = false; return; } isTouched = isMoved = false; var currentPos; if (s.params.followFinger) { currentPos = s.rtl ? s.translate : -s.translate; } else { currentPos = -currentTranslate; } if (s.params.freeMode) { if (currentPos < -s.minTranslate()) { s.slideTo(s.activeIndex); return; } else if (currentPos > -s.maxTranslate()) { if (s.slides.length < s.snapGrid.length) { s.slideTo(s.snapGrid.length - 1); } else { s.slideTo(s.slides.length - 1); } return; } if (s.params.freeModeMomentum) { if (velocities.length > 1) { var lastMoveEvent = velocities.pop(), velocityEvent = velocities.pop(); var distance = lastMoveEvent.position - velocityEvent.position; var time = lastMoveEvent.time - velocityEvent.time; s.velocity = distance / time; s.velocity = s.velocity / 2; if (Math.abs(s.velocity) < s.params.freeModeMinimumVelocity) { s.velocity = 0; } // this implies that the user stopped moving a finger then released. // There would be no events with distance zero, so the last event is stale. if (time > 150 || (new window.Date().getTime() - lastMoveEvent.time) > 300) { s.velocity = 0; } } else { s.velocity = 0; } velocities.length = 0; var momentumDuration = 1000 * s.params.freeModeMomentumRatio; var momentumDistance = s.velocity * momentumDuration; var newPosition = s.translate + momentumDistance; if (s.rtl) newPosition = - newPosition; var doBounce = false; var afterBouncePosition; var bounceAmount = Math.abs(s.velocity) * 20 * s.params.freeModeMomentumBounceRatio; if (newPosition < s.maxTranslate()) { if (s.params.freeModeMomentumBounce) { if (newPosition + s.maxTranslate() < -bounceAmount) { newPosition = s.maxTranslate() - bounceAmount; } afterBouncePosition = s.maxTranslate(); doBounce = true; allowMomentumBounce = true; } else { newPosition = s.maxTranslate(); } } else if (newPosition > s.minTranslate()) { if (s.params.freeModeMomentumBounce) { if (newPosition - s.minTranslate() > bounceAmount) { newPosition = s.minTranslate() + bounceAmount; } afterBouncePosition = s.minTranslate(); doBounce = true; allowMomentumBounce = true; } else { newPosition = s.minTranslate(); } } else if (s.params.freeModeSticky) { var j = 0, nextSlide; for (j = 0; j < s.snapGrid.length; j += 1) { if (s.snapGrid[j] > -newPosition) { nextSlide = j; break; } } if (Math.abs(s.snapGrid[nextSlide] - newPosition) < Math.abs(s.snapGrid[nextSlide - 1] - newPosition) || s.swipeDirection === 'next') { newPosition = s.snapGrid[nextSlide]; } else { newPosition = s.snapGrid[nextSlide - 1]; } if (!s.rtl) newPosition = - newPosition; } //Fix duration if (s.velocity !== 0) { if (s.rtl) { momentumDuration = Math.abs((-newPosition - s.translate) / s.velocity); } else { momentumDuration = Math.abs((newPosition - s.translate) / s.velocity); } } else if (s.params.freeModeSticky) { s.slideReset(); return; } if (s.params.freeModeMomentumBounce && doBounce) { s.updateProgress(afterBouncePosition); s.setWrapperTransition(momentumDuration); s.setWrapperTranslate(newPosition); s.onTransitionStart(); s.animating = true; s.wrapper.transitionEnd(function () { if (!s || !allowMomentumBounce) return; s.emit('onMomentumBounce', s); s.setWrapperTransition(s.params.speed); s.setWrapperTranslate(afterBouncePosition); s.wrapper.transitionEnd(function () { if (!s) return; s.onTransitionEnd(); }); }); } else if (s.velocity) { s.updateProgress(newPosition); s.setWrapperTransition(momentumDuration); s.setWrapperTranslate(newPosition); s.onTransitionStart(); if (!s.animating) { s.animating = true; s.wrapper.transitionEnd(function () { if (!s) return; s.onTransitionEnd(); }); } } else { s.updateProgress(newPosition); } s.updateActiveIndex(); } if (!s.params.freeModeMomentum || timeDiff >= s.params.longSwipesMs) { s.updateProgress(); s.updateActiveIndex(); } return; } // Find current slide var i, stopIndex = 0, groupSize = s.slidesSizesGrid[0]; for (i = 0; i < s.slidesGrid.length; i += s.params.slidesPerGroup) { if (typeof s.slidesGrid[i + s.params.slidesPerGroup] !== 'undefined') { if (currentPos >= s.slidesGrid[i] && currentPos < s.slidesGrid[i + s.params.slidesPerGroup]) { stopIndex = i; groupSize = s.slidesGrid[i + s.params.slidesPerGroup] - s.slidesGrid[i]; } } else { if (currentPos >= s.slidesGrid[i]) { stopIndex = i; groupSize = s.slidesGrid[s.slidesGrid.length - 1] - s.slidesGrid[s.slidesGrid.length - 2]; } } } // Find current slide size var ratio = (currentPos - s.slidesGrid[stopIndex]) / groupSize; if (timeDiff > s.params.longSwipesMs) { // Long touches if (!s.params.longSwipes) { s.slideTo(s.activeIndex); return; } if (s.swipeDirection === 'next') { if (ratio >= s.params.longSwipesRatio) s.slideTo(stopIndex + s.params.slidesPerGroup); else s.slideTo(stopIndex); } if (s.swipeDirection === 'prev') { if (ratio > (1 - s.params.longSwipesRatio)) s.slideTo(stopIndex + s.params.slidesPerGroup); else s.slideTo(stopIndex); } } else { // Short swipes if (!s.params.shortSwipes) { s.slideTo(s.activeIndex); return; } if (s.swipeDirection === 'next') { s.slideTo(stopIndex + s.params.slidesPerGroup); } if (s.swipeDirection === 'prev') { s.slideTo(stopIndex); } } }; /*========================= Transitions ===========================*/ s._slideTo = function (slideIndex, speed) { return s.slideTo(slideIndex, speed, true, true); }; s.slideTo = function (slideIndex, speed, runCallbacks, internal) { if (typeof runCallbacks === 'undefined') runCallbacks = true; if (typeof slideIndex === 'undefined') slideIndex = 0; if (slideIndex < 0) slideIndex = 0; s.snapIndex = Math.floor(slideIndex / s.params.slidesPerGroup); if (s.snapIndex >= s.snapGrid.length) s.snapIndex = s.snapGrid.length - 1; var translate = - s.snapGrid[s.snapIndex]; // Stop autoplay if (s.params.autoplay && s.autoplaying) { if (internal || !s.params.autoplayDisableOnInteraction) { s.pauseAutoplay(speed); } else { s.stopAutoplay(); } } // Update progress s.updateProgress(translate); // Normalize slideIndex for (var i = 0; i < s.slidesGrid.length; i++) { if (- Math.floor(translate * 100) >= Math.floor(s.slidesGrid[i] * 100)) { slideIndex = i; } } // Directions locks if (!s.params.allowSwipeToNext && translate < s.translate && translate < s.minTranslate()) { return false; } if (!s.params.allowSwipeToPrev && translate > s.translate && translate > s.maxTranslate()) { if ((s.activeIndex || 0) !== slideIndex ) return false; } // Update Index if (typeof speed === 'undefined') speed = s.params.speed; s.previousIndex = s.activeIndex || 0; s.activeIndex = slideIndex; if ((s.rtl && -translate === s.translate) || (!s.rtl && translate === s.translate)) { // Update Height if (s.params.autoHeight) { s.updateAutoHeight(); } s.updateClasses(); if (s.params.effect !== 'slide') { s.setWrapperTranslate(translate); } return false; } s.updateClasses(); s.onTransitionStart(runCallbacks); if (speed === 0) { s.setWrapperTranslate(translate); s.setWrapperTransition(0); s.onTransitionEnd(runCallbacks); } else { s.setWrapperTranslate(translate); s.setWrapperTransition(speed); if (!s.animating) { s.animating = true; s.wrapper.transitionEnd(function () { if (!s) return; s.onTransitionEnd(runCallbacks); }); } } return true; }; s.onTransitionStart = function (runCallbacks) { if (typeof runCallbacks === 'undefined') runCallbacks = true; if (s.params.autoHeight) { s.updateAutoHeight(); } if (s.lazy) s.lazy.onTransitionStart(); if (runCallbacks) { s.emit('onTransitionStart', s); if (s.activeIndex !== s.previousIndex) { s.emit('onSlideChangeStart', s); if (s.activeIndex > s.previousIndex) { s.emit('onSlideNextStart', s); } else { s.emit('onSlidePrevStart', s); } } } }; s.onTransitionEnd = function (runCallbacks) { s.animating = false; s.setWrapperTransition(0); if (typeof runCallbacks === 'undefined') runCallbacks = true; if (s.lazy) s.lazy.onTransitionEnd(); if (runCallbacks) { s.emit('onTransitionEnd', s); if (s.activeIndex !== s.previousIndex) { s.emit('onSlideChangeEnd', s); if (s.activeIndex > s.previousIndex) { s.emit('onSlideNextEnd', s); } else { s.emit('onSlidePrevEnd', s); } } } if (s.params.hashnav && s.hashnav) { s.hashnav.setHash(); } }; s.slideNext = function (runCallbacks, speed, internal) { if (s.params.loop) { if (s.animating) return false; s.fixLoop(); var clientLeft = s.container[0].clientLeft; return s.slideTo(s.activeIndex + s.params.slidesPerGroup, speed, runCallbacks, internal); } else return s.slideTo(s.activeIndex + s.params.slidesPerGroup, speed, runCallbacks, internal); }; s._slideNext = function (speed) { return s.slideNext(true, speed, true); }; s.slidePrev = function (runCallbacks, speed, internal) { if (s.params.loop) { if (s.animating) return false; s.fixLoop(); var clientLeft = s.container[0].clientLeft; return s.slideTo(s.activeIndex - 1, speed, runCallbacks, internal); } else return s.slideTo(s.activeIndex - 1, speed, runCallbacks, internal); }; s._slidePrev = function (speed) { return s.slidePrev(true, speed, true); }; s.slideReset = function (runCallbacks, speed, internal) { return s.slideTo(s.activeIndex, speed, runCallbacks); }; /*========================= Translate/transition helpers ===========================*/ s.setWrapperTransition = function (duration, byController) { s.wrapper.transition(duration); if (s.params.effect !== 'slide' && s.effects[s.params.effect]) { s.effects[s.params.effect].setTransition(duration); } if (s.params.parallax && s.parallax) { s.parallax.setTransition(duration); } if (s.params.scrollbar && s.scrollbar) { s.scrollbar.setTransition(duration); } if (s.params.control && s.controller) { s.controller.setTransition(duration, byController); } s.emit('onSetTransition', s, duration); }; s.setWrapperTranslate = function (translate, updateActiveIndex, byController) { var x = 0, y = 0, z = 0; if (isH()) { x = s.rtl ? -translate : translate; } else { y = translate; } if (s.params.roundLengths) { x = round(x); y = round(y); } if (!s.params.virtualTranslate) { if (s.support.transforms3d) s.wrapper.transform('translate3d(' + x + 'px, ' + y + 'px, ' + z + 'px)'); else s.wrapper.transform('translate(' + x + 'px, ' + y + 'px)'); } s.translate = isH() ? x : y; // Check if we need to update progress var progress; var translatesDiff = s.maxTranslate() - s.minTranslate(); if (translatesDiff === 0) { progress = 0; } else { progress = (translate - s.minTranslate()) / (translatesDiff); } if (progress !== s.progress) { s.updateProgress(translate); } if (updateActiveIndex) s.updateActiveIndex(); if (s.params.effect !== 'slide' && s.effects[s.params.effect]) { s.effects[s.params.effect].setTranslate(s.translate); } if (s.params.parallax && s.parallax) { s.parallax.setTranslate(s.translate); } if (s.params.scrollbar && s.scrollbar) { s.scrollbar.setTranslate(s.translate); } if (s.params.control && s.controller) { s.controller.setTranslate(s.translate, byController); } s.emit('onSetTranslate', s, s.translate); }; s.getTranslate = function (el, axis) { var matrix, curTransform, curStyle, transformMatrix; // automatic axis detection if (typeof axis === 'undefined') { axis = 'x'; } if (s.params.virtualTranslate) { return s.rtl ? -s.translate : s.translate; } curStyle = window.getComputedStyle(el, null); if (window.WebKitCSSMatrix) { curTransform = curStyle.transform || curStyle.webkitTransform; if (curTransform.split(',').length > 6) { curTransform = curTransform.split(', ').map(function(a){ return a.replace(',','.'); }).join(', '); } // Some old versions of Webkit choke when 'none' is passed; pass // empty string instead in this case transformMatrix = new window.WebKitCSSMatrix(curTransform === 'none' ? '' : curTransform); } else { transformMatrix = curStyle.MozTransform || curStyle.OTransform || curStyle.MsTransform || curStyle.msTransform || curStyle.transform || curStyle.getPropertyValue('transform').replace('translate(', 'matrix(1, 0, 0, 1,'); matrix = transformMatrix.toString().split(','); } if (axis === 'x') { //Latest Chrome and webkits Fix if (window.WebKitCSSMatrix) curTransform = transformMatrix.m41; //Crazy IE10 Matrix else if (matrix.length === 16) curTransform = parseFloat(matrix[12]); //Normal Browsers else curTransform = parseFloat(matrix[4]); } if (axis === 'y') { //Latest Chrome and webkits Fix if (window.WebKitCSSMatrix) curTransform = transformMatrix.m42; //Crazy IE10 Matrix else if (matrix.length === 16) curTransform = parseFloat(matrix[13]); //Normal Browsers else curTransform = parseFloat(matrix[5]); } if (s.rtl && curTransform) curTransform = -curTransform; return curTransform || 0; }; s.getWrapperTranslate = function (axis) { if (typeof axis === 'undefined') { axis = isH() ? 'x' : 'y'; } return s.getTranslate(s.wrapper[0], axis); }; /*========================= Observer ===========================*/ s.observers = []; function initObserver(target, options) { options = options || {}; // create an observer instance var ObserverFunc = window.MutationObserver || window.WebkitMutationObserver; var observer = new ObserverFunc(function (mutations) { mutations.forEach(function (mutation) { s.onResize(true); s.emit('onObserverUpdate', s, mutation); }); }); observer.observe(target, { attributes: typeof options.attributes === 'undefined' ? true : options.attributes, childList: typeof options.childList === 'undefined' ? true : options.childList, characterData: typeof options.characterData === 'undefined' ? true : options.characterData }); s.observers.push(observer); } s.initObservers = function () { if (s.params.observeParents) { var containerParents = s.container.parents(); for (var i = 0; i < containerParents.length; i++) { initObserver(containerParents[i]); } } // Observe container initObserver(s.container[0], {childList: false}); // Observe wrapper initObserver(s.wrapper[0], {attributes: false}); }; s.disconnectObservers = function () { for (var i = 0; i < s.observers.length; i++) { s.observers[i].disconnect(); } s.observers = []; }; /*========================= Loop ===========================*/ // Create looped slides s.createLoop = function () { var toRemove = s.wrapper.children('.' + s.params.slideClass + '.' + s.params.slideDuplicateClass); angular.element(toRemove).remove(); var slides = s.wrapper.children('.' + s.params.slideClass); if(s.params.slidesPerView === 'auto' && !s.params.loopedSlides) s.params.loopedSlides = slides.length; s.loopedSlides = parseInt(s.params.loopedSlides || s.params.slidesPerView, 10); s.loopedSlides = s.loopedSlides + s.params.loopAdditionalSlides; if (s.loopedSlides > slides.length) { s.loopedSlides = slides.length; } var prependSlides = [], appendSlides = [], i, scope, newNode; slides.each(function (index, el) { var slide = $(this); if (index < s.loopedSlides) appendSlides.push(el); if (index < slides.length && index >= slides.length - s.loopedSlides) prependSlides.push(el); slide.attr('data-swiper-slide-index', index); }); for (i = 0; i < appendSlides.length; i++) { newNode = angular.element(appendSlides[i]).clone().addClass(s.params.slideDuplicateClass); newNode.removeAttr('ng-transclude'); newNode.removeAttr('ng-repeat'); scope = angular.element(appendSlides[i]).scope(); newNode = $compile(newNode)(scope); angular.element(s.wrapper).append(newNode); //s.wrapper.append($(appendSlides[i].cloneNode(true)).addClass(s.params.slideDuplicateClass)); } for (i = prependSlides.length - 1; i >= 0; i--) { //s.wrapper.prepend($(prependSlides[i].cloneNode(true)).addClass(s.params.slideDuplicateClass)); newNode = angular.element(prependSlides[i]).clone().addClass(s.params.slideDuplicateClass); newNode.removeAttr('ng-transclude'); newNode.removeAttr('ng-repeat'); scope = angular.element(prependSlides[i]).scope(); newNode = $compile(newNode)(scope); angular.element(s.wrapper).prepend(newNode); } }; s.destroyLoop = function () { s.wrapper.children('.' + s.params.slideClass + '.' + s.params.slideDuplicateClass).remove(); s.slides.removeAttr('data-swiper-slide-index'); }; s.fixLoop = function () { var newIndex; //Fix For Negative Oversliding if (s.activeIndex < s.loopedSlides) { newIndex = s.slides.length - s.loopedSlides * 3 + s.activeIndex; newIndex = newIndex + s.loopedSlides; s.slideTo(newIndex, 0, false, true); } //Fix For Positive Oversliding else if ((s.params.slidesPerView === 'auto' && s.activeIndex >= s.loopedSlides * 2) || (s.activeIndex > s.slides.length - s.params.slidesPerView * 2)) { newIndex = -s.slides.length + s.activeIndex + s.loopedSlides; newIndex = newIndex + s.loopedSlides; s.slideTo(newIndex, 0, false, true); } }; /*========================= Append/Prepend/Remove Slides ===========================*/ s.appendSlide = function (slides) { if (s.params.loop) { s.destroyLoop(); } if (typeof slides === 'object' && slides.length) { for (var i = 0; i < slides.length; i++) { if (slides[i]) s.wrapper.append(slides[i]); } } else { s.wrapper.append(slides); } if (s.params.loop) { s.createLoop(); } if (!(s.params.observer && s.support.observer)) { s.update(true); } }; s.prependSlide = function (slides) { if (s.params.loop) { s.destroyLoop(); } var newActiveIndex = s.activeIndex + 1; if (typeof slides === 'object' && slides.length) { for (var i = 0; i < slides.length; i++) { if (slides[i]) s.wrapper.prepend(slides[i]); } newActiveIndex = s.activeIndex + slides.length; } else { s.wrapper.prepend(slides); } if (s.params.loop) { s.createLoop(); } if (!(s.params.observer && s.support.observer)) { s.update(true); } s.slideTo(newActiveIndex, 0, false); }; s.removeSlide = function (slidesIndexes) { if (s.params.loop) { s.destroyLoop(); s.slides = s.wrapper.children('.' + s.params.slideClass); } var newActiveIndex = s.activeIndex, indexToRemove; if (typeof slidesIndexes === 'object' && slidesIndexes.length) { for (var i = 0; i < slidesIndexes.length; i++) { indexToRemove = slidesIndexes[i]; if (s.slides[indexToRemove]) s.slides.eq(indexToRemove).remove(); if (indexToRemove < newActiveIndex) newActiveIndex--; } newActiveIndex = Math.max(newActiveIndex, 0); } else { indexToRemove = slidesIndexes; if (s.slides[indexToRemove]) s.slides.eq(indexToRemove).remove(); if (indexToRemove < newActiveIndex) newActiveIndex--; newActiveIndex = Math.max(newActiveIndex, 0); } if (s.params.loop) { s.createLoop(); } if (!(s.params.observer && s.support.observer)) { s.update(true); } if (s.params.loop) { s.slideTo(newActiveIndex + s.loopedSlides, 0, false); } else { s.slideTo(newActiveIndex, 0, false); } }; s.removeAllSlides = function () { var slidesIndexes = []; for (var i = 0; i < s.slides.length; i++) { slidesIndexes.push(i); } s.removeSlide(slidesIndexes); }; /*========================= Effects ===========================*/ s.effects = { fade: { setTranslate: function () { for (var i = 0; i < s.slides.length; i++) { var slide = s.slides.eq(i); var offset = slide[0].swiperSlideOffset; var tx = -offset; if (!s.params.virtualTranslate) tx = tx - s.translate; var ty = 0; if (!isH()) { ty = tx; tx = 0; } var slideOpacity = s.params.fade.crossFade ? Math.max(1 - Math.abs(slide[0].progress), 0) : 1 + Math.min(Math.max(slide[0].progress, -1), 0); slide .css({ opacity: slideOpacity }) .transform('translate3d(' + tx + 'px, ' + ty + 'px, 0px)'); } }, setTransition: function (duration) { s.slides.transition(duration); if (s.params.virtualTranslate && duration !== 0) { var eventTriggered = false; s.slides.transitionEnd(function () { if (eventTriggered) return; if (!s) return; eventTriggered = true; s.animating = false; var triggerEvents = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd']; for (var i = 0; i < triggerEvents.length; i++) { s.wrapper.trigger(triggerEvents[i]); } }); } } }, cube: { setTranslate: function () { var wrapperRotate = 0, cubeShadow; if (s.params.cube.shadow) { if (isH()) { cubeShadow = s.wrapper.find('.swiper-cube-shadow'); if (cubeShadow.length === 0) { cubeShadow = $('<div class="swiper-cube-shadow"></div>'); s.wrapper.append(cubeShadow); } cubeShadow.css({height: s.width + 'px'}); } else { cubeShadow = s.container.find('.swiper-cube-shadow'); if (cubeShadow.length === 0) { cubeShadow = $('<div class="swiper-cube-shadow"></div>'); s.container.append(cubeShadow); } } } for (var i = 0; i < s.slides.length; i++) { var slide = s.slides.eq(i); var slideAngle = i * 90; var round = Math.floor(slideAngle / 360); if (s.rtl) { slideAngle = -slideAngle; round = Math.floor(-slideAngle / 360); } var progress = Math.max(Math.min(slide[0].progress, 1), -1); var tx = 0, ty = 0, tz = 0; if (i % 4 === 0) { tx = - round * 4 * s.size; tz = 0; } else if ((i - 1) % 4 === 0) { tx = 0; tz = - round * 4 * s.size; } else if ((i - 2) % 4 === 0) { tx = s.size + round * 4 * s.size; tz = s.size; } else if ((i - 3) % 4 === 0) { tx = - s.size; tz = 3 * s.size + s.size * 4 * round; } if (s.rtl) { tx = -tx; } if (!isH()) { ty = tx; tx = 0; } var transform = 'rotateX(' + (isH() ? 0 : -slideAngle) + 'deg) rotateY(' + (isH() ? slideAngle : 0) + 'deg) translate3d(' + tx + 'px, ' + ty + 'px, ' + tz + 'px)'; if (progress <= 1 && progress > -1) { wrapperRotate = i * 90 + progress * 90; if (s.rtl) wrapperRotate = -i * 90 - progress * 90; } slide.transform(transform); if (s.params.cube.slideShadows) { //Set shadows var shadowBefore = isH() ? slide.find('.swiper-slide-shadow-left') : slide.find('.swiper-slide-shadow-top'); var shadowAfter = isH() ? slide.find('.swiper-slide-shadow-right') : slide.find('.swiper-slide-shadow-bottom'); if (shadowBefore.length === 0) { shadowBefore = $('<div class="swiper-slide-shadow-' + (isH() ? 'left' : 'top') + '"></div>'); slide.append(shadowBefore); } if (shadowAfter.length === 0) { shadowAfter = $('<div class="swiper-slide-shadow-' + (isH() ? 'right' : 'bottom') + '"></div>'); slide.append(shadowAfter); } var shadowOpacity = slide[0].progress; if (shadowBefore.length) shadowBefore[0].style.opacity = -slide[0].progress; if (shadowAfter.length) shadowAfter[0].style.opacity = slide[0].progress; } } s.wrapper.css({ '-webkit-transform-origin': '50% 50% -' + (s.size / 2) + 'px', '-moz-transform-origin': '50% 50% -' + (s.size / 2) + 'px', '-ms-transform-origin': '50% 50% -' + (s.size / 2) + 'px', 'transform-origin': '50% 50% -' + (s.size / 2) + 'px' }); if (s.params.cube.shadow) { if (isH()) { cubeShadow.transform('translate3d(0px, ' + (s.width / 2 + s.params.cube.shadowOffset) + 'px, ' + (-s.width / 2) + 'px) rotateX(90deg) rotateZ(0deg) scale(' + (s.params.cube.shadowScale) + ')'); } else { var shadowAngle = Math.abs(wrapperRotate) - Math.floor(Math.abs(wrapperRotate) / 90) * 90; var multiplier = 1.5 - (Math.sin(shadowAngle * 2 * Math.PI / 360) / 2 + Math.cos(shadowAngle * 2 * Math.PI / 360) / 2); var scale1 = s.params.cube.shadowScale, scale2 = s.params.cube.shadowScale / multiplier, offset = s.params.cube.shadowOffset; cubeShadow.transform('scale3d(' + scale1 + ', 1, ' + scale2 + ') translate3d(0px, ' + (s.height / 2 + offset) + 'px, ' + (-s.height / 2 / scale2) + 'px) rotateX(-90deg)'); } } var zFactor = (s.isSafari || s.isUiWebView) ? (-s.size / 2) : 0; s.wrapper.transform('translate3d(0px,0,' + zFactor + 'px) rotateX(' + (isH() ? 0 : wrapperRotate) + 'deg) rotateY(' + (isH() ? -wrapperRotate : 0) + 'deg)'); }, setTransition: function (duration) { s.slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration); if (s.params.cube.shadow && !isH()) { s.container.find('.swiper-cube-shadow').transition(duration); } } }, coverflow: { setTranslate: function () { var transform = s.translate; var center = isH() ? -transform + s.width / 2 : -transform + s.height / 2; var rotate = isH() ? s.params.coverflow.rotate: -s.params.coverflow.rotate; var translate = s.params.coverflow.depth; //Each slide offset from center for (var i = 0, length = s.slides.length; i < length; i++) { var slide = s.slides.eq(i); var slideSize = s.slidesSizesGrid[i]; var slideOffset = slide[0].swiperSlideOffset; var offsetMultiplier = (center - slideOffset - slideSize / 2) / slideSize * s.params.coverflow.modifier; var rotateY = isH() ? rotate * offsetMultiplier : 0; var rotateX = isH() ? 0 : rotate * offsetMultiplier; // var rotateZ = 0 var translateZ = -translate * Math.abs(offsetMultiplier); var translateY = isH() ? 0 : s.params.coverflow.stretch * (offsetMultiplier); var translateX = isH() ? s.params.coverflow.stretch * (offsetMultiplier) : 0; //Fix for ultra small values if (Math.abs(translateX) < 0.001) translateX = 0; if (Math.abs(translateY) < 0.001) translateY = 0; if (Math.abs(translateZ) < 0.001) translateZ = 0; if (Math.abs(rotateY) < 0.001) rotateY = 0; if (Math.abs(rotateX) < 0.001) rotateX = 0; var slideTransform = 'translate3d(' + translateX + 'px,' + translateY + 'px,' + translateZ + 'px) rotateX(' + rotateX + 'deg) rotateY(' + rotateY + 'deg)'; slide.transform(slideTransform); slide[0].style.zIndex = -Math.abs(Math.round(offsetMultiplier)) + 1; if (s.params.coverflow.slideShadows) { //Set shadows var shadowBefore = isH() ? slide.find('.swiper-slide-shadow-left') : slide.find('.swiper-slide-shadow-top'); var shadowAfter = isH() ? slide.find('.swiper-slide-shadow-right') : slide.find('.swiper-slide-shadow-bottom'); if (shadowBefore.length === 0) { shadowBefore = $('<div class="swiper-slide-shadow-' + (isH() ? 'left' : 'top') + '"></div>'); slide.append(shadowBefore); } if (shadowAfter.length === 0) { shadowAfter = $('<div class="swiper-slide-shadow-' + (isH() ? 'right' : 'bottom') + '"></div>'); slide.append(shadowAfter); } if (shadowBefore.length) shadowBefore[0].style.opacity = offsetMultiplier > 0 ? offsetMultiplier : 0; if (shadowAfter.length) shadowAfter[0].style.opacity = (-offsetMultiplier) > 0 ? -offsetMultiplier : 0; } } //Set correct perspective for IE10 if (s.browser.ie) { var ws = s.wrapper[0].style; ws.perspectiveOrigin = center + 'px 50%'; } }, setTransition: function (duration) { s.slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration); } } }; /*========================= Images Lazy Loading ===========================*/ s.lazy = { initialImageLoaded: false, loadImageInSlide: function (index, loadInDuplicate) { if (typeof index === 'undefined') return; if (typeof loadInDuplicate === 'undefined') loadInDuplicate = true; if (s.slides.length === 0) return; var slide = s.slides.eq(index); var img = slide.find('.swiper-lazy:not(.swiper-lazy-loaded):not(.swiper-lazy-loading)'); if (slide.hasClass('swiper-lazy') && !slide.hasClass('swiper-lazy-loaded') && !slide.hasClass('swiper-lazy-loading')) { img = img.add(slide[0]); } if (img.length === 0) return; img.each(function () { var _img = $(this); _img.addClass('swiper-lazy-loading'); var background = _img.attr('data-background'); var src = _img.attr('data-src'), srcset = _img.attr('data-srcset'); s.loadImage(_img[0], (src || background), srcset, false, function () { if (background) { _img.css('background-image', 'url(' + background + ')'); _img.removeAttr('data-background'); } else { if (srcset) { _img.attr('srcset', srcset); _img.removeAttr('data-srcset'); } if (src) { _img.attr('src', src); _img.removeAttr('data-src'); } } _img.addClass('swiper-lazy-loaded').removeClass('swiper-lazy-loading'); slide.find('.swiper-lazy-preloader, .preloader').remove(); if (s.params.loop && loadInDuplicate) { var slideOriginalIndex = slide.attr('data-swiper-slide-index'); if (slide.hasClass(s.params.slideDuplicateClass)) { var originalSlide = s.wrapper.children('[data-swiper-slide-index="' + slideOriginalIndex + '"]:not(.' + s.params.slideDuplicateClass + ')'); s.lazy.loadImageInSlide(originalSlide.index(), false); } else { var duplicatedSlide = s.wrapper.children('.' + s.params.slideDuplicateClass + '[data-swiper-slide-index="' + slideOriginalIndex + '"]'); s.lazy.loadImageInSlide(duplicatedSlide.index(), false); } } s.emit('onLazyImageReady', s, slide[0], _img[0]); }); s.emit('onLazyImageLoad', s, slide[0], _img[0]); }); }, load: function () { var i; if (s.params.watchSlidesVisibility) { s.wrapper.children('.' + s.params.slideVisibleClass).each(function () { s.lazy.loadImageInSlide($(this).index()); }); } else { if (s.params.slidesPerView > 1) { for (i = s.activeIndex; i < s.activeIndex + s.params.slidesPerView ; i++) { if (s.slides[i]) s.lazy.loadImageInSlide(i); } } else { s.lazy.loadImageInSlide(s.activeIndex); } } if (s.params.lazyLoadingInPrevNext) { if (s.params.slidesPerView > 1) { // Next Slides for (i = s.activeIndex + s.params.slidesPerView; i < s.activeIndex + s.params.slidesPerView + s.params.slidesPerView; i++) { if (s.slides[i]) s.lazy.loadImageInSlide(i); } // Prev Slides for (i = s.activeIndex - s.params.slidesPerView; i < s.activeIndex ; i++) { if (s.slides[i]) s.lazy.loadImageInSlide(i); } } else { var nextSlide = s.wrapper.children('.' + s.params.slideNextClass); if (nextSlide.length > 0) s.lazy.loadImageInSlide(nextSlide.index()); var prevSlide = s.wrapper.children('.' + s.params.slidePrevClass); if (prevSlide.length > 0) s.lazy.loadImageInSlide(prevSlide.index()); } } }, onTransitionStart: function () { if (s.params.lazyLoading) { if (s.params.lazyLoadingOnTransitionStart || (!s.params.lazyLoadingOnTransitionStart && !s.lazy.initialImageLoaded)) { s.lazy.load(); } } }, onTransitionEnd: function () { if (s.params.lazyLoading && !s.params.lazyLoadingOnTransitionStart) { s.lazy.load(); } } }; /*========================= Scrollbar ===========================*/ s.scrollbar = { isTouched: false, setDragPosition: function (e) { var sb = s.scrollbar; var x = 0, y = 0; var translate; var pointerPosition = isH() ? ((e.type === 'touchstart' || e.type === 'touchmove') ? e.targetTouches[0].pageX : e.pageX || e.clientX) : ((e.type === 'touchstart' || e.type === 'touchmove') ? e.targetTouches[0].pageY : e.pageY || e.clientY) ; var position = (pointerPosition) - sb.track.offset()[isH() ? 'left' : 'top'] - sb.dragSize / 2; var positionMin = -s.minTranslate() * sb.moveDivider; var positionMax = -s.maxTranslate() * sb.moveDivider; if (position < positionMin) { position = positionMin; } else if (position > positionMax) { position = positionMax; } position = -position / sb.moveDivider; s.updateProgress(position); s.setWrapperTranslate(position, true); }, dragStart: function (e) { var sb = s.scrollbar; sb.isTouched = true; e.preventDefault(); e.stopPropagation(); sb.setDragPosition(e); clearTimeout(sb.dragTimeout); sb.track.transition(0); if (s.params.scrollbarHide) { sb.track.css('opacity', 1); } s.wrapper.transition(100); sb.drag.transition(100); s.emit('onScrollbarDragStart', s); }, dragMove: function (e) { var sb = s.scrollbar; if (!sb.isTouched) return; if (e.preventDefault) e.preventDefault(); else e.returnValue = false; sb.setDragPosition(e); s.wrapper.transition(0); sb.track.transition(0); sb.drag.transition(0); s.emit('onScrollbarDragMove', s); }, dragEnd: function (e) { var sb = s.scrollbar; if (!sb.isTouched) return; sb.isTouched = false; if (s.params.scrollbarHide) { clearTimeout(sb.dragTimeout); sb.dragTimeout = setTimeout(function () { sb.track.css('opacity', 0); sb.track.transition(400); }, 1000); } s.emit('onScrollbarDragEnd', s); if (s.params.scrollbarSnapOnRelease) { s.slideReset(); } }, enableDraggable: function () { var sb = s.scrollbar; var target = s.support.touch ? sb.track : document; $(sb.track).on(s.touchEvents.start, sb.dragStart); $(target).on(s.touchEvents.move, sb.dragMove); $(target).on(s.touchEvents.end, sb.dragEnd); }, disableDraggable: function () { var sb = s.scrollbar; var target = s.support.touch ? sb.track : document; $(sb.track).off(s.touchEvents.start, sb.dragStart); $(target).off(s.touchEvents.move, sb.dragMove); $(target).off(s.touchEvents.end, sb.dragEnd); }, set: function () { if (!s.params.scrollbar) return; var sb = s.scrollbar; sb.track = $(s.params.scrollbar); sb.drag = sb.track.find('.swiper-scrollbar-drag'); if (sb.drag.length === 0) { sb.drag = $('<div class="swiper-scrollbar-drag"></div>'); sb.track.append(sb.drag); } sb.drag[0].style.width = ''; sb.drag[0].style.height = ''; sb.trackSize = isH() ? sb.track[0].offsetWidth : sb.track[0].offsetHeight; sb.divider = s.size / s.virtualSize; sb.moveDivider = sb.divider * (sb.trackSize / s.size); sb.dragSize = sb.trackSize * sb.divider; if (isH()) { sb.drag[0].style.width = sb.dragSize + 'px'; } else { sb.drag[0].style.height = sb.dragSize + 'px'; } if (sb.divider >= 1) { sb.track[0].style.display = 'none'; } else { sb.track[0].style.display = ''; } if (s.params.scrollbarHide) { sb.track[0].style.opacity = 0; } }, setTranslate: function () { if (!s.params.scrollbar) return; var diff; var sb = s.scrollbar; var translate = s.translate || 0; var newPos; var newSize = sb.dragSize; newPos = (sb.trackSize - sb.dragSize) * s.progress; if (s.rtl && isH()) { newPos = -newPos; if (newPos > 0) { newSize = sb.dragSize - newPos; newPos = 0; } else if (-newPos + sb.dragSize > sb.trackSize) { newSize = sb.trackSize + newPos; } } else { if (newPos < 0) { newSize = sb.dragSize + newPos; newPos = 0; } else if (newPos + sb.dragSize > sb.trackSize) { newSize = sb.trackSize - newPos; } } if (isH()) { if (s.support.transforms3d) { sb.drag.transform('translate3d(' + (newPos) + 'px, 0, 0)'); } else { sb.drag.transform('translateX(' + (newPos) + 'px)'); } sb.drag[0].style.width = newSize + 'px'; } else { if (s.support.transforms3d) { sb.drag.transform('translate3d(0px, ' + (newPos) + 'px, 0)'); } else { sb.drag.transform('translateY(' + (newPos) + 'px)'); } sb.drag[0].style.height = newSize + 'px'; } if (s.params.scrollbarHide) { clearTimeout(sb.timeout); sb.track[0].style.opacity = 1; sb.timeout = setTimeout(function () { sb.track[0].style.opacity = 0; sb.track.transition(400); }, 1000); } }, setTransition: function (duration) { if (!s.params.scrollbar) return; s.scrollbar.drag.transition(duration); } }; /*========================= Controller ===========================*/ s.controller = { LinearSpline: function (x, y) { this.x = x; this.y = y; this.lastIndex = x.length - 1; // Given an x value (x2), return the expected y2 value: // (x1,y1) is the known point before given value, // (x3,y3) is the known point after given value. var i1, i3; var l = this.x.length; this.interpolate = function (x2) { if (!x2) return 0; // Get the indexes of x1 and x3 (the array indexes before and after given x2): i3 = binarySearch(this.x, x2); i1 = i3 - 1; // We have our indexes i1 & i3, so we can calculate already: // y2 := ((x2−x1) × (y3−y1)) ÷ (x3−x1) + y1 return ((x2 - this.x[i1]) * (this.y[i3] - this.y[i1])) / (this.x[i3] - this.x[i1]) + this.y[i1]; }; var binarySearch = (function() { var maxIndex, minIndex, guess; return function(array, val) { minIndex = -1; maxIndex = array.length; while (maxIndex - minIndex > 1) if (array[guess = maxIndex + minIndex >> 1] <= val) { minIndex = guess; } else { maxIndex = guess; } return maxIndex; }; })(); }, //xxx: for now i will just save one spline function to to getInterpolateFunction: function(c){ if(!s.controller.spline) s.controller.spline = s.params.loop ? new s.controller.LinearSpline(s.slidesGrid, c.slidesGrid) : new s.controller.LinearSpline(s.snapGrid, c.snapGrid); }, setTranslate: function (translate, byController) { var controlled = s.params.control; var multiplier, controlledTranslate; function setControlledTranslate(c) { // this will create an Interpolate function based on the snapGrids // x is the Grid of the scrolled scroller and y will be the controlled scroller // it makes sense to create this only once and recall it for the interpolation // the function does a lot of value caching for performance translate = c.rtl && c.params.direction === 'horizontal' ? -s.translate : s.translate; if (s.params.controlBy === 'slide') { s.controller.getInterpolateFunction(c); // i am not sure why the values have to be multiplicated this way, tried to invert the snapGrid // but it did not work out controlledTranslate = -s.controller.spline.interpolate(-translate); } if(!controlledTranslate || s.params.controlBy === 'container'){ multiplier = (c.maxTranslate() - c.minTranslate()) / (s.maxTranslate() - s.minTranslate()); controlledTranslate = (translate - s.minTranslate()) * multiplier + c.minTranslate(); } if (s.params.controlInverse) { controlledTranslate = c.maxTranslate() - controlledTranslate; } c.updateProgress(controlledTranslate); c.setWrapperTranslate(controlledTranslate, false, s); c.updateActiveIndex(); } if (s.isArray(controlled)) { for (var i = 0; i < controlled.length; i++) { if (controlled[i] !== byController && controlled[i] instanceof Swiper) { setControlledTranslate(controlled[i]); } } } else if (controlled instanceof Swiper && byController !== controlled) { setControlledTranslate(controlled); } }, setTransition: function (duration, byController) { var controlled = s.params.control; var i; function setControlledTransition(c) { c.setWrapperTransition(duration, s); if (duration !== 0) { c.onTransitionStart(); c.wrapper.transitionEnd(function(){ if (!controlled) return; if (c.params.loop && s.params.controlBy === 'slide') { c.fixLoop(); } c.onTransitionEnd(); }); } } if (s.isArray(controlled)) { for (i = 0; i < controlled.length; i++) { if (controlled[i] !== byController && controlled[i] instanceof Swiper) { setControlledTransition(controlled[i]); } } } else if (controlled instanceof Swiper && byController !== controlled) { setControlledTransition(controlled); } } }; /*========================= Hash Navigation ===========================*/ s.hashnav = { init: function () { if (!s.params.hashnav) return; s.hashnav.initialized = true; var hash = document.location.hash.replace('#', ''); if (!hash) return; var speed = 0; for (var i = 0, length = s.slides.length; i < length; i++) { var slide = s.slides.eq(i); var slideHash = slide.attr('data-hash'); if (slideHash === hash && !slide.hasClass(s.params.slideDuplicateClass)) { var index = slide.index(); s.slideTo(index, speed, s.params.runCallbacksOnInit, true); } } }, setHash: function () { if (!s.hashnav.initialized || !s.params.hashnav) return; document.location.hash = s.slides.eq(s.activeIndex).attr('data-hash') || ''; } }; /*========================= Keyboard Control ===========================*/ function handleKeyboard(e) { if (e.originalEvent) e = e.originalEvent; //jquery fix var kc = e.keyCode || e.charCode; // Directions locks if (!s.params.allowSwipeToNext && (isH() && kc === 39 || !isH() && kc === 40)) { return false; } if (!s.params.allowSwipeToPrev && (isH() && kc === 37 || !isH() && kc === 38)) { return false; } if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) { return; } if (document.activeElement && document.activeElement.nodeName && (document.activeElement.nodeName.toLowerCase() === 'input' || document.activeElement.nodeName.toLowerCase() === 'textarea')) { return; } if (kc === 37 || kc === 39 || kc === 38 || kc === 40) { var inView = false; //Check that swiper should be inside of visible area of window if (s.container.parents('.swiper-slide').length > 0 && s.container.parents('.swiper-slide-active').length === 0) { return; } var windowScroll = { left: window.pageXOffset, top: window.pageYOffset }; var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var swiperOffset = s.container.offset(); if (s.rtl) swiperOffset.left = swiperOffset.left - s.container[0].scrollLeft; var swiperCoord = [ [swiperOffset.left, swiperOffset.top], [swiperOffset.left + s.width, swiperOffset.top], [swiperOffset.left, swiperOffset.top + s.height], [swiperOffset.left + s.width, swiperOffset.top + s.height] ]; for (var i = 0; i < swiperCoord.length; i++) { var point = swiperCoord[i]; if ( point[0] >= windowScroll.left && point[0] <= windowScroll.left + windowWidth && point[1] >= windowScroll.top && point[1] <= windowScroll.top + windowHeight ) { inView = true; } } if (!inView) return; } if (isH()) { if (kc === 37 || kc === 39) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } if ((kc === 39 && !s.rtl) || (kc === 37 && s.rtl)) s.slideNext(); if ((kc === 37 && !s.rtl) || (kc === 39 && s.rtl)) s.slidePrev(); } else { if (kc === 38 || kc === 40) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } if (kc === 40) s.slideNext(); if (kc === 38) s.slidePrev(); } } s.disableKeyboardControl = function () { s.params.keyboardControl = false; $(document).off('keydown', handleKeyboard); }; s.enableKeyboardControl = function () { s.params.keyboardControl = true; $(document).on('keydown', handleKeyboard); }; /*========================= Mousewheel Control ===========================*/ s.mousewheel = { event: false, lastScrollTime: (new window.Date()).getTime() }; if (s.params.mousewheelControl) { try { new window.WheelEvent('wheel'); s.mousewheel.event = 'wheel'; } catch (e) {} if (!s.mousewheel.event && document.onmousewheel !== undefined) { s.mousewheel.event = 'mousewheel'; } if (!s.mousewheel.event) { s.mousewheel.event = 'DOMMouseScroll'; } } function handleMousewheel(e) { if (e.originalEvent) e = e.originalEvent; //jquery fix var we = s.mousewheel.event; var delta = 0; var rtlFactor = s.rtl ? -1 : 1; //Opera & IE if (e.detail) delta = -e.detail; //WebKits else if (we === 'mousewheel') { if (s.params.mousewheelForceToAxis) { if (isH()) { if (Math.abs(e.wheelDeltaX) > Math.abs(e.wheelDeltaY)) delta = e.wheelDeltaX * rtlFactor; else return; } else { if (Math.abs(e.wheelDeltaY) > Math.abs(e.wheelDeltaX)) delta = e.wheelDeltaY; else return; } } else { delta = Math.abs(e.wheelDeltaX) > Math.abs(e.wheelDeltaY) ? - e.wheelDeltaX * rtlFactor : - e.wheelDeltaY; } } //Old FireFox else if (we === 'DOMMouseScroll') delta = -e.detail; //New FireFox else if (we === 'wheel') { if (s.params.mousewheelForceToAxis) { if (isH()) { if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) delta = -e.deltaX * rtlFactor; else return; } else { if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) delta = -e.deltaY; else return; } } else { delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? - e.deltaX * rtlFactor : - e.deltaY; } } if (delta === 0) return; if (s.params.mousewheelInvert) delta = -delta; if (!s.params.freeMode) { if ((new window.Date()).getTime() - s.mousewheel.lastScrollTime > 60) { if (delta < 0) { if ((!s.isEnd || s.params.loop) && !s.animating) s.slideNext(); else if (s.params.mousewheelReleaseOnEdges) return true; } else { if ((!s.isBeginning || s.params.loop) && !s.animating) s.slidePrev(); else if (s.params.mousewheelReleaseOnEdges) return true; } } s.mousewheel.lastScrollTime = (new window.Date()).getTime(); } else { //Freemode or scrollContainer: var position = s.getWrapperTranslate() + delta * s.params.mousewheelSensitivity; var wasBeginning = s.isBeginning, wasEnd = s.isEnd; if (position >= s.minTranslate()) position = s.minTranslate(); if (position <= s.maxTranslate()) position = s.maxTranslate(); s.setWrapperTransition(0); s.setWrapperTranslate(position); s.updateProgress(); s.updateActiveIndex(); if (!wasBeginning && s.isBeginning || !wasEnd && s.isEnd) { s.updateClasses(); } if (s.params.freeModeSticky) { clearTimeout(s.mousewheel.timeout); s.mousewheel.timeout = setTimeout(function () { s.slideReset(); }, 300); } // Return page scroll on edge positions if (position === 0 || position === s.maxTranslate()) return; } if (s.params.autoplay) s.stopAutoplay(); if (e.preventDefault) e.preventDefault(); else e.returnValue = false; return false; } s.disableMousewheelControl = function () { if (!s.mousewheel.event) return false; s.container.off(s.mousewheel.event, handleMousewheel); return true; }; s.enableMousewheelControl = function () { if (!s.mousewheel.event) return false; s.container.on(s.mousewheel.event, handleMousewheel); return true; }; /*========================= Parallax ===========================*/ function setParallaxTransform(el, progress) { el = $(el); var p, pX, pY; var rtlFactor = s.rtl ? -1 : 1; p = el.attr('data-swiper-parallax') || '0'; pX = el.attr('data-swiper-parallax-x'); pY = el.attr('data-swiper-parallax-y'); if (pX || pY) { pX = pX || '0'; pY = pY || '0'; } else { if (isH()) { pX = p; pY = '0'; } else { pY = p; pX = '0'; } } if ((pX).indexOf('%') >= 0) { pX = parseInt(pX, 10) * progress * rtlFactor + '%'; } else { pX = pX * progress * rtlFactor + 'px' ; } if ((pY).indexOf('%') >= 0) { pY = parseInt(pY, 10) * progress + '%'; } else { pY = pY * progress + 'px' ; } el.transform('translate3d(' + pX + ', ' + pY + ',0px)'); } s.parallax = { setTranslate: function () { s.container.children('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function(){ setParallaxTransform(this, s.progress); }); s.slides.each(function () { var slide = $(this); slide.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function () { var progress = Math.min(Math.max(slide[0].progress, -1), 1); setParallaxTransform(this, progress); }); }); }, setTransition: function (duration) { if (typeof duration === 'undefined') duration = s.params.speed; s.container.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function(){ var el = $(this); var parallaxDuration = parseInt(el.attr('data-swiper-parallax-duration'), 10) || duration; if (duration === 0) parallaxDuration = 0; el.transition(parallaxDuration); }); } }; /*========================= Plugins API. Collect all and init all plugins ===========================*/ s._plugins = []; for (var plugin in s.plugins) { var p = s.plugins[plugin](s, s.params[plugin]); if (p) s._plugins.push(p); } // Method to call all plugins event/method s.callPlugins = function (eventName) { for (var i = 0; i < s._plugins.length; i++) { if (eventName in s._plugins[i]) { s._plugins[i][eventName](arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); } } }; /*========================= Events/Callbacks/Plugins Emitter ===========================*/ function normalizeEventName (eventName) { if (eventName.indexOf('on') !== 0) { if (eventName[0] !== eventName[0].toUpperCase()) { eventName = 'on' + eventName[0].toUpperCase() + eventName.substring(1); } else { eventName = 'on' + eventName; } } return eventName; } s.emitterEventListeners = { }; s.emit = function (eventName) { // Trigger callbacks if (s.params[eventName]) { s.params[eventName](arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); } var i; // Trigger events if (s.emitterEventListeners[eventName]) { for (i = 0; i < s.emitterEventListeners[eventName].length; i++) { s.emitterEventListeners[eventName][i](arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); } } // Trigger plugins if (s.callPlugins) s.callPlugins(eventName, arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); }; s.on = function (eventName, handler) { eventName = normalizeEventName(eventName); if (!s.emitterEventListeners[eventName]) s.emitterEventListeners[eventName] = []; s.emitterEventListeners[eventName].push(handler); return s; }; s.off = function (eventName, handler) { var i; eventName = normalizeEventName(eventName); if (typeof handler === 'undefined') { // Remove all handlers for such event s.emitterEventListeners[eventName] = []; return s; } if (!s.emitterEventListeners[eventName] || s.emitterEventListeners[eventName].length === 0) return; for (i = 0; i < s.emitterEventListeners[eventName].length; i++) { if(s.emitterEventListeners[eventName][i] === handler) s.emitterEventListeners[eventName].splice(i, 1); } return s; }; s.once = function (eventName, handler) { eventName = normalizeEventName(eventName); var _handler = function () { handler(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]); s.off(eventName, _handler); }; s.on(eventName, _handler); return s; }; // Accessibility tools s.a11y = { makeFocusable: function ($el) { $el.attr('tabIndex', '0'); return $el; }, addRole: function ($el, role) { $el.attr('role', role); return $el; }, addLabel: function ($el, label) { $el.attr('aria-label', label); return $el; }, disable: function ($el) { $el.attr('aria-disabled', true); return $el; }, enable: function ($el) { $el.attr('aria-disabled', false); return $el; }, onEnterKey: function (event) { if (event.keyCode !== 13) return; if ($(event.target).is(s.params.nextButton)) { s.onClickNext(event); if (s.isEnd) { s.a11y.notify(s.params.lastSlideMessage); } else { s.a11y.notify(s.params.nextSlideMessage); } } else if ($(event.target).is(s.params.prevButton)) { s.onClickPrev(event); if (s.isBeginning) { s.a11y.notify(s.params.firstSlideMessage); } else { s.a11y.notify(s.params.prevSlideMessage); } } if ($(event.target).is('.' + s.params.bulletClass)) { $(event.target)[0].click(); } }, liveRegion: $('<span class="swiper-notification" aria-live="assertive" aria-atomic="true"></span>'), notify: function (message) { var notification = s.a11y.liveRegion; if (notification.length === 0) return; notification.html(''); notification.html(message); }, init: function () { // Setup accessibility if (s.params.nextButton) { var nextButton = $(s.params.nextButton); s.a11y.makeFocusable(nextButton); s.a11y.addRole(nextButton, 'button'); s.a11y.addLabel(nextButton, s.params.nextSlideMessage); } if (s.params.prevButton) { var prevButton = $(s.params.prevButton); s.a11y.makeFocusable(prevButton); s.a11y.addRole(prevButton, 'button'); s.a11y.addLabel(prevButton, s.params.prevSlideMessage); } $(s.container).append(s.a11y.liveRegion); }, initPagination: function () { if (s.params.pagination && s.params.paginationClickable && s.bullets && s.bullets.length) { s.bullets.each(function () { var bullet = $(this); s.a11y.makeFocusable(bullet); s.a11y.addRole(bullet, 'button'); s.a11y.addLabel(bullet, s.params.paginationBulletMessage.replace(/{{index}}/, bullet.index() + 1)); }); } }, destroy: function () { if (s.a11y.liveRegion && s.a11y.liveRegion.length > 0) s.a11y.liveRegion.remove(); } }; /*========================= Init/Destroy ===========================*/ s.init = function () { if (s.params.loop) s.createLoop(); s.updateContainerSize(); s.updateSlidesSize(); s.updatePagination(); if (s.params.scrollbar && s.scrollbar) { s.scrollbar.set(); if (s.params.scrollbarDraggable) { s.scrollbar.enableDraggable(); } } if (s.params.effect !== 'slide' && s.effects[s.params.effect]) { if (!s.params.loop) s.updateProgress(); s.effects[s.params.effect].setTranslate(); } if (s.params.loop) { s.slideTo(s.params.initialSlide + s.loopedSlides, 0, s.params.runCallbacksOnInit); } else { s.slideTo(s.params.initialSlide, 0, s.params.runCallbacksOnInit); if (s.params.initialSlide === 0) { if (s.parallax && s.params.parallax) s.parallax.setTranslate(); if (s.lazy && s.params.lazyLoading) { s.lazy.load(); s.lazy.initialImageLoaded = true; } } } s.attachEvents(); if (s.params.observer && s.support.observer) { s.initObservers(); } if (s.params.preloadImages && !s.params.lazyLoading) { s.preloadImages(); } if (s.params.autoplay) { s.startAutoplay(); } if (s.params.keyboardControl) { if (s.enableKeyboardControl) s.enableKeyboardControl(); } if (s.params.mousewheelControl) { if (s.enableMousewheelControl) s.enableMousewheelControl(); } if (s.params.hashnav) { if (s.hashnav) s.hashnav.init(); } if (s.params.a11y && s.a11y) s.a11y.init(); s.emit('onInit', s); }; // Cleanup dynamic styles s.cleanupStyles = function () { // Container s.container.removeClass(s.classNames.join(' ')).removeAttr('style'); // Wrapper s.wrapper.removeAttr('style'); // Slides if (s.slides && s.slides.length) { s.slides .removeClass([ s.params.slideVisibleClass, s.params.slideActiveClass, s.params.slideNextClass, s.params.slidePrevClass ].join(' ')) .removeAttr('style') .removeAttr('data-swiper-column') .removeAttr('data-swiper-row'); } // Pagination/Bullets if (s.paginationContainer && s.paginationContainer.length) { s.paginationContainer.removeClass(s.params.paginationHiddenClass); } if (s.bullets && s.bullets.length) { s.bullets.removeClass(s.params.bulletActiveClass); } // Buttons if (s.params.prevButton) $(s.params.prevButton).removeClass(s.params.buttonDisabledClass); if (s.params.nextButton) $(s.params.nextButton).removeClass(s.params.buttonDisabledClass); // Scrollbar if (s.params.scrollbar && s.scrollbar) { if (s.scrollbar.track && s.scrollbar.track.length) s.scrollbar.track.removeAttr('style'); if (s.scrollbar.drag && s.scrollbar.drag.length) s.scrollbar.drag.removeAttr('style'); } }; // Destroy s.destroy = function (deleteInstance, cleanupStyles) { // Detach evebts s.detachEvents(); // Stop autoplay s.stopAutoplay(); // Disable draggable if (s.params.scrollbar && s.scrollbar) { if (s.params.scrollbarDraggable) { s.scrollbar.disableDraggable(); } } // Destroy loop if (s.params.loop) { s.destroyLoop(); } // Cleanup styles if (cleanupStyles) { s.cleanupStyles(); } // Disconnect observer s.disconnectObservers(); // Disable keyboard/mousewheel if (s.params.keyboardControl) { if (s.disableKeyboardControl) s.disableKeyboardControl(); } if (s.params.mousewheelControl) { if (s.disableMousewheelControl) s.disableMousewheelControl(); } // Disable a11y if (s.params.a11y && s.a11y) s.a11y.destroy(); // Destroy callback s.emit('onDestroy'); // Delete instance if (deleteInstance !== false) s = null; }; s.init(); // Return swiper instance return s; }; /*================================================== Prototype ====================================================*/ Swiper.prototype = { isSafari: (function () { var ua = navigator.userAgent.toLowerCase(); return (ua.indexOf('safari') >= 0 && ua.indexOf('chrome') < 0 && ua.indexOf('android') < 0); })(), isUiWebView: /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent), isArray: function (arr) { return Object.prototype.toString.apply(arr) === '[object Array]'; }, /*================================================== Browser ====================================================*/ browser: { ie: window.navigator.pointerEnabled || window.navigator.msPointerEnabled, ieTouch: (window.navigator.msPointerEnabled && window.navigator.msMaxTouchPoints > 1) || (window.navigator.pointerEnabled && window.navigator.maxTouchPoints > 1) }, /*================================================== Devices ====================================================*/ device: (function () { var ua = navigator.userAgent; var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/); var ipad = ua.match(/(iPad).*OS\s([\d_]+)/); var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/); var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/); return { ios: ipad || iphone || ipod, android: android }; })(), /*================================================== Feature Detection ====================================================*/ support: { touch : (window.Modernizr && Modernizr.touch === true) || (function () { return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch); })(), transforms3d : (window.Modernizr && Modernizr.csstransforms3d === true) || (function () { var div = document.createElement('div').style; return ('webkitPerspective' in div || 'MozPerspective' in div || 'OPerspective' in div || 'MsPerspective' in div || 'perspective' in div); })(), flexbox: (function () { var div = document.createElement('div').style; var styles = ('alignItems webkitAlignItems webkitBoxAlign msFlexAlign mozBoxAlign webkitFlexDirection msFlexDirection mozBoxDirection mozBoxOrient webkitBoxDirection webkitBoxOrient').split(' '); for (var i = 0; i < styles.length; i++) { if (styles[i] in div) return true; } })(), observer: (function () { return ('MutationObserver' in window || 'WebkitMutationObserver' in window); })() }, /*================================================== Plugins ====================================================*/ plugins: {} }; /*=========================== Dom7 Library ===========================*/ var Dom7 = (function () { var Dom7 = function (arr) { var _this = this, i = 0; // Create array-like object for (i = 0; i < arr.length; i++) { _this[i] = arr[i]; } _this.length = arr.length; // Return collection with methods return this; }; var $ = function (selector, context) { var arr = [], i = 0; if (selector && !context) { if (selector instanceof Dom7) { return selector; } } if (selector) { // String if (typeof selector === 'string') { var els, tempParent, html = selector.trim(); if (html.indexOf('<') >= 0 && html.indexOf('>') >= 0) { var toCreate = 'div'; if (html.indexOf('<li') === 0) toCreate = 'ul'; if (html.indexOf('<tr') === 0) toCreate = 'tbody'; if (html.indexOf('<td') === 0 || html.indexOf('<th') === 0) toCreate = 'tr'; if (html.indexOf('<tbody') === 0) toCreate = 'table'; if (html.indexOf('<option') === 0) toCreate = 'select'; tempParent = document.createElement(toCreate); tempParent.innerHTML = selector; for (i = 0; i < tempParent.childNodes.length; i++) { arr.push(tempParent.childNodes[i]); } } else { if (!context && selector[0] === '#' && !selector.match(/[ .<>:~]/)) { // Pure ID selector els = [document.getElementById(selector.split('#')[1])]; } else { // Other selectors els = (context || document).querySelectorAll(selector); } for (i = 0; i < els.length; i++) { if (els[i]) arr.push(els[i]); } } } // Node/element else if (selector.nodeType || selector === window || selector === document) { arr.push(selector); } //Array of elements or instance of Dom else if (selector.length > 0 && selector[0].nodeType) { for (i = 0; i < selector.length; i++) { arr.push(selector[i]); } } } return new Dom7(arr); }; Dom7.prototype = { // Classes and attriutes addClass: function (className) { if (typeof className === 'undefined') { return this; } var classes = className.split(' '); for (var i = 0; i < classes.length; i++) { for (var j = 0; j < this.length; j++) { this[j].classList.add(classes[i]); } } return this; }, removeClass: function (className) { var classes = className.split(' '); for (var i = 0; i < classes.length; i++) { for (var j = 0; j < this.length; j++) { this[j].classList.remove(classes[i]); } } return this; }, hasClass: function (className) { if (!this[0]) return false; else return this[0].classList.contains(className); }, toggleClass: function (className) { var classes = className.split(' '); for (var i = 0; i < classes.length; i++) { for (var j = 0; j < this.length; j++) { this[j].classList.toggle(classes[i]); } } return this; }, attr: function (attrs, value) { if (arguments.length === 1 && typeof attrs === 'string') { // Get attr if (this[0]) return this[0].getAttribute(attrs); else return undefined; } else { // Set attrs for (var i = 0; i < this.length; i++) { if (arguments.length === 2) { // String this[i].setAttribute(attrs, value); } else { // Object for (var attrName in attrs) { this[i][attrName] = attrs[attrName]; this[i].setAttribute(attrName, attrs[attrName]); } } } return this; } }, removeAttr: function (attr) { for (var i = 0; i < this.length; i++) { this[i].removeAttribute(attr); } return this; }, data: function (key, value) { if (typeof value === 'undefined') { // Get value if (this[0]) { var dataKey = this[0].getAttribute('data-' + key); if (dataKey) return dataKey; else if (this[0].dom7ElementDataStorage && (key in this[0].dom7ElementDataStorage)) return this[0].dom7ElementDataStorage[key]; else return undefined; } else return undefined; } else { // Set value for (var i = 0; i < this.length; i++) { var el = this[i]; if (!el.dom7ElementDataStorage) el.dom7ElementDataStorage = {}; el.dom7ElementDataStorage[key] = value; } return this; } }, // Transforms transform : function (transform) { for (var i = 0; i < this.length; i++) { var elStyle = this[i].style; elStyle.webkitTransform = elStyle.MsTransform = elStyle.msTransform = elStyle.MozTransform = elStyle.OTransform = elStyle.transform = transform; } return this; }, transition: function (duration) { if (typeof duration !== 'string') { duration = duration + 'ms'; } for (var i = 0; i < this.length; i++) { var elStyle = this[i].style; elStyle.webkitTransitionDuration = elStyle.MsTransitionDuration = elStyle.msTransitionDuration = elStyle.MozTransitionDuration = elStyle.OTransitionDuration = elStyle.transitionDuration = duration; } return this; }, //Events on: function (eventName, targetSelector, listener, capture) { function handleLiveEvent(e) { var target = e.target; if ($(target).is(targetSelector)) listener.call(target, e); else { var parents = $(target).parents(); for (var k = 0; k < parents.length; k++) { if ($(parents[k]).is(targetSelector)) listener.call(parents[k], e); } } } var events = eventName.split(' '); var i, j; for (i = 0; i < this.length; i++) { if (typeof targetSelector === 'function' || targetSelector === false) { // Usual events if (typeof targetSelector === 'function') { listener = arguments[1]; capture = arguments[2] || false; } for (j = 0; j < events.length; j++) { this[i].addEventListener(events[j], listener, capture); } } else { //Live events for (j = 0; j < events.length; j++) { if (!this[i].dom7LiveListeners) this[i].dom7LiveListeners = []; this[i].dom7LiveListeners.push({listener: listener, liveListener: handleLiveEvent}); this[i].addEventListener(events[j], handleLiveEvent, capture); } } } return this; }, off: function (eventName, targetSelector, listener, capture) { var events = eventName.split(' '); for (var i = 0; i < events.length; i++) { for (var j = 0; j < this.length; j++) { if (typeof targetSelector === 'function' || targetSelector === false) { // Usual events if (typeof targetSelector === 'function') { listener = arguments[1]; capture = arguments[2] || false; } this[j].removeEventListener(events[i], listener, capture); } else { // Live event if (this[j].dom7LiveListeners) { for (var k = 0; k < this[j].dom7LiveListeners.length; k++) { if (this[j].dom7LiveListeners[k].listener === listener) { this[j].removeEventListener(events[i], this[j].dom7LiveListeners[k].liveListener, capture); } } } } } } return this; }, once: function (eventName, targetSelector, listener, capture) { var dom = this; if (typeof targetSelector === 'function') { targetSelector = false; listener = arguments[1]; capture = arguments[2]; } function proxy(e) { listener(e); dom.off(eventName, targetSelector, proxy, capture); } dom.on(eventName, targetSelector, proxy, capture); }, trigger: function (eventName, eventData) { for (var i = 0; i < this.length; i++) { var evt; try { evt = new window.CustomEvent(eventName, {detail: eventData, bubbles: true, cancelable: true}); } catch (e) { evt = document.createEvent('Event'); evt.initEvent(eventName, true, true); evt.detail = eventData; } this[i].dispatchEvent(evt); } return this; }, transitionEnd: function (callback) { var events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'], i, j, dom = this; function fireCallBack(e) { /*jshint validthis:true */ if (e.target !== this) return; callback.call(this, e); for (i = 0; i < events.length; i++) { dom.off(events[i], fireCallBack); } } if (callback) { for (i = 0; i < events.length; i++) { dom.on(events[i], fireCallBack); } } return this; }, // Sizing/Styles width: function () { if (this[0] === window) { return window.innerWidth; } else { if (this.length > 0) { return parseFloat(this.css('width')); } else { return null; } } }, outerWidth: function (includeMargins) { if (this.length > 0) { if (includeMargins) return this[0].offsetWidth + parseFloat(this.css('margin-right')) + parseFloat(this.css('margin-left')); else return this[0].offsetWidth; } else return null; }, height: function () { if (this[0] === window) { return window.innerHeight; } else { if (this.length > 0) { return parseFloat(this.css('height')); } else { return null; } } }, outerHeight: function (includeMargins) { if (this.length > 0) { if (includeMargins) return this[0].offsetHeight + parseFloat(this.css('margin-top')) + parseFloat(this.css('margin-bottom')); else return this[0].offsetHeight; } else return null; }, offset: function () { if (this.length > 0) { var el = this[0]; var box = el.getBoundingClientRect(); var body = document.body; var clientTop = el.clientTop || body.clientTop || 0; var clientLeft = el.clientLeft || body.clientLeft || 0; var scrollTop = window.pageYOffset || el.scrollTop; var scrollLeft = window.pageXOffset || el.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; } else { return null; } }, css: function (props, value) { var i; if (arguments.length === 1) { if (typeof props === 'string') { if (this[0]) return window.getComputedStyle(this[0], null).getPropertyValue(props); } else { for (i = 0; i < this.length; i++) { for (var prop in props) { this[i].style[prop] = props[prop]; } } return this; } } if (arguments.length === 2 && typeof props === 'string') { for (i = 0; i < this.length; i++) { this[i].style[props] = value; } return this; } return this; }, //Dom manipulation each: function (callback) { for (var i = 0; i < this.length; i++) { callback.call(this[i], i, this[i]); } return this; }, html: function (html) { if (typeof html === 'undefined') { return this[0] ? this[0].innerHTML : undefined; } else { for (var i = 0; i < this.length; i++) { this[i].innerHTML = html; } return this; } }, is: function (selector) { if (!this[0]) return false; var compareWith, i; if (typeof selector === 'string') { var el = this[0]; if (el === document) return selector === document; if (el === window) return selector === window; if (el.matches) return el.matches(selector); else if (el.webkitMatchesSelector) return el.webkitMatchesSelector(selector); else if (el.mozMatchesSelector) return el.mozMatchesSelector(selector); else if (el.msMatchesSelector) return el.msMatchesSelector(selector); else { compareWith = $(selector); for (i = 0; i < compareWith.length; i++) { if (compareWith[i] === this[0]) return true; } return false; } } else if (selector === document) return this[0] === document; else if (selector === window) return this[0] === window; else { if (selector.nodeType || selector instanceof Dom7) { compareWith = selector.nodeType ? [selector] : selector; for (i = 0; i < compareWith.length; i++) { if (compareWith[i] === this[0]) return true; } return false; } return false; } }, index: function () { if (this[0]) { var child = this[0]; var i = 0; while ((child = child.previousSibling) !== null) { if (child.nodeType === 1) i++; } return i; } else return undefined; }, eq: function (index) { if (typeof index === 'undefined') return this; var length = this.length; var returnIndex; if (index > length - 1) { return new Dom7([]); } if (index < 0) { returnIndex = length + index; if (returnIndex < 0) return new Dom7([]); else return new Dom7([this[returnIndex]]); } return new Dom7([this[index]]); }, append: function (newChild) { var i, j; for (i = 0; i < this.length; i++) { if (typeof newChild === 'string') { var tempDiv = document.createElement('div'); tempDiv.innerHTML = newChild; while (tempDiv.firstChild) { this[i].appendChild(tempDiv.firstChild); } } else if (newChild instanceof Dom7) { for (j = 0; j < newChild.length; j++) { this[i].appendChild(newChild[j]); } } else { this[i].appendChild(newChild); } } return this; }, prepend: function (newChild) { var i, j; for (i = 0; i < this.length; i++) { if (typeof newChild === 'string') { var tempDiv = document.createElement('div'); tempDiv.innerHTML = newChild; for (j = tempDiv.childNodes.length - 1; j >= 0; j--) { this[i].insertBefore(tempDiv.childNodes[j], this[i].childNodes[0]); } // this[i].insertAdjacentHTML('afterbegin', newChild); } else if (newChild instanceof Dom7) { for (j = 0; j < newChild.length; j++) { this[i].insertBefore(newChild[j], this[i].childNodes[0]); } } else { this[i].insertBefore(newChild, this[i].childNodes[0]); } } return this; }, insertBefore: function (selector) { var before = $(selector); for (var i = 0; i < this.length; i++) { if (before.length === 1) { before[0].parentNode.insertBefore(this[i], before[0]); } else if (before.length > 1) { for (var j = 0; j < before.length; j++) { before[j].parentNode.insertBefore(this[i].cloneNode(true), before[j]); } } } }, insertAfter: function (selector) { var after = $(selector); for (var i = 0; i < this.length; i++) { if (after.length === 1) { after[0].parentNode.insertBefore(this[i], after[0].nextSibling); } else if (after.length > 1) { for (var j = 0; j < after.length; j++) { after[j].parentNode.insertBefore(this[i].cloneNode(true), after[j].nextSibling); } } } }, next: function (selector) { if (this.length > 0) { if (selector) { if (this[0].nextElementSibling && $(this[0].nextElementSibling).is(selector)) return new Dom7([this[0].nextElementSibling]); else return new Dom7([]); } else { if (this[0].nextElementSibling) return new Dom7([this[0].nextElementSibling]); else return new Dom7([]); } } else return new Dom7([]); }, nextAll: function (selector) { var nextEls = []; var el = this[0]; if (!el) return new Dom7([]); while (el.nextElementSibling) { var next = el.nextElementSibling; if (selector) { if($(next).is(selector)) nextEls.push(next); } else nextEls.push(next); el = next; } return new Dom7(nextEls); }, prev: function (selector) { if (this.length > 0) { if (selector) { if (this[0].previousElementSibling && $(this[0].previousElementSibling).is(selector)) return new Dom7([this[0].previousElementSibling]); else return new Dom7([]); } else { if (this[0].previousElementSibling) return new Dom7([this[0].previousElementSibling]); else return new Dom7([]); } } else return new Dom7([]); }, prevAll: function (selector) { var prevEls = []; var el = this[0]; if (!el) return new Dom7([]); while (el.previousElementSibling) { var prev = el.previousElementSibling; if (selector) { if($(prev).is(selector)) prevEls.push(prev); } else prevEls.push(prev); el = prev; } return new Dom7(prevEls); }, parent: function (selector) { var parents = []; for (var i = 0; i < this.length; i++) { if (selector) { if ($(this[i].parentNode).is(selector)) parents.push(this[i].parentNode); } else { parents.push(this[i].parentNode); } } return $($.unique(parents)); }, parents: function (selector) { var parents = []; for (var i = 0; i < this.length; i++) { var parent = this[i].parentNode; while (parent) { if (selector) { if ($(parent).is(selector)) parents.push(parent); } else { parents.push(parent); } parent = parent.parentNode; } } return $($.unique(parents)); }, find : function (selector) { var foundElements = []; for (var i = 0; i < this.length; i++) { var found = this[i].querySelectorAll(selector); for (var j = 0; j < found.length; j++) { foundElements.push(found[j]); } } return new Dom7(foundElements); }, children: function (selector) { var children = []; for (var i = 0; i < this.length; i++) { var childNodes = this[i].childNodes; for (var j = 0; j < childNodes.length; j++) { if (!selector) { if (childNodes[j].nodeType === 1) children.push(childNodes[j]); } else { if (childNodes[j].nodeType === 1 && $(childNodes[j]).is(selector)) children.push(childNodes[j]); } } } return new Dom7($.unique(children)); }, remove: function () { for (var i = 0; i < this.length; i++) { if (this[i].parentNode) this[i].parentNode.removeChild(this[i]); } return this; }, add: function () { var dom = this; var i, j; for (i = 0; i < arguments.length; i++) { var toAdd = $(arguments[i]); for (j = 0; j < toAdd.length; j++) { dom[dom.length] = toAdd[j]; dom.length++; } } return dom; } }; $.fn = Dom7.prototype; $.unique = function (arr) { var unique = []; for (var i = 0; i < arr.length; i++) { if (unique.indexOf(arr[i]) === -1) unique.push(arr[i]); } return unique; }; return $; })(); /*=========================== Get Dom libraries ===========================*/ var swiperDomPlugins = ['jQuery', 'Zepto', 'Dom7']; for (var i = 0; i < swiperDomPlugins.length; i++) { if (window[swiperDomPlugins[i]]) { addLibraryPlugin(window[swiperDomPlugins[i]]); } } // Required DOM Plugins var domLib; if (typeof Dom7 === 'undefined') { domLib = window.Dom7 || window.Zepto || window.jQuery; } else { domLib = Dom7; } /*=========================== Add .swiper plugin from Dom libraries ===========================*/ function addLibraryPlugin(lib) { lib.fn.swiper = function (params) { var firstInstance; lib(this).each(function () { var s = new Swiper(this, params); if (!firstInstance) firstInstance = s; }); return firstInstance; }; } if (domLib) { if (!('transitionEnd' in domLib.fn)) { domLib.fn.transitionEnd = function (callback) { var events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'], i, j, dom = this; function fireCallBack(e) { /*jshint validthis:true */ if (e.target !== this) return; callback.call(this, e); for (i = 0; i < events.length; i++) { dom.off(events[i], fireCallBack); } } if (callback) { for (i = 0; i < events.length; i++) { dom.on(events[i], fireCallBack); } } return this; }; } if (!('transform' in domLib.fn)) { domLib.fn.transform = function (transform) { for (var i = 0; i < this.length; i++) { var elStyle = this[i].style; elStyle.webkitTransform = elStyle.MsTransform = elStyle.msTransform = elStyle.MozTransform = elStyle.OTransform = elStyle.transform = transform; } return this; }; } if (!('transition' in domLib.fn)) { domLib.fn.transition = function (duration) { if (typeof duration !== 'string') { duration = duration + 'ms'; } for (var i = 0; i < this.length; i++) { var elStyle = this[i].style; elStyle.webkitTransitionDuration = elStyle.MsTransitionDuration = elStyle.msTransitionDuration = elStyle.MozTransitionDuration = elStyle.OTransitionDuration = elStyle.transitionDuration = duration; } return this; }; } } ionic.views.Swiper = Swiper; })(); (function(ionic) { 'use strict'; ionic.views.Toggle = ionic.views.View.inherit({ initialize: function(opts) { var self = this; this.el = opts.el; this.checkbox = opts.checkbox; this.track = opts.track; this.handle = opts.handle; this.openPercent = -1; this.onChange = opts.onChange || function() {}; this.triggerThreshold = opts.triggerThreshold || 20; this.dragStartHandler = function(e) { self.dragStart(e); }; this.dragHandler = function(e) { self.drag(e); }; this.holdHandler = function(e) { self.hold(e); }; this.releaseHandler = function(e) { self.release(e); }; this.dragStartGesture = ionic.onGesture('dragstart', this.dragStartHandler, this.el); this.dragGesture = ionic.onGesture('drag', this.dragHandler, this.el); this.dragHoldGesture = ionic.onGesture('hold', this.holdHandler, this.el); this.dragReleaseGesture = ionic.onGesture('release', this.releaseHandler, this.el); }, destroy: function() { ionic.offGesture(this.dragStartGesture, 'dragstart', this.dragStartGesture); ionic.offGesture(this.dragGesture, 'drag', this.dragGesture); ionic.offGesture(this.dragHoldGesture, 'hold', this.holdHandler); ionic.offGesture(this.dragReleaseGesture, 'release', this.releaseHandler); }, tap: function() { if(this.el.getAttribute('disabled') !== 'disabled') { this.val( !this.checkbox.checked ); } }, dragStart: function(e) { if(this.checkbox.disabled) return; this._dragInfo = { width: this.el.offsetWidth, left: this.el.offsetLeft, right: this.el.offsetLeft + this.el.offsetWidth, triggerX: this.el.offsetWidth / 2, initialState: this.checkbox.checked }; // Stop any parent dragging e.gesture.srcEvent.preventDefault(); // Trigger hold styles this.hold(e); }, drag: function(e) { var self = this; if(!this._dragInfo) { return; } // Stop any parent dragging e.gesture.srcEvent.preventDefault(); ionic.requestAnimationFrame(function () { if (!self._dragInfo) { return; } var px = e.gesture.touches[0].pageX - self._dragInfo.left; var mx = self._dragInfo.width - self.triggerThreshold; // The initial state was on, so "tend towards" on if(self._dragInfo.initialState) { if(px < self.triggerThreshold) { self.setOpenPercent(0); } else if(px > self._dragInfo.triggerX) { self.setOpenPercent(100); } } else { // The initial state was off, so "tend towards" off if(px < self._dragInfo.triggerX) { self.setOpenPercent(0); } else if(px > mx) { self.setOpenPercent(100); } } }); }, endDrag: function() { this._dragInfo = null; }, hold: function() { this.el.classList.add('dragging'); }, release: function(e) { this.el.classList.remove('dragging'); this.endDrag(e); }, setOpenPercent: function(openPercent) { // only make a change if the new open percent has changed if(this.openPercent < 0 || (openPercent < (this.openPercent - 3) || openPercent > (this.openPercent + 3) ) ) { this.openPercent = openPercent; if(openPercent === 0) { this.val(false); } else if(openPercent === 100) { this.val(true); } else { var openPixel = Math.round( (openPercent / 100) * this.track.offsetWidth - (this.handle.offsetWidth) ); openPixel = (openPixel < 1 ? 0 : openPixel); this.handle.style[ionic.CSS.TRANSFORM] = 'translate3d(' + openPixel + 'px,0,0)'; } } }, val: function(value) { if(value === true || value === false) { if(this.handle.style[ionic.CSS.TRANSFORM] !== "") { this.handle.style[ionic.CSS.TRANSFORM] = ""; } this.checkbox.checked = value; this.openPercent = (value ? 100 : 0); this.onChange && this.onChange(); } return this.checkbox.checked; } }); })(ionic); })();
goog.provide('ee.MapLayerOverlay'); goog.require('ee.AbstractOverlay'); goog.require('ee.MapTileManager'); goog.require('ee.TileEvent'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.iter'); goog.require('goog.net.EventType'); goog.require('goog.structs.Set'); goog.require('goog.style'); goog.forwardDeclare('ee.data.Profiler'); /** * A google.maps.MapType implementation used to display Earth Engine tiles. * This class behaves much like an ImageMapType, but emits events when tiles * are loaded. * @export * @ignore * @deprecated Use ee.layers.ImageOverlay instead. */ ee.MapLayerOverlay = class extends ee.AbstractOverlay { /** * @param {string} url The url for fetching this layer's tiles. * @param {string} mapId The map ID for fetching this layer's tiles. * @param {string} token The temporary token for fetching tiles. * @param {Object} init Initialization options, of the same form as a * google.maps.ImageMapTypeOptions object. * @param {ee.data.Profiler=} opt_profiler Map tile calculation cost will be * sent to this profiler, if its enabled flag is set. */ constructor(url, mapId, token, init, opt_profiler) { super(url, mapId, token, init, opt_profiler); // Set ImageMapTypeOptions properties. this.minZoom = init.minZoom || 0; this.maxZoom = init.maxZoom || 20; if (!window['google'] || !window['google']['maps']) { throw Error('Google Maps API hasn\'t been initialized.'); } this.tileSize = init.tileSize || new google.maps.Size(256, 256); this.isPng = (init.isPng !== undefined) ? init.isPng : true; this.name = init.name; /** @private {goog.structs.Set} The set of loaded tiles. */ this.tiles_ = new goog.structs.Set(); /** @private {number} The layer's opacity. */ this.opacity_ = 1.0; /** @private {boolean} Whether the layer is currently visible. */ this.visible_ = true; /** * Map tile calculation cost will be sent to this profiler, if its enabled * flag is set. * @private {?ee.data.Profiler} */ this.profiler_ = opt_profiler || null; } /** * Adds a callback to be fired each time a tile is loaded. * @param {function(ee.TileEvent)} callback The function to call when a * tile has loaded. * @return {!Object} An ID which can be passed to removeTileCallback() to * remove the callback. * @export */ addTileCallback(callback) { return /** @type {!Object} */ (goog.events.listen( this, ee.AbstractOverlay.EventType.TILE_LOADED, callback)); } /** * Removes the callback with the given ID. * @param {!Object} callbackId The ID returned by addTileLoaded() * when the callback was registered. * @export */ removeTileCallback(callbackId) { goog.events.unlistenByKey(/** @type {goog.events.Key} */ (callbackId)); } /** * Send an event about a change in the number of outstanding tiles. * @private */ dispatchTileEvent_() { this.dispatchEvent(new ee.TileEvent(this.tilesLoading.length)); } /** * Implements getTile() for the google.maps.MapType interface. * @param {!google.maps.Point} coord Position of tile. * @param {number} zoom Zoom level. * @param {Node} ownerDocument Parent document. * @return {Node} Element to be displayed as a map tile. */ getTile(coord, zoom, ownerDocument) { var maxCoord = 1 << zoom; if (zoom < this.minZoom || coord.y < 0 || coord.y >= maxCoord) { // Construct and return the tile immediately. var img = ownerDocument.createElement('IMG'); img.style.width = '0px'; img.style.height = '0px'; return img; } var profiling = this.profiler_ && this.profiler_.isEnabled(); var tileId = this.getTileId(coord, zoom); var src = [this.url, tileId].join('/') + '?token=' + this.token; if (profiling) { src += '&profiling=1'; } // Append 1) a unique counter string to the tileid to make sure that // repeated requests for the same tile and cancellations thereof // (which may occur if the user quickly moves the map around) // don't overwrite each other's state, and 2) the unique token for this // layer to differentiate its tile requests from other tile requests // for other layers with the same map ID. var uniqueTileId = [tileId, this.tileCounter, this.token].join('/'); this.tileCounter += 1; // Holds the <img> element created asynchronously. var div = goog.dom.createDom(goog.dom.TagName.DIV, {'id': uniqueTileId}); // Use the current time in seconds as the priority for the tile // loading queue. Smaller priorities move to the front of the queue, // which is what we want - the Maps API loads the tiles in a spiral // starting from the center, and we would like to preserve this order. // Requests for tiles that are no longer visible won't clog the queue: // if the map is moved around a lot, Maps API calls our releaseTile() // method, and the obsolete requests will be removed from the queue. var priority = new Date().getTime() / 1000; this.tilesLoading.push(uniqueTileId); ee.MapTileManager.getInstance().send( uniqueTileId, src, priority, goog.bind(this.handleImageCompleted_, this, div, uniqueTileId)); this.dispatchTileEvent_(); return div; } /** @return {number} The number of tiles successfully loaded. */ getLoadedTilesCount() { return this.tiles_.getCount(); } /** @return {number} The number of tiles currently loading. */ getLoadingTilesCount() { return this.tilesLoading.length; } /** * Implements releaseTile() for the google.maps.MapType * interface. * @param {Node} tileDiv The tile that has been released. */ releaseTile(tileDiv) { ee.MapTileManager.getInstance().abort(tileDiv.id); var tileImg = goog.dom.getFirstElementChild(tileDiv); this.tiles_.remove(tileImg); if (tileDiv.id !== '') { // Out-of-bounds tiles have no ID. this.tilesFailed.remove(tileDiv.id); if (this.profiler_) { this.profiler_.removeTile(tileDiv.id); } } } /** * Implements setOpacity() for the google.maps.MapType interface. * @param {number} opacity The opacity to set this layer to. */ setOpacity(opacity) { this.opacity_ = opacity; var iter = this.tiles_.__iterator__(); goog.iter.forEach(iter, function(tile) { goog.style.setOpacity(tile, opacity); }); } /** * Handle image 'load' and 'error' events. When the last one has * finished, dispatch an ee.AbstractOverlay.EventType.TILE_LOADED event. * Handle bookkeeping to keep the tilesLoading array accurate. * @param {Node} div Tile div to which images should be appended. * @param {string} tileId The id of the tile that was requested. * @param {!goog.events.Event} e Image loading event. * @param {?string} profileId If profiling, profile ID for the tile. * @private */ handleImageCompleted_(div, tileId, e, profileId) { if (e.type == goog.net.EventType.ERROR) { // Forward error events. goog.array.remove(this.tilesLoading, tileId); this.tilesFailed.add(tileId); this.dispatchEvent(e); } else { // Convert tile loading events to our own type. goog.array.remove(this.tilesLoading, tileId); var tile; if (e.target && (e.type == goog.events.EventType.LOAD)) { tile = /** @type {Node} */ (e.target); this.tiles_.add(tile); if (this.opacity_ != 1.0) { goog.style.setOpacity(/** @type {Element} */ (tile), this.opacity_); } div.appendChild(tile); } this.dispatchTileEvent_(); } if (this.profiler_ && profileId !== null) { this.profiler_.addTile(tileId, profileId); } } }; // Export getTile and removeTile so they are not eliminated by dead // code removal during compilation goog.exportProperty( ee.MapLayerOverlay.prototype, 'getTile', ee.MapLayerOverlay.prototype.getTile); goog.exportProperty( ee.MapLayerOverlay.prototype, 'setOpacity', ee.MapLayerOverlay.prototype.setOpacity); goog.exportProperty( ee.MapLayerOverlay.prototype, 'releaseTile', ee.MapLayerOverlay.prototype.releaseTile);
#!/usr/bin/env python import pytest """ Test 171. Excel Sheet Column Number """ @pytest.fixture(scope="session") def init_variables_171(): from src.leetcode_171_excel_sheet_column_number import Solution solution = Solution() def _init_variables_171(): return solution yield _init_variables_171 class TestClass171: def test_solution_0(self, init_variables_171): assert init_variables_171().titleToNumber("A") == 1 def test_solution_1(self, init_variables_171): assert init_variables_171().titleToNumber("AB") == 28 def test_solution_2(self, init_variables_171): assert init_variables_171().titleToNumber("ZY") == 701 def test_solution_3(self, init_variables_171): assert init_variables_171().titleToNumber("FXSHRXW") == 2147483647