repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
delph-in/pydelphin
delphin/itsdb.py
Table.from_file
def from_file(cls, path, fields=None, encoding='utf-8'): """ Instantiate a Table from a database file. This method instantiates a table attached to the file at *path*. The file will be opened and traversed to determine the number of records, but the contents will not be stored in memory unless they are modified. Args: path: the path to the table file fields: the Relation schema for the table (loaded from the relations file in the same directory if not given) encoding: the character encoding of the file at *path* """ path = _table_filename(path) # do early in case file not found if fields is None: fields = _get_relation_from_table_path(path) table = cls(fields) table.attach(path, encoding=encoding) return table
python
def from_file(cls, path, fields=None, encoding='utf-8'): """ Instantiate a Table from a database file. This method instantiates a table attached to the file at *path*. The file will be opened and traversed to determine the number of records, but the contents will not be stored in memory unless they are modified. Args: path: the path to the table file fields: the Relation schema for the table (loaded from the relations file in the same directory if not given) encoding: the character encoding of the file at *path* """ path = _table_filename(path) # do early in case file not found if fields is None: fields = _get_relation_from_table_path(path) table = cls(fields) table.attach(path, encoding=encoding) return table
Instantiate a Table from a database file. This method instantiates a table attached to the file at *path*. The file will be opened and traversed to determine the number of records, but the contents will not be stored in memory unless they are modified. Args: path: the path to the table file fields: the Relation schema for the table (loaded from the relations file in the same directory if not given) encoding: the character encoding of the file at *path*
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L659-L681
delph-in/pydelphin
delphin/itsdb.py
Table.write
def write(self, records=None, path=None, fields=None, append=False, gzip=None): """ Write the table to disk. The basic usage has no arguments and writes the table's data to the attached file. The parameters accommodate a variety of use cases, such as using *fields* to refresh a table to a new schema or *records* and *append* to incrementally build a table. Args: records: an iterable of :class:`Record` objects to write; if `None` the table's existing data is used path: the destination file path; if `None` use the path of the file attached to the table fields (:class:`Relation`): table schema to use for writing, otherwise use the current one append: if `True`, append rather than overwrite gzip: compress with gzip if non-empty Examples: >>> table.write() >>> table.write(results, path='new/path/result') """ if path is None: if not self.is_attached(): raise ItsdbError('no path given for detached table') else: path = self.path path = _normalize_table_path(path) dirpath, name = os.path.split(path) if fields is None: fields = self.fields if records is None: records = iter(self) _write_table( dirpath, name, records, fields, append=append, gzip=gzip, encoding=self.encoding) if self.is_attached() and path == _normalize_table_path(self.path): self.path = _table_filename(path) self._sync_with_file()
python
def write(self, records=None, path=None, fields=None, append=False, gzip=None): """ Write the table to disk. The basic usage has no arguments and writes the table's data to the attached file. The parameters accommodate a variety of use cases, such as using *fields* to refresh a table to a new schema or *records* and *append* to incrementally build a table. Args: records: an iterable of :class:`Record` objects to write; if `None` the table's existing data is used path: the destination file path; if `None` use the path of the file attached to the table fields (:class:`Relation`): table schema to use for writing, otherwise use the current one append: if `True`, append rather than overwrite gzip: compress with gzip if non-empty Examples: >>> table.write() >>> table.write(results, path='new/path/result') """ if path is None: if not self.is_attached(): raise ItsdbError('no path given for detached table') else: path = self.path path = _normalize_table_path(path) dirpath, name = os.path.split(path) if fields is None: fields = self.fields if records is None: records = iter(self) _write_table( dirpath, name, records, fields, append=append, gzip=gzip, encoding=self.encoding) if self.is_attached() and path == _normalize_table_path(self.path): self.path = _table_filename(path) self._sync_with_file()
Write the table to disk. The basic usage has no arguments and writes the table's data to the attached file. The parameters accommodate a variety of use cases, such as using *fields* to refresh a table to a new schema or *records* and *append* to incrementally build a table. Args: records: an iterable of :class:`Record` objects to write; if `None` the table's existing data is used path: the destination file path; if `None` use the path of the file attached to the table fields (:class:`Relation`): table schema to use for writing, otherwise use the current one append: if `True`, append rather than overwrite gzip: compress with gzip if non-empty Examples: >>> table.write() >>> table.write(results, path='new/path/result')
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L683-L729
delph-in/pydelphin
delphin/itsdb.py
Table.commit
def commit(self): """ Commit changes to disk if attached. This method helps normalize the interface for detached and attached tables and makes writing attached tables a bit more efficient. For detached tables nothing is done, as there is no notion of changes, but neither is an error raised (unlike with :meth:`write`). For attached tables, if all changes are new records, the changes are appended to the existing file, and otherwise the whole file is rewritten. """ if not self.is_attached(): return changes = self.list_changes() if changes: indices, records = zip(*changes) if min(indices) > self._last_synced_index: self.write(records, append=True) else: self.write(append=False)
python
def commit(self): """ Commit changes to disk if attached. This method helps normalize the interface for detached and attached tables and makes writing attached tables a bit more efficient. For detached tables nothing is done, as there is no notion of changes, but neither is an error raised (unlike with :meth:`write`). For attached tables, if all changes are new records, the changes are appended to the existing file, and otherwise the whole file is rewritten. """ if not self.is_attached(): return changes = self.list_changes() if changes: indices, records = zip(*changes) if min(indices) > self._last_synced_index: self.write(records, append=True) else: self.write(append=False)
Commit changes to disk if attached. This method helps normalize the interface for detached and attached tables and makes writing attached tables a bit more efficient. For detached tables nothing is done, as there is no notion of changes, but neither is an error raised (unlike with :meth:`write`). For attached tables, if all changes are new records, the changes are appended to the existing file, and otherwise the whole file is rewritten.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L731-L751
delph-in/pydelphin
delphin/itsdb.py
Table.attach
def attach(self, path, encoding='utf-8'): """ Attach the Table to the file at *path*. Attaching a table to a file means that only changed records are stored in memory, which greatly reduces the memory footprint of large profiles at some cost of performance. Tables created from :meth:`Table.from_file()` or from an attached :class:`TestSuite` are automatically attached. Attaching a file does not immediately flush the contents to disk; after attaching the table must be separately written to commit the in-memory data. A non-empty table will fail to attach to a non-empty file to avoid data loss when merging the contents. In this case, you may delete or clear the file, clear the table, or attach to another file. Args: path: the path to the table file encoding: the character encoding of the files in the testsuite """ if self.is_attached(): raise ItsdbError('already attached at {}'.format(self.path)) try: path = _table_filename(path) except ItsdbError: # neither path nor path.gz exist; create new empty file # (note: if the file were non-empty this would be destructive) path = _normalize_table_path(path) open(path, 'w').close() else: # path or path.gz exists; check if merging would be a problem if os.stat(path).st_size > 0 and len(self._records) > 0: raise ItsdbError( 'cannot attach non-empty table to non-empty file') self.path = path self.encoding = encoding # if _records is not empty then we're attaching to an empty file if len(self._records) == 0: self._sync_with_file()
python
def attach(self, path, encoding='utf-8'): """ Attach the Table to the file at *path*. Attaching a table to a file means that only changed records are stored in memory, which greatly reduces the memory footprint of large profiles at some cost of performance. Tables created from :meth:`Table.from_file()` or from an attached :class:`TestSuite` are automatically attached. Attaching a file does not immediately flush the contents to disk; after attaching the table must be separately written to commit the in-memory data. A non-empty table will fail to attach to a non-empty file to avoid data loss when merging the contents. In this case, you may delete or clear the file, clear the table, or attach to another file. Args: path: the path to the table file encoding: the character encoding of the files in the testsuite """ if self.is_attached(): raise ItsdbError('already attached at {}'.format(self.path)) try: path = _table_filename(path) except ItsdbError: # neither path nor path.gz exist; create new empty file # (note: if the file were non-empty this would be destructive) path = _normalize_table_path(path) open(path, 'w').close() else: # path or path.gz exists; check if merging would be a problem if os.stat(path).st_size > 0 and len(self._records) > 0: raise ItsdbError( 'cannot attach non-empty table to non-empty file') self.path = path self.encoding = encoding # if _records is not empty then we're attaching to an empty file if len(self._records) == 0: self._sync_with_file()
Attach the Table to the file at *path*. Attaching a table to a file means that only changed records are stored in memory, which greatly reduces the memory footprint of large profiles at some cost of performance. Tables created from :meth:`Table.from_file()` or from an attached :class:`TestSuite` are automatically attached. Attaching a file does not immediately flush the contents to disk; after attaching the table must be separately written to commit the in-memory data. A non-empty table will fail to attach to a non-empty file to avoid data loss when merging the contents. In this case, you may delete or clear the file, clear the table, or attach to another file. Args: path: the path to the table file encoding: the character encoding of the files in the testsuite
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L753-L796
delph-in/pydelphin
delphin/itsdb.py
Table.detach
def detach(self): """ Detach the table from a file. Detaching a table reads all data from the file and places it in memory. This is useful when constructing or significantly manipulating table data, or when more speed is needed. Tables created by the default constructor are detached. When detaching, only unmodified records are loaded from the file; any uncommited changes in the Table are left as-is. .. warning:: Very large tables may consume all available RAM when detached. Expect the in-memory table to take up about twice the space of an uncompressed table on disk, although this may vary by system. """ if not self.is_attached(): raise ItsdbError('already detached') records = self._records for i, line in self._enum_lines(): if records[i] is None: # check number of columns? records[i] = tuple(decode_row(line)) self.path = None self.encoding = None
python
def detach(self): """ Detach the table from a file. Detaching a table reads all data from the file and places it in memory. This is useful when constructing or significantly manipulating table data, or when more speed is needed. Tables created by the default constructor are detached. When detaching, only unmodified records are loaded from the file; any uncommited changes in the Table are left as-is. .. warning:: Very large tables may consume all available RAM when detached. Expect the in-memory table to take up about twice the space of an uncompressed table on disk, although this may vary by system. """ if not self.is_attached(): raise ItsdbError('already detached') records = self._records for i, line in self._enum_lines(): if records[i] is None: # check number of columns? records[i] = tuple(decode_row(line)) self.path = None self.encoding = None
Detach the table from a file. Detaching a table reads all data from the file and places it in memory. This is useful when constructing or significantly manipulating table data, or when more speed is needed. Tables created by the default constructor are detached. When detaching, only unmodified records are loaded from the file; any uncommited changes in the Table are left as-is. .. warning:: Very large tables may consume all available RAM when detached. Expect the in-memory table to take up about twice the space of an uncompressed table on disk, although this may vary by system.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L798-L825
delph-in/pydelphin
delphin/itsdb.py
Table.list_changes
def list_changes(self): """ Return a list of modified records. This is only applicable for attached tables. Returns: A list of `(row_index, record)` tuples of modified records Raises: :class:`delphin.exceptions.ItsdbError`: when called on a detached table """ if not self.is_attached(): raise ItsdbError('changes are not tracked for detached tables.') return [(i, self[i]) for i, row in enumerate(self._records) if row is not None]
python
def list_changes(self): """ Return a list of modified records. This is only applicable for attached tables. Returns: A list of `(row_index, record)` tuples of modified records Raises: :class:`delphin.exceptions.ItsdbError`: when called on a detached table """ if not self.is_attached(): raise ItsdbError('changes are not tracked for detached tables.') return [(i, self[i]) for i, row in enumerate(self._records) if row is not None]
Return a list of modified records. This is only applicable for attached tables. Returns: A list of `(row_index, record)` tuples of modified records Raises: :class:`delphin.exceptions.ItsdbError`: when called on a detached table
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L835-L850
delph-in/pydelphin
delphin/itsdb.py
Table._sync_with_file
def _sync_with_file(self): """Clear in-memory structures so table is synced with the file.""" self._records = [] i = -1 for i, line in self._enum_lines(): self._records.append(None) self._last_synced_index = i
python
def _sync_with_file(self): """Clear in-memory structures so table is synced with the file.""" self._records = [] i = -1 for i, line in self._enum_lines(): self._records.append(None) self._last_synced_index = i
Clear in-memory structures so table is synced with the file.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L852-L858
delph-in/pydelphin
delphin/itsdb.py
Table._enum_lines
def _enum_lines(self): """Enumerate lines from the attached file.""" with _open_table(self.path, self.encoding) as lines: for i, line in enumerate(lines): yield i, line
python
def _enum_lines(self): """Enumerate lines from the attached file.""" with _open_table(self.path, self.encoding) as lines: for i, line in enumerate(lines): yield i, line
Enumerate lines from the attached file.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L860-L864
delph-in/pydelphin
delphin/itsdb.py
Table._enum_attached_rows
def _enum_attached_rows(self, indices): """Enumerate on-disk and in-memory records.""" records = self._records i = 0 # first rows covered by the file for i, line in self._enum_lines(): if i in indices: row = records[i] if row is None: row = decode_row(line) yield (i, row) # then any uncommitted rows for j in range(i, len(records)): if j in indices: if records[j] is not None: yield (j, records[j])
python
def _enum_attached_rows(self, indices): """Enumerate on-disk and in-memory records.""" records = self._records i = 0 # first rows covered by the file for i, line in self._enum_lines(): if i in indices: row = records[i] if row is None: row = decode_row(line) yield (i, row) # then any uncommitted rows for j in range(i, len(records)): if j in indices: if records[j] is not None: yield (j, records[j])
Enumerate on-disk and in-memory records.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L866-L881
delph-in/pydelphin
delphin/itsdb.py
Table._iterslice
def _iterslice(self, slice): """Yield records from a slice index.""" indices = range(*slice.indices(len(self._records))) if self.is_attached(): rows = self._enum_attached_rows(indices) if slice.step is not None and slice.step < 0: rows = reversed(list(rows)) else: rows = zip(indices, self._records[slice]) fields = self.fields for i, row in rows: yield Record._make(fields, row, self, i)
python
def _iterslice(self, slice): """Yield records from a slice index.""" indices = range(*slice.indices(len(self._records))) if self.is_attached(): rows = self._enum_attached_rows(indices) if slice.step is not None and slice.step < 0: rows = reversed(list(rows)) else: rows = zip(indices, self._records[slice]) fields = self.fields for i, row in rows: yield Record._make(fields, row, self, i)
Yield records from a slice index.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L893-L905
delph-in/pydelphin
delphin/itsdb.py
Table._getitem
def _getitem(self, index): """Get a single non-slice index.""" row = self._records[index] if row is not None: pass elif self.is_attached(): # need to handle negative indices manually if index < 0: index = len(self._records) + index row = next((decode_row(line) for i, line in self._enum_lines() if i == index), None) if row is None: raise ItsdbError('could not retrieve row in attached table') else: raise ItsdbError('invalid row in detached table: {}'.format(index)) return Record._make(self.fields, row, self, index)
python
def _getitem(self, index): """Get a single non-slice index.""" row = self._records[index] if row is not None: pass elif self.is_attached(): # need to handle negative indices manually if index < 0: index = len(self._records) + index row = next((decode_row(line) for i, line in self._enum_lines() if i == index), None) if row is None: raise ItsdbError('could not retrieve row in attached table') else: raise ItsdbError('invalid row in detached table: {}'.format(index)) return Record._make(self.fields, row, self, index)
Get a single non-slice index.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L907-L925
delph-in/pydelphin
delphin/itsdb.py
Table.extend
def extend(self, records): """ Add each record in *records* to the end of the table. Args: record: an iterable of :class:`Record` or other iterables containing column values """ fields = self.fields for record in records: record = _cast_record_to_str_tuple(record, fields) self._records.append(record)
python
def extend(self, records): """ Add each record in *records* to the end of the table. Args: record: an iterable of :class:`Record` or other iterables containing column values """ fields = self.fields for record in records: record = _cast_record_to_str_tuple(record, fields) self._records.append(record)
Add each record in *records* to the end of the table. Args: record: an iterable of :class:`Record` or other iterables containing column values
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L954-L965
delph-in/pydelphin
delphin/itsdb.py
Table.select
def select(self, cols, mode='list'): """ Select columns from each row in the table. See :func:`select_rows` for a description of how to use the *mode* parameter. Args: cols: an iterable of Field (column) names mode: how to return the data """ if isinstance(cols, stringtypes): cols = _split_cols(cols) if not cols: cols = [f.name for f in self.fields] return select_rows(cols, self, mode=mode)
python
def select(self, cols, mode='list'): """ Select columns from each row in the table. See :func:`select_rows` for a description of how to use the *mode* parameter. Args: cols: an iterable of Field (column) names mode: how to return the data """ if isinstance(cols, stringtypes): cols = _split_cols(cols) if not cols: cols = [f.name for f in self.fields] return select_rows(cols, self, mode=mode)
Select columns from each row in the table. See :func:`select_rows` for a description of how to use the *mode* parameter. Args: cols: an iterable of Field (column) names mode: how to return the data
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L967-L982
delph-in/pydelphin
delphin/itsdb.py
ItsdbProfile.add_filter
def add_filter(self, table, cols, condition): """ Add a filter. When reading *table*, rows in *table* will be filtered by filter_rows(). Args: table: The table the filter applies to. cols: The columns in *table* to filter on. condition: The filter function. """ if table is not None and table not in self.relations: raise ItsdbError('Cannot add filter; table "{}" is not defined ' 'by the relations file.' .format(table)) # this is a hack, though perhaps well-motivated if cols is None: cols = [None] self.filters[table].append((cols, condition))
python
def add_filter(self, table, cols, condition): """ Add a filter. When reading *table*, rows in *table* will be filtered by filter_rows(). Args: table: The table the filter applies to. cols: The columns in *table* to filter on. condition: The filter function. """ if table is not None and table not in self.relations: raise ItsdbError('Cannot add filter; table "{}" is not defined ' 'by the relations file.' .format(table)) # this is a hack, though perhaps well-motivated if cols is None: cols = [None] self.filters[table].append((cols, condition))
Add a filter. When reading *table*, rows in *table* will be filtered by filter_rows(). Args: table: The table the filter applies to. cols: The columns in *table* to filter on. condition: The filter function.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1951-L1968
delph-in/pydelphin
delphin/itsdb.py
ItsdbProfile.add_applicator
def add_applicator(self, table, cols, function): """ Add an applicator. When reading *table*, rows in *table* will be modified by apply_rows(). Args: table: The table to apply the function to. cols: The columns in *table* to apply the function on. function: The applicator function. """ if table not in self.relations: raise ItsdbError('Cannot add applicator; table "{}" is not ' 'defined by the relations file.' .format(table)) if cols is None: raise ItsdbError('Cannot add applicator; columns not specified.') fields = set(f.name for f in self.relations[table]) for col in cols: if col not in fields: raise ItsdbError('Cannot add applicator; column "{}" not ' 'defined by the relations file.' .format(col)) self.applicators[table].append((cols, function))
python
def add_applicator(self, table, cols, function): """ Add an applicator. When reading *table*, rows in *table* will be modified by apply_rows(). Args: table: The table to apply the function to. cols: The columns in *table* to apply the function on. function: The applicator function. """ if table not in self.relations: raise ItsdbError('Cannot add applicator; table "{}" is not ' 'defined by the relations file.' .format(table)) if cols is None: raise ItsdbError('Cannot add applicator; columns not specified.') fields = set(f.name for f in self.relations[table]) for col in cols: if col not in fields: raise ItsdbError('Cannot add applicator; column "{}" not ' 'defined by the relations file.' .format(col)) self.applicators[table].append((cols, function))
Add an applicator. When reading *table*, rows in *table* will be modified by apply_rows(). Args: table: The table to apply the function to. cols: The columns in *table* to apply the function on. function: The applicator function.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1970-L1993
delph-in/pydelphin
delphin/itsdb.py
ItsdbProfile.read_raw_table
def read_raw_table(self, table): """ Yield rows in the [incr tsdb()] *table*. A row is a dictionary mapping column names to values. Data from a profile is decoded by decode_row(). No filters or applicators are used. """ fields = self.table_relations(table) if self.cast else None field_names = [f.name for f in self.table_relations(table)] field_len = len(field_names) table_path = os.path.join(self.root, table) with _open_table(table_path, self.encoding) as tbl: for line in tbl: cols = decode_row(line, fields=fields) if len(cols) != field_len: # should this throw an exception instead? logging.error('Number of stored fields ({}) ' 'differ from the expected number({}); ' 'fields may be misaligned!' .format(len(cols), field_len)) row = OrderedDict(zip(field_names, cols)) yield row
python
def read_raw_table(self, table): """ Yield rows in the [incr tsdb()] *table*. A row is a dictionary mapping column names to values. Data from a profile is decoded by decode_row(). No filters or applicators are used. """ fields = self.table_relations(table) if self.cast else None field_names = [f.name for f in self.table_relations(table)] field_len = len(field_names) table_path = os.path.join(self.root, table) with _open_table(table_path, self.encoding) as tbl: for line in tbl: cols = decode_row(line, fields=fields) if len(cols) != field_len: # should this throw an exception instead? logging.error('Number of stored fields ({}) ' 'differ from the expected number({}); ' 'fields may be misaligned!' .format(len(cols), field_len)) row = OrderedDict(zip(field_names, cols)) yield row
Yield rows in the [incr tsdb()] *table*. A row is a dictionary mapping column names to values. Data from a profile is decoded by decode_row(). No filters or applicators are used.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L2019-L2039
delph-in/pydelphin
delphin/itsdb.py
ItsdbProfile.read_table
def read_table(self, table, key_filter=True): """ Yield rows in the [incr tsdb()] *table* that pass any defined filters, and with values changed by any applicators. If no filters or applicators are defined, the result is the same as from ItsdbProfile.read_raw_table(). """ filters = self.filters[None] + self.filters[table] if key_filter: for f in self.relations[table]: key = f.name if f.key and (self._index.get(key) is not None): ids = self._index[key] # Can't keep local variables (like ids) in the scope of # the lambda expression, so make it a default argument. # Source: http://stackoverflow.com/a/938493/1441112 function = lambda r, x, ids=ids: x in ids filters.append(([key], function)) applicators = self.applicators[table] rows = self.read_raw_table(table) return filter_rows(filters, apply_rows(applicators, rows))
python
def read_table(self, table, key_filter=True): """ Yield rows in the [incr tsdb()] *table* that pass any defined filters, and with values changed by any applicators. If no filters or applicators are defined, the result is the same as from ItsdbProfile.read_raw_table(). """ filters = self.filters[None] + self.filters[table] if key_filter: for f in self.relations[table]: key = f.name if f.key and (self._index.get(key) is not None): ids = self._index[key] # Can't keep local variables (like ids) in the scope of # the lambda expression, so make it a default argument. # Source: http://stackoverflow.com/a/938493/1441112 function = lambda r, x, ids=ids: x in ids filters.append(([key], function)) applicators = self.applicators[table] rows = self.read_raw_table(table) return filter_rows(filters, apply_rows(applicators, rows))
Yield rows in the [incr tsdb()] *table* that pass any defined filters, and with values changed by any applicators. If no filters or applicators are defined, the result is the same as from ItsdbProfile.read_raw_table().
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L2041-L2061
delph-in/pydelphin
delphin/itsdb.py
ItsdbProfile.select
def select(self, table, cols, mode='list', key_filter=True): """ Yield selected rows from *table*. This method just calls select_rows() on the rows read from *table*. """ if cols is None: cols = [c.name for c in self.relations[table]] rows = self.read_table(table, key_filter=key_filter) for row in select_rows(cols, rows, mode=mode): yield row
python
def select(self, table, cols, mode='list', key_filter=True): """ Yield selected rows from *table*. This method just calls select_rows() on the rows read from *table*. """ if cols is None: cols = [c.name for c in self.relations[table]] rows = self.read_table(table, key_filter=key_filter) for row in select_rows(cols, rows, mode=mode): yield row
Yield selected rows from *table*. This method just calls select_rows() on the rows read from *table*.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L2063-L2072
delph-in/pydelphin
delphin/itsdb.py
ItsdbProfile.join
def join(self, table1, table2, key_filter=True): """ Yield rows from a table built by joining *table1* and *table2*. The column names in the rows have the original table name prepended and separated by a colon. For example, joining tables 'item' and 'parse' will result in column names like 'item:i-input' and 'parse:parse-id'. """ get_keys = lambda t: (f.name for f in self.relations[t] if f.key) keys = set(get_keys(table1)).intersection(get_keys(table2)) if not keys: raise ItsdbError( 'Cannot join tables "{}" and "{}"; no shared key exists.' .format(table1, table2) ) key = keys.pop() # this join method stores the whole of table2 in memory, but it is # MUCH faster than a nested loop method. Most profiles will fit in # memory anyway, so it's a decent tradeoff table2_data = defaultdict(list) for row in self.read_table(table2, key_filter=key_filter): table2_data[row[key]].append(row) for row1 in self.read_table(table1, key_filter=key_filter): for row2 in table2_data.get(row1[key], []): joinedrow = OrderedDict( [('{}:{}'.format(table1, k), v) for k, v in row1.items()] + [('{}:{}'.format(table2, k), v) for k, v in row2.items()] ) yield joinedrow
python
def join(self, table1, table2, key_filter=True): """ Yield rows from a table built by joining *table1* and *table2*. The column names in the rows have the original table name prepended and separated by a colon. For example, joining tables 'item' and 'parse' will result in column names like 'item:i-input' and 'parse:parse-id'. """ get_keys = lambda t: (f.name for f in self.relations[t] if f.key) keys = set(get_keys(table1)).intersection(get_keys(table2)) if not keys: raise ItsdbError( 'Cannot join tables "{}" and "{}"; no shared key exists.' .format(table1, table2) ) key = keys.pop() # this join method stores the whole of table2 in memory, but it is # MUCH faster than a nested loop method. Most profiles will fit in # memory anyway, so it's a decent tradeoff table2_data = defaultdict(list) for row in self.read_table(table2, key_filter=key_filter): table2_data[row[key]].append(row) for row1 in self.read_table(table1, key_filter=key_filter): for row2 in table2_data.get(row1[key], []): joinedrow = OrderedDict( [('{}:{}'.format(table1, k), v) for k, v in row1.items()] + [('{}:{}'.format(table2, k), v) for k, v in row2.items()] ) yield joinedrow
Yield rows from a table built by joining *table1* and *table2*. The column names in the rows have the original table name prepended and separated by a colon. For example, joining tables 'item' and 'parse' will result in column names like 'item:i-input' and 'parse:parse-id'.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L2074-L2104
delph-in/pydelphin
delphin/itsdb.py
ItsdbProfile.write_table
def write_table(self, table, rows, append=False, gzip=False): """ Encode and write out *table* to the profile directory. Args: table: The name of the table to write rows: The rows to write to the table append: If `True`, append the encoded rows to any existing data. gzip: If `True`, compress the resulting table with `gzip`. The table's filename will have `.gz` appended. """ _write_table(self.root, table, rows, self.table_relations(table), append=append, gzip=gzip, encoding=self.encoding)
python
def write_table(self, table, rows, append=False, gzip=False): """ Encode and write out *table* to the profile directory. Args: table: The name of the table to write rows: The rows to write to the table append: If `True`, append the encoded rows to any existing data. gzip: If `True`, compress the resulting table with `gzip`. The table's filename will have `.gz` appended. """ _write_table(self.root, table, rows, self.table_relations(table), append=append, gzip=gzip, encoding=self.encoding)
Encode and write out *table* to the profile directory. Args: table: The name of the table to write rows: The rows to write to the table append: If `True`, append the encoded rows to any existing data. gzip: If `True`, compress the resulting table with `gzip`. The table's filename will have `.gz` appended.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L2106-L2124
delph-in/pydelphin
delphin/itsdb.py
ItsdbProfile.write_profile
def write_profile(self, profile_directory, relations_filename=None, key_filter=True, append=False, gzip=None): """ Write all tables (as specified by the relations) to a profile. Args: profile_directory: The directory of the output profile relations_filename: If given, read and use the relations at this path instead of the current profile's relations key_filter: If True, filter the rows by keys in the index append: If `True`, append profile data to existing tables in the output profile directory gzip: If `True`, compress tables using `gzip`. Table filenames will have `.gz` appended. If `False`, only write out text files. If `None`, use whatever the original file was. """ if relations_filename: src_rels = os.path.abspath(relations_filename) relations = get_relations(relations_filename) else: src_rels = os.path.abspath(os.path.join(self.root, _relations_filename)) relations = self.relations tgt_rels = os.path.abspath(os.path.join(profile_directory, _relations_filename)) if not (os.path.isfile(tgt_rels) and src_rels == tgt_rels): with open(tgt_rels, 'w') as rel_fh: print(open(src_rels).read(), file=rel_fh) tables = self._tables if tables is not None: tables = set(tables) for table, fields in relations.items(): if tables is not None and table not in tables: continue try: fn = _table_filename(os.path.join(self.root, table)) _gzip = gzip if gzip is not None else fn.endswith('.gz') rows = list(self.read_table(table, key_filter=key_filter)) _write_table( profile_directory, table, rows, fields, append=append, gzip=_gzip, encoding=self.encoding ) except ItsdbError: logging.warning( 'Could not write "{}"; table doesn\'t exist.'.format(table) ) continue self._cleanup(gzip=gzip)
python
def write_profile(self, profile_directory, relations_filename=None, key_filter=True, append=False, gzip=None): """ Write all tables (as specified by the relations) to a profile. Args: profile_directory: The directory of the output profile relations_filename: If given, read and use the relations at this path instead of the current profile's relations key_filter: If True, filter the rows by keys in the index append: If `True`, append profile data to existing tables in the output profile directory gzip: If `True`, compress tables using `gzip`. Table filenames will have `.gz` appended. If `False`, only write out text files. If `None`, use whatever the original file was. """ if relations_filename: src_rels = os.path.abspath(relations_filename) relations = get_relations(relations_filename) else: src_rels = os.path.abspath(os.path.join(self.root, _relations_filename)) relations = self.relations tgt_rels = os.path.abspath(os.path.join(profile_directory, _relations_filename)) if not (os.path.isfile(tgt_rels) and src_rels == tgt_rels): with open(tgt_rels, 'w') as rel_fh: print(open(src_rels).read(), file=rel_fh) tables = self._tables if tables is not None: tables = set(tables) for table, fields in relations.items(): if tables is not None and table not in tables: continue try: fn = _table_filename(os.path.join(self.root, table)) _gzip = gzip if gzip is not None else fn.endswith('.gz') rows = list(self.read_table(table, key_filter=key_filter)) _write_table( profile_directory, table, rows, fields, append=append, gzip=_gzip, encoding=self.encoding ) except ItsdbError: logging.warning( 'Could not write "{}"; table doesn\'t exist.'.format(table) ) continue self._cleanup(gzip=gzip)
Write all tables (as specified by the relations) to a profile. Args: profile_directory: The directory of the output profile relations_filename: If given, read and use the relations at this path instead of the current profile's relations key_filter: If True, filter the rows by keys in the index append: If `True`, append profile data to existing tables in the output profile directory gzip: If `True`, compress tables using `gzip`. Table filenames will have `.gz` appended. If `False`, only write out text files. If `None`, use whatever the original file was.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L2126-L2179
delph-in/pydelphin
delphin/itsdb.py
ItsdbProfile.exists
def exists(self, table=None): """ Return True if the profile or a table exist. If *table* is `None`, this function returns True if the root directory exists and contains a valid relations file. If *table* is given, the function returns True if the table exists as a file (even if empty). Otherwise it returns False. """ if not os.path.isdir(self.root): return False if not os.path.isfile(os.path.join(self.root, _relations_filename)): return False if table is not None: try: _table_filename(os.path.join(self.root, table)) except ItsdbError: return False return True
python
def exists(self, table=None): """ Return True if the profile or a table exist. If *table* is `None`, this function returns True if the root directory exists and contains a valid relations file. If *table* is given, the function returns True if the table exists as a file (even if empty). Otherwise it returns False. """ if not os.path.isdir(self.root): return False if not os.path.isfile(os.path.join(self.root, _relations_filename)): return False if table is not None: try: _table_filename(os.path.join(self.root, table)) except ItsdbError: return False return True
Return True if the profile or a table exist. If *table* is `None`, this function returns True if the root directory exists and contains a valid relations file. If *table* is given, the function returns True if the table exists as a file (even if empty). Otherwise it returns False.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L2181-L2199
delph-in/pydelphin
delphin/itsdb.py
ItsdbProfile.size
def size(self, table=None): """ Return the size, in bytes, of the profile or *table*. If *table* is `None`, this function returns the size of the whole profile (i.e. the sum of the table sizes). Otherwise, it returns the size of *table*. Note: if the file is gzipped, it returns the compressed size. """ size = 0 if table is None: for table in self.relations: size += self.size(table) else: try: fn = _table_filename(os.path.join(self.root, table)) size += os.stat(fn).st_size except ItsdbError: pass return size
python
def size(self, table=None): """ Return the size, in bytes, of the profile or *table*. If *table* is `None`, this function returns the size of the whole profile (i.e. the sum of the table sizes). Otherwise, it returns the size of *table*. Note: if the file is gzipped, it returns the compressed size. """ size = 0 if table is None: for table in self.relations: size += self.size(table) else: try: fn = _table_filename(os.path.join(self.root, table)) size += os.stat(fn).st_size except ItsdbError: pass return size
Return the size, in bytes, of the profile or *table*. If *table* is `None`, this function returns the size of the whole profile (i.e. the sum of the table sizes). Otherwise, it returns the size of *table*. Note: if the file is gzipped, it returns the compressed size.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L2201-L2221
delph-in/pydelphin
delphin/interfaces/rest.py
parse
def parse(input, server=default_erg_server, params=None, headers=None): """ Request a parse of *input* on *server* and return the response. Args: input (str): sentence to be parsed server (str): the url for the server (the default LOGON server is used by default) params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers Returns: A ParseResponse containing the results, if the request was successful. Raises: requests.HTTPError: if the status code was not 200 """ return next(parse_from_iterable([input], server, params, headers), None)
python
def parse(input, server=default_erg_server, params=None, headers=None): """ Request a parse of *input* on *server* and return the response. Args: input (str): sentence to be parsed server (str): the url for the server (the default LOGON server is used by default) params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers Returns: A ParseResponse containing the results, if the request was successful. Raises: requests.HTTPError: if the status code was not 200 """ return next(parse_from_iterable([input], server, params, headers), None)
Request a parse of *input* on *server* and return the response. Args: input (str): sentence to be parsed server (str): the url for the server (the default LOGON server is used by default) params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers Returns: A ParseResponse containing the results, if the request was successful. Raises: requests.HTTPError: if the status code was not 200
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/rest.py#L151-L167
delph-in/pydelphin
delphin/interfaces/rest.py
parse_from_iterable
def parse_from_iterable( inputs, server=default_erg_server, params=None, headers=None): """ Request parses for all *inputs*. Args: inputs (iterable): sentences to parse server (str): the url for the server (the default LOGON server is used by default) params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers Yields: ParseResponse objects for each successful response. Raises: requests.HTTPError: for the first response with a status code that is not 200 """ client = DelphinRestClient(server) for input in inputs: yield client.parse(input, params=params, headers=headers)
python
def parse_from_iterable( inputs, server=default_erg_server, params=None, headers=None): """ Request parses for all *inputs*. Args: inputs (iterable): sentences to parse server (str): the url for the server (the default LOGON server is used by default) params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers Yields: ParseResponse objects for each successful response. Raises: requests.HTTPError: for the first response with a status code that is not 200 """ client = DelphinRestClient(server) for input in inputs: yield client.parse(input, params=params, headers=headers)
Request parses for all *inputs*. Args: inputs (iterable): sentences to parse server (str): the url for the server (the default LOGON server is used by default) params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers Yields: ParseResponse objects for each successful response. Raises: requests.HTTPError: for the first response with a status code that is not 200
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/rest.py#L169-L191
delph-in/pydelphin
delphin/interfaces/rest.py
DelphinRestClient.parse
def parse(self, sentence, params=None, headers=None): """ Request a parse of *sentence* and return the response. Args: sentence (str): sentence to be parsed params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers Returns: A ParseResponse containing the results, if the request was successful. Raises: requests.HTTPError: if the status code was not 200 """ if params is None: params = {} params['input'] = sentence hdrs = {'Accept': 'application/json'} if headers is not None: hdrs.update(headers) url = urljoin(self.server, 'parse') r = requests.get(url, params=params, headers=hdrs) if r.status_code == 200: return _RestResponse(r.json()) else: r.raise_for_status()
python
def parse(self, sentence, params=None, headers=None): """ Request a parse of *sentence* and return the response. Args: sentence (str): sentence to be parsed params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers Returns: A ParseResponse containing the results, if the request was successful. Raises: requests.HTTPError: if the status code was not 200 """ if params is None: params = {} params['input'] = sentence hdrs = {'Accept': 'application/json'} if headers is not None: hdrs.update(headers) url = urljoin(self.server, 'parse') r = requests.get(url, params=params, headers=hdrs) if r.status_code == 200: return _RestResponse(r.json()) else: r.raise_for_status()
Request a parse of *sentence* and return the response. Args: sentence (str): sentence to be parsed params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers Returns: A ParseResponse containing the results, if the request was successful. Raises: requests.HTTPError: if the status code was not 200
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/rest.py#L113-L140
kylemacfarlane/zplgrf
src/zplgrf/__init__.py
_calculate_crc_ccitt
def _calculate_crc_ccitt(data): """ All CRC stuff ripped from PyCRC, GPLv3 licensed """ global CRC_CCITT_TABLE if not CRC_CCITT_TABLE: crc_ccitt_table = [] for i in range(0, 256): crc = 0 c = i << 8 for j in range(0, 8): if (crc ^ c) & 0x8000: crc = c_ushort(crc << 1).value ^ 0x1021 else: crc = c_ushort(crc << 1).value c = c_ushort(c << 1).value crc_ccitt_table.append(crc) CRC_CCITT_TABLE = crc_ccitt_table is_string = _is_string(data) crc_value = 0x0000 # XModem version for c in data: d = ord(c) if is_string else c tmp = ((crc_value >> 8) & 0xff) ^ d crc_value = ((crc_value << 8) & 0xff00) ^ CRC_CCITT_TABLE[tmp] return crc_value
python
def _calculate_crc_ccitt(data): """ All CRC stuff ripped from PyCRC, GPLv3 licensed """ global CRC_CCITT_TABLE if not CRC_CCITT_TABLE: crc_ccitt_table = [] for i in range(0, 256): crc = 0 c = i << 8 for j in range(0, 8): if (crc ^ c) & 0x8000: crc = c_ushort(crc << 1).value ^ 0x1021 else: crc = c_ushort(crc << 1).value c = c_ushort(c << 1).value crc_ccitt_table.append(crc) CRC_CCITT_TABLE = crc_ccitt_table is_string = _is_string(data) crc_value = 0x0000 # XModem version for c in data: d = ord(c) if is_string else c tmp = ((crc_value >> 8) & 0xff) ^ d crc_value = ((crc_value << 8) & 0xff00) ^ CRC_CCITT_TABLE[tmp] return crc_value
All CRC stuff ripped from PyCRC, GPLv3 licensed
https://github.com/kylemacfarlane/zplgrf/blob/aacad3e69c7abe04dbfe9ce3c5cf6ac2a1ab67b3/src/zplgrf/__init__.py#L31-L61
kylemacfarlane/zplgrf
src/zplgrf/__init__.py
GRF.to_zpl_line
def to_zpl_line(self, compression=3, **kwargs): """ Compression: 3 = ZB64/Z64, base64 encoded DEFLATE compressed - best compression 2 = ASCII hex encoded run length compressed - most compatible 1 = B64, base64 encoded - pointless? """ if compression == 3: data = base64.b64encode(zlib.compress(self.data.bytes)) data = ':Z64:%s:%s' % (data.decode('ascii'), self._calc_crc(data)) elif compression == 1: data = base64.b64encode(self.data.bytes) data = ':B64:%s:%s' % (data.decode('ascii'), self._calc_crc(data)) else: lines = [] last_unique_line = None for line in self.data.hex_rows: if line.endswith('00'): line = line.rstrip('0') if len(line) % 2: line += '0' line += ',' if line == last_unique_line: line = ':' else: last_unique_line = line lines.append(line) data = '\n'.join(lines) to_compress = set(RE_UNCOMPRESSED.findall(data)) to_compress = sorted(to_compress, reverse=True) for uncompressed in to_compress: uncompressed = uncompressed[0] repeat = len(uncompressed) compressed = '' while repeat >= 400: compressed += 'z' repeat -= 400 if repeat >= 20: value = repeat // 20 repeat -= value * 20 compressed += chr(value + 70).lower() if repeat > 0: compressed += chr(repeat + 70) data = data.replace(uncompressed, compressed + uncompressed[0]) data = data.replace('\n', '') zpl = '~DGR:%s.GRF,%s,%s,%s' % ( self.filename, self.data.filesize, self.data.width // 8, data ) return zpl
python
def to_zpl_line(self, compression=3, **kwargs): """ Compression: 3 = ZB64/Z64, base64 encoded DEFLATE compressed - best compression 2 = ASCII hex encoded run length compressed - most compatible 1 = B64, base64 encoded - pointless? """ if compression == 3: data = base64.b64encode(zlib.compress(self.data.bytes)) data = ':Z64:%s:%s' % (data.decode('ascii'), self._calc_crc(data)) elif compression == 1: data = base64.b64encode(self.data.bytes) data = ':B64:%s:%s' % (data.decode('ascii'), self._calc_crc(data)) else: lines = [] last_unique_line = None for line in self.data.hex_rows: if line.endswith('00'): line = line.rstrip('0') if len(line) % 2: line += '0' line += ',' if line == last_unique_line: line = ':' else: last_unique_line = line lines.append(line) data = '\n'.join(lines) to_compress = set(RE_UNCOMPRESSED.findall(data)) to_compress = sorted(to_compress, reverse=True) for uncompressed in to_compress: uncompressed = uncompressed[0] repeat = len(uncompressed) compressed = '' while repeat >= 400: compressed += 'z' repeat -= 400 if repeat >= 20: value = repeat // 20 repeat -= value * 20 compressed += chr(value + 70).lower() if repeat > 0: compressed += chr(repeat + 70) data = data.replace(uncompressed, compressed + uncompressed[0]) data = data.replace('\n', '') zpl = '~DGR:%s.GRF,%s,%s,%s' % ( self.filename, self.data.filesize, self.data.width // 8, data ) return zpl
Compression: 3 = ZB64/Z64, base64 encoded DEFLATE compressed - best compression 2 = ASCII hex encoded run length compressed - most compatible 1 = B64, base64 encoded - pointless?
https://github.com/kylemacfarlane/zplgrf/blob/aacad3e69c7abe04dbfe9ce3c5cf6ac2a1ab67b3/src/zplgrf/__init__.py#L265-L321
kylemacfarlane/zplgrf
src/zplgrf/__init__.py
GRF.to_zpl
def to_zpl( self, quantity=1, pause_and_cut=0, override_pause=False, print_mode='C', print_orientation='N', media_tracking='Y', **kwargs ): """ The most basic ZPL to print the GRF. Since ZPL printers are stateful this may not work and you may need to build your own. """ zpl = [ self.to_zpl_line(**kwargs), # Download image to printer '^XA', # Start Label Format '^MM%s,Y' % print_mode, '^PO%s' % print_orientation, '^MN%s' % media_tracking, '^FO0,0', # Field Origin to 0,0 '^XGR:%s.GRF,1,1' % self.filename, # Draw image '^FS', # Field Separator '^PQ%s,%s,0,%s' % ( int(quantity), # Print Quantity int(pause_and_cut), # Pause and cut every N labels 'Y' if override_pause else 'N' # Don't pause between cuts ), '^XZ', # End Label Format '^IDR:%s.GRF' % self.filename # Delete image from printer ] return ''.join(zpl)
python
def to_zpl( self, quantity=1, pause_and_cut=0, override_pause=False, print_mode='C', print_orientation='N', media_tracking='Y', **kwargs ): """ The most basic ZPL to print the GRF. Since ZPL printers are stateful this may not work and you may need to build your own. """ zpl = [ self.to_zpl_line(**kwargs), # Download image to printer '^XA', # Start Label Format '^MM%s,Y' % print_mode, '^PO%s' % print_orientation, '^MN%s' % media_tracking, '^FO0,0', # Field Origin to 0,0 '^XGR:%s.GRF,1,1' % self.filename, # Draw image '^FS', # Field Separator '^PQ%s,%s,0,%s' % ( int(quantity), # Print Quantity int(pause_and_cut), # Pause and cut every N labels 'Y' if override_pause else 'N' # Don't pause between cuts ), '^XZ', # End Label Format '^IDR:%s.GRF' % self.filename # Delete image from printer ] return ''.join(zpl)
The most basic ZPL to print the GRF. Since ZPL printers are stateful this may not work and you may need to build your own.
https://github.com/kylemacfarlane/zplgrf/blob/aacad3e69c7abe04dbfe9ce3c5cf6ac2a1ab67b3/src/zplgrf/__init__.py#L323-L348
kylemacfarlane/zplgrf
src/zplgrf/__init__.py
GRF.from_image
def from_image(cls, image, filename): """ Filename is 1-8 alphanumeric characters to identify the GRF in ZPL. """ source = Image.open(BytesIO(image)) source = source.convert('1') width = int(math.ceil(source.size[0] / 8.0)) data = [] for line in _chunked(list(source.getdata()), source.size[0]): row = ''.join(['0' if p else '1' for p in line]) row = row.ljust(width * 8, '0') data.append(row) data = GRFData(width, bin=''.join(data)) return cls(filename, data)
python
def from_image(cls, image, filename): """ Filename is 1-8 alphanumeric characters to identify the GRF in ZPL. """ source = Image.open(BytesIO(image)) source = source.convert('1') width = int(math.ceil(source.size[0] / 8.0)) data = [] for line in _chunked(list(source.getdata()), source.size[0]): row = ''.join(['0' if p else '1' for p in line]) row = row.ljust(width * 8, '0') data.append(row) data = GRFData(width, bin=''.join(data)) return cls(filename, data)
Filename is 1-8 alphanumeric characters to identify the GRF in ZPL.
https://github.com/kylemacfarlane/zplgrf/blob/aacad3e69c7abe04dbfe9ce3c5cf6ac2a1ab67b3/src/zplgrf/__init__.py#L351-L367
kylemacfarlane/zplgrf
src/zplgrf/__init__.py
GRF.from_pdf
def from_pdf( cls, pdf, filename, width=288, height=432, dpi=203, font_path=None, center_of_pixel=False, use_bindings=False ): """ Filename is 1-8 alphanumeric characters to identify the GRF in ZPL. Dimensions and DPI are for a typical 4"x6" shipping label. E.g. 432 points / 72 points in an inch / 203 dpi = 6 inches Using center of pixel will improve barcode quality but may decrease the quality of some text. use_bindings=False: - Uses subprocess.Popen - Forks so there is a memory spike - Easier to setup - only needs the gs binary use_bindings=True: - Uses python-ghostscript - Doesn't fork so should use less memory - python-ghostscript is a bit buggy - May be harder to setup - even if you have updated the gs binary there may stil be old libgs* files on your system """ # Most arguments below are based on what CUPS uses setpagedevice = [ '/.HWMargins[0.000000 0.000000 0.000000 0.000000]', '/Margins[0 0]' ] cmd = [ 'gs', '-dQUIET', '-dPARANOIDSAFER', '-dNOPAUSE', '-dBATCH', '-dNOINTERPOLATE', '-sDEVICE=pngmono', '-dAdvanceDistance=1000', '-r%s' % int(dpi), '-dDEVICEWIDTHPOINTS=%s' % int(width), '-dDEVICEHEIGHTPOINTS=%s' % int(height), '-dFIXEDMEDIA', '-dPDFFitPage', '-c', '<<%s>>setpagedevice' % ' '.join(setpagedevice) ] if center_of_pixel: cmd += ['0 .setfilladjust'] if font_path and os.path.exists(font_path): cmd += ['-I' + font_path] if use_bindings: import ghostscript # python-ghostscript doesn't like reading/writing from # stdin/stdout so we need to use temp files with tempfile.NamedTemporaryFile() as in_file, \ tempfile.NamedTemporaryFile() as out_file: in_file.write(pdf) in_file.flush() # Ghostscript seems to be sensitive to argument order cmd[13:13] += [ '-sOutputFile=%s' % out_file.name ] cmd += [ '-f', in_file.name ] try: ghostscript.Ghostscript(*[c.encode('ascii') for c in cmd]) except Exception as e: raise GRFException(e) pngs = out_file.read() else: from subprocess import PIPE, Popen # Ghostscript seems to be sensitive to argument order cmd[13:13] += [ '-sstdout=%stderr', '-sOutputFile=%stdout', ] cmd += [ '-f', '-' ] p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) pngs, stderr = p.communicate(pdf) if stderr: raise GRFException(stderr) # This is what PIL uses to identify PNGs png_start = b'\211PNG\r\n\032\n' grfs = [] for png in pngs.split(png_start)[1:]: grfs.append(cls.from_image(png_start + png, filename)) return grfs
python
def from_pdf( cls, pdf, filename, width=288, height=432, dpi=203, font_path=None, center_of_pixel=False, use_bindings=False ): """ Filename is 1-8 alphanumeric characters to identify the GRF in ZPL. Dimensions and DPI are for a typical 4"x6" shipping label. E.g. 432 points / 72 points in an inch / 203 dpi = 6 inches Using center of pixel will improve barcode quality but may decrease the quality of some text. use_bindings=False: - Uses subprocess.Popen - Forks so there is a memory spike - Easier to setup - only needs the gs binary use_bindings=True: - Uses python-ghostscript - Doesn't fork so should use less memory - python-ghostscript is a bit buggy - May be harder to setup - even if you have updated the gs binary there may stil be old libgs* files on your system """ # Most arguments below are based on what CUPS uses setpagedevice = [ '/.HWMargins[0.000000 0.000000 0.000000 0.000000]', '/Margins[0 0]' ] cmd = [ 'gs', '-dQUIET', '-dPARANOIDSAFER', '-dNOPAUSE', '-dBATCH', '-dNOINTERPOLATE', '-sDEVICE=pngmono', '-dAdvanceDistance=1000', '-r%s' % int(dpi), '-dDEVICEWIDTHPOINTS=%s' % int(width), '-dDEVICEHEIGHTPOINTS=%s' % int(height), '-dFIXEDMEDIA', '-dPDFFitPage', '-c', '<<%s>>setpagedevice' % ' '.join(setpagedevice) ] if center_of_pixel: cmd += ['0 .setfilladjust'] if font_path and os.path.exists(font_path): cmd += ['-I' + font_path] if use_bindings: import ghostscript # python-ghostscript doesn't like reading/writing from # stdin/stdout so we need to use temp files with tempfile.NamedTemporaryFile() as in_file, \ tempfile.NamedTemporaryFile() as out_file: in_file.write(pdf) in_file.flush() # Ghostscript seems to be sensitive to argument order cmd[13:13] += [ '-sOutputFile=%s' % out_file.name ] cmd += [ '-f', in_file.name ] try: ghostscript.Ghostscript(*[c.encode('ascii') for c in cmd]) except Exception as e: raise GRFException(e) pngs = out_file.read() else: from subprocess import PIPE, Popen # Ghostscript seems to be sensitive to argument order cmd[13:13] += [ '-sstdout=%stderr', '-sOutputFile=%stdout', ] cmd += [ '-f', '-' ] p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) pngs, stderr = p.communicate(pdf) if stderr: raise GRFException(stderr) # This is what PIL uses to identify PNGs png_start = b'\211PNG\r\n\032\n' grfs = [] for png in pngs.split(png_start)[1:]: grfs.append(cls.from_image(png_start + png, filename)) return grfs
Filename is 1-8 alphanumeric characters to identify the GRF in ZPL. Dimensions and DPI are for a typical 4"x6" shipping label. E.g. 432 points / 72 points in an inch / 203 dpi = 6 inches Using center of pixel will improve barcode quality but may decrease the quality of some text. use_bindings=False: - Uses subprocess.Popen - Forks so there is a memory spike - Easier to setup - only needs the gs binary use_bindings=True: - Uses python-ghostscript - Doesn't fork so should use less memory - python-ghostscript is a bit buggy - May be harder to setup - even if you have updated the gs binary there may stil be old libgs* files on your system
https://github.com/kylemacfarlane/zplgrf/blob/aacad3e69c7abe04dbfe9ce3c5cf6ac2a1ab67b3/src/zplgrf/__init__.py#L384-L485
kylemacfarlane/zplgrf
src/zplgrf/__init__.py
GRF._optimise_barcodes
def _optimise_barcodes( self, data, min_bar_height=20, min_bar_count=100, max_gap_size=30, min_percent_white=0.2, max_percent_white=0.8, **kwargs ): """ min_bar_height = Minimum height of black bars in px. Set this too low and it might pick up text and data matrices, too high and it might pick up borders, tables, etc. min_bar_count = Minimum number of parallel black bars before a pattern is considered a potential barcode. max_gap_size = Biggest white gap in px allowed between black bars. This is only important if you have multiple barcodes next to each other. min_percent_white = Minimum percentage of white bars between black bars. This helps to ignore solid rectangles. max_percent_white = Maximum percentage of white bars between black bars. This helps to ignore solid rectangles. """ re_bars = re.compile(r'1{%s,}' % min_bar_height) bars = {} for i, line in enumerate(data): for match in re_bars.finditer(line): try: bars[match.span()].append(i) except KeyError: bars[match.span()] = [i] grouped_bars = [] for span, seen_at in bars.items(): group = [] for coords in seen_at: if group and coords - group[-1] > max_gap_size: grouped_bars.append((span, group)) group = [] group.append(coords) grouped_bars.append((span, group)) suspected_barcodes = [] for span, seen_at in grouped_bars: if len(seen_at) < min_bar_count: continue pc_white = len(seen_at) / float(seen_at[-1] - seen_at[0]) if pc_white >= min_percent_white and pc_white <= max_percent_white: suspected_barcodes.append((span, seen_at)) for span, seen_at in suspected_barcodes: barcode = [] for line in data[seen_at[0]:seen_at[-1]+1]: barcode.append(line[span[0]]) barcode = ''.join(barcode) # Do the actual optimisation barcode = self._optimise_barcode(barcode) barcode = list(barcode) barcode.reverse() width = span[1] - span[0] for i in range(seen_at[0], seen_at[-1]+1): line = data[i] line = ( line[:span[0]] + (barcode.pop() * width) + line[span[1]:] ) data[i] = line return data
python
def _optimise_barcodes( self, data, min_bar_height=20, min_bar_count=100, max_gap_size=30, min_percent_white=0.2, max_percent_white=0.8, **kwargs ): """ min_bar_height = Minimum height of black bars in px. Set this too low and it might pick up text and data matrices, too high and it might pick up borders, tables, etc. min_bar_count = Minimum number of parallel black bars before a pattern is considered a potential barcode. max_gap_size = Biggest white gap in px allowed between black bars. This is only important if you have multiple barcodes next to each other. min_percent_white = Minimum percentage of white bars between black bars. This helps to ignore solid rectangles. max_percent_white = Maximum percentage of white bars between black bars. This helps to ignore solid rectangles. """ re_bars = re.compile(r'1{%s,}' % min_bar_height) bars = {} for i, line in enumerate(data): for match in re_bars.finditer(line): try: bars[match.span()].append(i) except KeyError: bars[match.span()] = [i] grouped_bars = [] for span, seen_at in bars.items(): group = [] for coords in seen_at: if group and coords - group[-1] > max_gap_size: grouped_bars.append((span, group)) group = [] group.append(coords) grouped_bars.append((span, group)) suspected_barcodes = [] for span, seen_at in grouped_bars: if len(seen_at) < min_bar_count: continue pc_white = len(seen_at) / float(seen_at[-1] - seen_at[0]) if pc_white >= min_percent_white and pc_white <= max_percent_white: suspected_barcodes.append((span, seen_at)) for span, seen_at in suspected_barcodes: barcode = [] for line in data[seen_at[0]:seen_at[-1]+1]: barcode.append(line[span[0]]) barcode = ''.join(barcode) # Do the actual optimisation barcode = self._optimise_barcode(barcode) barcode = list(barcode) barcode.reverse() width = span[1] - span[0] for i in range(seen_at[0], seen_at[-1]+1): line = data[i] line = ( line[:span[0]] + (barcode.pop() * width) + line[span[1]:] ) data[i] = line return data
min_bar_height = Minimum height of black bars in px. Set this too low and it might pick up text and data matrices, too high and it might pick up borders, tables, etc. min_bar_count = Minimum number of parallel black bars before a pattern is considered a potential barcode. max_gap_size = Biggest white gap in px allowed between black bars. This is only important if you have multiple barcodes next to each other. min_percent_white = Minimum percentage of white bars between black bars. This helps to ignore solid rectangles. max_percent_white = Maximum percentage of white bars between black bars. This helps to ignore solid rectangles.
https://github.com/kylemacfarlane/zplgrf/blob/aacad3e69c7abe04dbfe9ce3c5cf6ac2a1ab67b3/src/zplgrf/__init__.py#L506-L572
luckydonald/pytgbot
pytgbot/api_types/sendable/payments.py
ShippingOption.from_array
def from_array(array): """ Deserialize a new ShippingOption from a given dictionary. :return: new ShippingOption instance. :rtype: ShippingOption """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['id'] = u(array.get('id')) data['title'] = u(array.get('title')) data['prices'] = LabeledPrice.from_array_list(array.get('prices'), list_level=1) instance = ShippingOption(**data) instance._raw = array return instance
python
def from_array(array): """ Deserialize a new ShippingOption from a given dictionary. :return: new ShippingOption instance. :rtype: ShippingOption """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['id'] = u(array.get('id')) data['title'] = u(array.get('title')) data['prices'] = LabeledPrice.from_array_list(array.get('prices'), list_level=1) instance = ShippingOption(**data) instance._raw = array return instance
Deserialize a new ShippingOption from a given dictionary. :return: new ShippingOption instance. :rtype: ShippingOption
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/payments.py#L172-L192
luckydonald/pytgbot
code_generation/code_generator.py
convert_to_underscore
def convert_to_underscore(name): """ "someFunctionWhatever" -> "some_function_whatever" """ s1 = _first_cap_re.sub(r'\1_\2', name) return _all_cap_re.sub(r'\1_\2', s1).lower()
python
def convert_to_underscore(name): """ "someFunctionWhatever" -> "some_function_whatever" """ s1 = _first_cap_re.sub(r'\1_\2', name) return _all_cap_re.sub(r'\1_\2', s1).lower()
"someFunctionWhatever" -> "some_function_whatever"
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator.py#L20-L23
luckydonald/pytgbot
code_generation/code_generator.py
func
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"): """ Live template for pycharm: y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$") """ description_with_tabs = "\t\t" + description.strip().replace("\n", "\n\t\t") param_list_args = [] param_list_kwargs = [] args = [] args2 = [] kwargs = [] kwargs2 = [] asserts = [] str_args = "" str_kwargs = "" param_strings = params_string.split("\n") for param in param_strings: assert_commands, assert_comments, param_name, param_type, table, non_buildin_type, param_name_input = parse_param_types(param) param_required = table[2].strip() param_needed = None if param_required == "Yes": param_needed = True elif param_required == "Optional": param_needed = False param_description = table[3].strip() if param_needed: param_list_args.append(Param(param_name, param_type,param_needed, param_description)) args.append(param_name) args2.append("{param_name}={param_name}".format(param_name=param_name)) str_args += '\t\t:param {key}: {descr}\n\t\t:type {key}: {type}\n\n'.format(key=param_name, descr=param_description, type=param_type) if assert_commands: asserts.append("assert({var} is not None)".format(var=param_name)) asserts.append("assert({ass})".format(ass=" or ".join(assert_commands)) + ((" # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else "")) else: param_list_kwargs.append(Param(param_name, param_type,param_needed, param_description)) kwargs.append("{param_name}=None".format(param_name=param_name)) kwargs2.append("{param_name}={param_name}".format(param_name=param_name)) str_kwargs += '\t\t:keyword {key}: {descr}\n\t\t:type {key}: {type}\n\n'.format(key=param_name, descr=param_description, type=param_type) if assert_commands: asserts.append("assert({var} is None or {ass})".format(var=param_name, ass=" or ".join(assert_commands)) + ((" # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else "")) args.extend(kwargs) args2.extend(kwargs2) asserts_string = "\n\t\t" + "\n\t\t".join(asserts) text = "" if len(str_args)>0: text += '\n\t\tParameters:\n\n' text += str_args if len(str_kwargs)>0: text += '\n\t\tOptional keyword parameters:\n\n' text += str_kwargs do_args = ['"%s"' % command] do_args.extend(args2) result = '\tdef {funcname}(self, {params}):\n\t\t"""\n{description_with_tabs}\n\n\t\t{link}\n\n' \ '{paramshit}\n' \ '\t\tReturns:\n\n\t\t:return: {returns}\n\t\t:rtype: {return_type}\n\t\t"""{asserts_with_tabs}\n\t\treturn self.do({do_args})\n\t# end def {funcname}'.format( funcname=convert_to_underscore(command), params=", ".join(args), description_with_tabs=description_with_tabs, link=link, returns=returns, return_type=return_type, command=command, do_args=", ".join(do_args), asserts_with_tabs=asserts_string, paramshit = text ) result = result.replace("\t", " ") return result
python
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"): """ Live template for pycharm: y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$") """ description_with_tabs = "\t\t" + description.strip().replace("\n", "\n\t\t") param_list_args = [] param_list_kwargs = [] args = [] args2 = [] kwargs = [] kwargs2 = [] asserts = [] str_args = "" str_kwargs = "" param_strings = params_string.split("\n") for param in param_strings: assert_commands, assert_comments, param_name, param_type, table, non_buildin_type, param_name_input = parse_param_types(param) param_required = table[2].strip() param_needed = None if param_required == "Yes": param_needed = True elif param_required == "Optional": param_needed = False param_description = table[3].strip() if param_needed: param_list_args.append(Param(param_name, param_type,param_needed, param_description)) args.append(param_name) args2.append("{param_name}={param_name}".format(param_name=param_name)) str_args += '\t\t:param {key}: {descr}\n\t\t:type {key}: {type}\n\n'.format(key=param_name, descr=param_description, type=param_type) if assert_commands: asserts.append("assert({var} is not None)".format(var=param_name)) asserts.append("assert({ass})".format(ass=" or ".join(assert_commands)) + ((" # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else "")) else: param_list_kwargs.append(Param(param_name, param_type,param_needed, param_description)) kwargs.append("{param_name}=None".format(param_name=param_name)) kwargs2.append("{param_name}={param_name}".format(param_name=param_name)) str_kwargs += '\t\t:keyword {key}: {descr}\n\t\t:type {key}: {type}\n\n'.format(key=param_name, descr=param_description, type=param_type) if assert_commands: asserts.append("assert({var} is None or {ass})".format(var=param_name, ass=" or ".join(assert_commands)) + ((" # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else "")) args.extend(kwargs) args2.extend(kwargs2) asserts_string = "\n\t\t" + "\n\t\t".join(asserts) text = "" if len(str_args)>0: text += '\n\t\tParameters:\n\n' text += str_args if len(str_kwargs)>0: text += '\n\t\tOptional keyword parameters:\n\n' text += str_kwargs do_args = ['"%s"' % command] do_args.extend(args2) result = '\tdef {funcname}(self, {params}):\n\t\t"""\n{description_with_tabs}\n\n\t\t{link}\n\n' \ '{paramshit}\n' \ '\t\tReturns:\n\n\t\t:return: {returns}\n\t\t:rtype: {return_type}\n\t\t"""{asserts_with_tabs}\n\t\treturn self.do({do_args})\n\t# end def {funcname}'.format( funcname=convert_to_underscore(command), params=", ".join(args), description_with_tabs=description_with_tabs, link=link, returns=returns, return_type=return_type, command=command, do_args=", ".join(do_args), asserts_with_tabs=asserts_string, paramshit = text ) result = result.replace("\t", " ") return result
Live template for pycharm: y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$")
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator.py#L26-L89
luckydonald/pytgbot
code_generation/code_generator.py
clazz
def clazz(clazz, parent_clazz, description, link, params_string, init_super_args=None): """ Live template for pycharm: y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$desc$", link="$lnk$", params_string="$first_param$") """ init_description_w_tabs = description.strip().replace("\n", "\n\t\t") clazz_description_w_tabs = description.strip().replace("\n", "\n\t") imports = [[], []] args = [] args2 = [] kwargs = [] kwargs2 = [] asserts = [] str_args = "" str_kwargs = "" to_array1 = [] to_array2 = [] from_array1 = [] from_array2 = [] param_strings = params_string.split("\n") for param in param_strings: assert_commands, assert_comments, param_name, param_type, table, non_buildin_type, param_name_input = parse_param_types(param) param_description = table[2].strip() param_needed = not param_description.startswith("Optional.") asserts.append("") if param_needed: args.append(param_name) str_args += '\n\n\t\t:param {key}: {descr}\n\t\t:type {key}: {type}'.format(key=param_name, descr=param_description, type=get_type_path(param_type)) if assert_commands: asserts.append("assert({var} is not None)".format(var=param_name)) asserts.append("assert({ass})".format(ass=" or ".join(assert_commands)) + ((" # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else "")) if non_buildin_type: to_array1.append('array["{var}"] = self.{var}.to_array()'.format(var=param_name)) from_array1.append("data['{var}'] = {type}.from_array(array.get('{array_key}'))".format(var=param_name, array_key=param_name_input, type=non_buildin_type)) else: to_array1.append('array["{var}"] = self.{var}'.format(var=param_name)) from_array2.append("data['{var}'] = array.get('{array_key}') # type {type}".format(var=param_name, array_key=param_name_input, type=non_buildin_type)) # end if non_buildin_type else: kwargs.append("{param_name}=None".format(param_name=param_name)) str_kwargs += '\n\n\t\t:keyword {key}: {descr}\n\t\t:type {key}: {type}'.format(key=param_name, descr=param_description, type=param_type) if assert_commands: asserts.append("assert({var} is None or {ass})".format(var=param_name, ass=" or ".join(assert_commands)) + ((" # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else "")) to_array2.append('if self.{var} is not None:'.format(var=param_name)) if non_buildin_type: to_array2.append('\tarray["{var}"] = self.{var}.to_array()'.format(var=param_name)) from_array2.append("data['{var}'] = {type}.from_array(array.get('{array_key}'))".format(var=param_name, array_key=param_name_input, type=non_buildin_type)) else: to_array2.append('\tarray["{var}"] = self.{var}'.format(var=param_name)) from_array2.append("data['{var}'] = array.get('{array_key}') # type {type}".format(var=param_name, array_key=param_name_input, type=non_buildin_type)) # end if non_buildin_type asserts.append("self.{param_name} = {param_name}".format(param_name=param_name)) param_description = "" if len(str_args)>0: param_description += '\n\t\tParameters:' param_description += str_args if len(str_kwargs)>0: param_description += '\n\n\n\t\tOptional keyword parameters:' param_description += str_kwargs args.extend(kwargs) to_array = ["array = super({clazz}, self).to_array()".format(clazz=clazz)] to_array.extend(to_array1) to_array.extend(to_array2) from_array = ["data = super({clazz}).from_array(array)".format(clazz=clazz)] from_array.extend(from_array1) from_array.extend(from_array2) from_array.append("return {clazz}(**data)".format(clazz=clazz)) result = 'class {clazz}({parent_clazz}):\n' \ '\t"""\n' \ '\t{clazz_description_w_tabs}\n' \ '\n' \ '\t{link}\n' \ '\t"""\n' \ '\tdef __init__(self, {params}):\n' \ '\t\t"""\n' \ '\t\t{init_description_w_tabs}\n' \ '\n' \ '\t\t{link}\n' \ '\n' \ '{param_description}\n' \ '\t\t"""\n' \ '\t\tsuper({clazz}, self).__init__({init_super_args})\n' \ '\t\t{asserts_with_tabs}\n' \ '\t# end def __init__\n' \ '\n' \ '\tdef to_array(self):\n' \ '\t\t{to_array_with_tabs}\n' \ '\t\treturn array\n' \ '\t# end def to_array\n' \ '\n' \ '\t@staticmethod\n' \ '\tdef from_array(array):\n' \ '\t\tif array is None:\n' \ '\t\t\treturn None\n' \ '\t\t# end if\n' \ '\t\t{from_array_with_tabs}\n' \ '\t# end def from_array\n' \ '# end class {clazz}\n'.format( clazz=clazz, parent_clazz=parent_clazz, params=", ".join(args), param_description = param_description, clazz_description_w_tabs=clazz_description_w_tabs, init_description_w_tabs=init_description_w_tabs, link=link, asserts_with_tabs="\n\t\t".join(asserts), to_array_with_tabs="\n\t\t".join(to_array), from_array_with_tabs="\n\t\t".join(from_array), init_super_args=(", ".join(init_super_args) if init_super_args else "") ) result = result.replace("\t", " ") return result
python
def clazz(clazz, parent_clazz, description, link, params_string, init_super_args=None): """ Live template for pycharm: y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$desc$", link="$lnk$", params_string="$first_param$") """ init_description_w_tabs = description.strip().replace("\n", "\n\t\t") clazz_description_w_tabs = description.strip().replace("\n", "\n\t") imports = [[], []] args = [] args2 = [] kwargs = [] kwargs2 = [] asserts = [] str_args = "" str_kwargs = "" to_array1 = [] to_array2 = [] from_array1 = [] from_array2 = [] param_strings = params_string.split("\n") for param in param_strings: assert_commands, assert_comments, param_name, param_type, table, non_buildin_type, param_name_input = parse_param_types(param) param_description = table[2].strip() param_needed = not param_description.startswith("Optional.") asserts.append("") if param_needed: args.append(param_name) str_args += '\n\n\t\t:param {key}: {descr}\n\t\t:type {key}: {type}'.format(key=param_name, descr=param_description, type=get_type_path(param_type)) if assert_commands: asserts.append("assert({var} is not None)".format(var=param_name)) asserts.append("assert({ass})".format(ass=" or ".join(assert_commands)) + ((" # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else "")) if non_buildin_type: to_array1.append('array["{var}"] = self.{var}.to_array()'.format(var=param_name)) from_array1.append("data['{var}'] = {type}.from_array(array.get('{array_key}'))".format(var=param_name, array_key=param_name_input, type=non_buildin_type)) else: to_array1.append('array["{var}"] = self.{var}'.format(var=param_name)) from_array2.append("data['{var}'] = array.get('{array_key}') # type {type}".format(var=param_name, array_key=param_name_input, type=non_buildin_type)) # end if non_buildin_type else: kwargs.append("{param_name}=None".format(param_name=param_name)) str_kwargs += '\n\n\t\t:keyword {key}: {descr}\n\t\t:type {key}: {type}'.format(key=param_name, descr=param_description, type=param_type) if assert_commands: asserts.append("assert({var} is None or {ass})".format(var=param_name, ass=" or ".join(assert_commands)) + ((" # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else "")) to_array2.append('if self.{var} is not None:'.format(var=param_name)) if non_buildin_type: to_array2.append('\tarray["{var}"] = self.{var}.to_array()'.format(var=param_name)) from_array2.append("data['{var}'] = {type}.from_array(array.get('{array_key}'))".format(var=param_name, array_key=param_name_input, type=non_buildin_type)) else: to_array2.append('\tarray["{var}"] = self.{var}'.format(var=param_name)) from_array2.append("data['{var}'] = array.get('{array_key}') # type {type}".format(var=param_name, array_key=param_name_input, type=non_buildin_type)) # end if non_buildin_type asserts.append("self.{param_name} = {param_name}".format(param_name=param_name)) param_description = "" if len(str_args)>0: param_description += '\n\t\tParameters:' param_description += str_args if len(str_kwargs)>0: param_description += '\n\n\n\t\tOptional keyword parameters:' param_description += str_kwargs args.extend(kwargs) to_array = ["array = super({clazz}, self).to_array()".format(clazz=clazz)] to_array.extend(to_array1) to_array.extend(to_array2) from_array = ["data = super({clazz}).from_array(array)".format(clazz=clazz)] from_array.extend(from_array1) from_array.extend(from_array2) from_array.append("return {clazz}(**data)".format(clazz=clazz)) result = 'class {clazz}({parent_clazz}):\n' \ '\t"""\n' \ '\t{clazz_description_w_tabs}\n' \ '\n' \ '\t{link}\n' \ '\t"""\n' \ '\tdef __init__(self, {params}):\n' \ '\t\t"""\n' \ '\t\t{init_description_w_tabs}\n' \ '\n' \ '\t\t{link}\n' \ '\n' \ '{param_description}\n' \ '\t\t"""\n' \ '\t\tsuper({clazz}, self).__init__({init_super_args})\n' \ '\t\t{asserts_with_tabs}\n' \ '\t# end def __init__\n' \ '\n' \ '\tdef to_array(self):\n' \ '\t\t{to_array_with_tabs}\n' \ '\t\treturn array\n' \ '\t# end def to_array\n' \ '\n' \ '\t@staticmethod\n' \ '\tdef from_array(array):\n' \ '\t\tif array is None:\n' \ '\t\t\treturn None\n' \ '\t\t# end if\n' \ '\t\t{from_array_with_tabs}\n' \ '\t# end def from_array\n' \ '# end class {clazz}\n'.format( clazz=clazz, parent_clazz=parent_clazz, params=", ".join(args), param_description = param_description, clazz_description_w_tabs=clazz_description_w_tabs, init_description_w_tabs=init_description_w_tabs, link=link, asserts_with_tabs="\n\t\t".join(asserts), to_array_with_tabs="\n\t\t".join(to_array), from_array_with_tabs="\n\t\t".join(from_array), init_super_args=(", ".join(init_super_args) if init_super_args else "") ) result = result.replace("\t", " ") return result
Live template for pycharm: y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$desc$", link="$lnk$", params_string="$first_param$")
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator.py#L106-L212
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/receivable/peer.py
User.to_array
def to_array(self): """ Serializes this User to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(User, self).to_array() array['id'] = int(self.id) # type int array['is_bot'] = bool(self.is_bot) # type bool array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.username is not None: array['username'] = u(self.username) # py2: type unicode, py3: type str if self.language_code is not None: array['language_code'] = u(self.language_code) # py2: type unicode, py3: type str return array
python
def to_array(self): """ Serializes this User to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(User, self).to_array() array['id'] = int(self.id) # type int array['is_bot'] = bool(self.is_bot) # type bool array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.username is not None: array['username'] = u(self.username) # py2: type unicode, py3: type str if self.language_code is not None: array['language_code'] = u(self.language_code) # py2: type unicode, py3: type str return array
Serializes this User to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/peer.py#L98-L119
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/receivable/peer.py
User.from_array
def from_array(array): """ Deserialize a new User from a given dictionary. :return: new User instance. :rtype: User """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['id'] = int(array.get('id')) data['is_bot'] = bool(array.get('is_bot')) data['first_name'] = u(array.get('first_name')) data['last_name'] = u(array.get('last_name')) if array.get('last_name') is not None else None data['username'] = u(array.get('username')) if array.get('username') is not None else None data['language_code'] = u(array.get('language_code')) if array.get('language_code') is not None else None data['_raw'] = array return User(**data)
python
def from_array(array): """ Deserialize a new User from a given dictionary. :return: new User instance. :rtype: User """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['id'] = int(array.get('id')) data['is_bot'] = bool(array.get('is_bot')) data['first_name'] = u(array.get('first_name')) data['last_name'] = u(array.get('last_name')) if array.get('last_name') is not None else None data['username'] = u(array.get('username')) if array.get('username') is not None else None data['language_code'] = u(array.get('language_code')) if array.get('language_code') is not None else None data['_raw'] = array return User(**data)
Deserialize a new User from a given dictionary. :return: new User instance. :rtype: User
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/peer.py#L123-L143
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/receivable/peer.py
Chat.to_array
def to_array(self): """ Serializes this Chat to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Chat, self).to_array() array['id'] = int(self.id) # type int array['type'] = u(self.type) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.username is not None: array['username'] = u(self.username) # py2: type unicode, py3: type str if self.first_name is not None: array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.all_members_are_administrators is not None: array['all_members_are_administrators'] = bool(self.all_members_are_administrators) # type bool if self.photo is not None: array['photo'] = self.photo.to_array() # type ChatPhoto if self.description is not None: array['description'] = u(self.description) # py2: type unicode, py3: type str if self.invite_link is not None: array['invite_link'] = u(self.invite_link) # py2: type unicode, py3: type str if self.pinned_message is not None: array['pinned_message'] = self.pinned_message.to_array() # type Message if self.sticker_set_name is not None: array['sticker_set_name'] = u(self.sticker_set_name) # py2: type unicode, py3: type str if self.can_set_sticker_set is not None: array['can_set_sticker_set'] = bool(self.can_set_sticker_set) # type bool return array
python
def to_array(self): """ Serializes this Chat to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Chat, self).to_array() array['id'] = int(self.id) # type int array['type'] = u(self.type) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.username is not None: array['username'] = u(self.username) # py2: type unicode, py3: type str if self.first_name is not None: array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.all_members_are_administrators is not None: array['all_members_are_administrators'] = bool(self.all_members_are_administrators) # type bool if self.photo is not None: array['photo'] = self.photo.to_array() # type ChatPhoto if self.description is not None: array['description'] = u(self.description) # py2: type unicode, py3: type str if self.invite_link is not None: array['invite_link'] = u(self.invite_link) # py2: type unicode, py3: type str if self.pinned_message is not None: array['pinned_message'] = self.pinned_message.to_array() # type Message if self.sticker_set_name is not None: array['sticker_set_name'] = u(self.sticker_set_name) # py2: type unicode, py3: type str if self.can_set_sticker_set is not None: array['can_set_sticker_set'] = bool(self.can_set_sticker_set) # type bool return array
Serializes this Chat to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/peer.py#L327-L369
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/receivable/peer.py
Chat.from_array
def from_array(array): """ Deserialize a new Chat from a given dictionary. :return: new Chat instance. :rtype: Chat """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.media import ChatPhoto from pytgbot.api_types.receivable.updates import Message data = {} data['id'] = int(array.get('id')) data['type'] = u(array.get('type')) data['title'] = u(array.get('title')) if array.get('title') is not None else None data['username'] = u(array.get('username')) if array.get('username') is not None else None data['first_name'] = u(array.get('first_name')) if array.get('first_name') is not None else None data['last_name'] = u(array.get('last_name')) if array.get('last_name') is not None else None data['all_members_are_administrators'] = bool(array.get('all_members_are_administrators')) if array.get('all_members_are_administrators') is not None else None data['photo'] = ChatPhoto.from_array(array.get('photo')) if array.get('photo') is not None else None data['description'] = u(array.get('description')) if array.get('description') is not None else None data['invite_link'] = u(array.get('invite_link')) if array.get('invite_link') is not None else None data['pinned_message'] = Message.from_array(array.get('pinned_message')) if array.get('pinned_message') is not None else None data['sticker_set_name'] = u(array.get('sticker_set_name')) if array.get('sticker_set_name') is not None else None data['can_set_sticker_set'] = bool(array.get('can_set_sticker_set')) if array.get('can_set_sticker_set') is not None else None data['_raw'] = array return Chat(**data)
python
def from_array(array): """ Deserialize a new Chat from a given dictionary. :return: new Chat instance. :rtype: Chat """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.media import ChatPhoto from pytgbot.api_types.receivable.updates import Message data = {} data['id'] = int(array.get('id')) data['type'] = u(array.get('type')) data['title'] = u(array.get('title')) if array.get('title') is not None else None data['username'] = u(array.get('username')) if array.get('username') is not None else None data['first_name'] = u(array.get('first_name')) if array.get('first_name') is not None else None data['last_name'] = u(array.get('last_name')) if array.get('last_name') is not None else None data['all_members_are_administrators'] = bool(array.get('all_members_are_administrators')) if array.get('all_members_are_administrators') is not None else None data['photo'] = ChatPhoto.from_array(array.get('photo')) if array.get('photo') is not None else None data['description'] = u(array.get('description')) if array.get('description') is not None else None data['invite_link'] = u(array.get('invite_link')) if array.get('invite_link') is not None else None data['pinned_message'] = Message.from_array(array.get('pinned_message')) if array.get('pinned_message') is not None else None data['sticker_set_name'] = u(array.get('sticker_set_name')) if array.get('sticker_set_name') is not None else None data['can_set_sticker_set'] = bool(array.get('can_set_sticker_set')) if array.get('can_set_sticker_set') is not None else None data['_raw'] = array return Chat(**data)
Deserialize a new Chat from a given dictionary. :return: new Chat instance. :rtype: Chat
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/peer.py#L373-L403
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/receivable/peer.py
ChatMember.to_array
def to_array(self): """ Serializes this ChatMember to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ChatMember, self).to_array() array['user'] = self.user.to_array() # type User array['status'] = u(self.status) # py2: type unicode, py3: type str if self.until_date is not None: array['until_date'] = int(self.until_date) # type int if self.can_be_edited is not None: array['can_be_edited'] = bool(self.can_be_edited) # type bool if self.can_change_info is not None: array['can_change_info'] = bool(self.can_change_info) # type bool if self.can_post_messages is not None: array['can_post_messages'] = bool(self.can_post_messages) # type bool if self.can_edit_messages is not None: array['can_edit_messages'] = bool(self.can_edit_messages) # type bool if self.can_delete_messages is not None: array['can_delete_messages'] = bool(self.can_delete_messages) # type bool if self.can_invite_users is not None: array['can_invite_users'] = bool(self.can_invite_users) # type bool if self.can_restrict_members is not None: array['can_restrict_members'] = bool(self.can_restrict_members) # type bool if self.can_pin_messages is not None: array['can_pin_messages'] = bool(self.can_pin_messages) # type bool if self.can_promote_members is not None: array['can_promote_members'] = bool(self.can_promote_members) # type bool if self.can_send_messages is not None: array['can_send_messages'] = bool(self.can_send_messages) # type bool if self.can_send_media_messages is not None: array['can_send_media_messages'] = bool(self.can_send_media_messages) # type bool if self.can_send_other_messages is not None: array['can_send_other_messages'] = bool(self.can_send_other_messages) # type bool if self.can_add_web_page_previews is not None: array['can_add_web_page_previews'] = bool(self.can_add_web_page_previews) # type bool return array
python
def to_array(self): """ Serializes this ChatMember to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ChatMember, self).to_array() array['user'] = self.user.to_array() # type User array['status'] = u(self.status) # py2: type unicode, py3: type str if self.until_date is not None: array['until_date'] = int(self.until_date) # type int if self.can_be_edited is not None: array['can_be_edited'] = bool(self.can_be_edited) # type bool if self.can_change_info is not None: array['can_change_info'] = bool(self.can_change_info) # type bool if self.can_post_messages is not None: array['can_post_messages'] = bool(self.can_post_messages) # type bool if self.can_edit_messages is not None: array['can_edit_messages'] = bool(self.can_edit_messages) # type bool if self.can_delete_messages is not None: array['can_delete_messages'] = bool(self.can_delete_messages) # type bool if self.can_invite_users is not None: array['can_invite_users'] = bool(self.can_invite_users) # type bool if self.can_restrict_members is not None: array['can_restrict_members'] = bool(self.can_restrict_members) # type bool if self.can_pin_messages is not None: array['can_pin_messages'] = bool(self.can_pin_messages) # type bool if self.can_promote_members is not None: array['can_promote_members'] = bool(self.can_promote_members) # type bool if self.can_send_messages is not None: array['can_send_messages'] = bool(self.can_send_messages) # type bool if self.can_send_media_messages is not None: array['can_send_media_messages'] = bool(self.can_send_media_messages) # type bool if self.can_send_other_messages is not None: array['can_send_other_messages'] = bool(self.can_send_other_messages) # type bool if self.can_add_web_page_previews is not None: array['can_add_web_page_previews'] = bool(self.can_add_web_page_previews) # type bool return array
Serializes this ChatMember to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/peer.py#L613-L653
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/receivable/peer.py
ChatMember.from_array
def from_array(array): """ Deserialize a new ChatMember from a given dictionary. :return: new ChatMember instance. :rtype: ChatMember """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.peer import User data = {} data['user'] = User.from_array(array.get('user')) data['status'] = u(array.get('status')) data['until_date'] = int(array.get('until_date')) if array.get('until_date') is not None else None data['can_be_edited'] = bool(array.get('can_be_edited')) if array.get('can_be_edited') is not None else None data['can_change_info'] = bool(array.get('can_change_info')) if array.get('can_change_info') is not None else None data['can_post_messages'] = bool(array.get('can_post_messages')) if array.get('can_post_messages') is not None else None data['can_edit_messages'] = bool(array.get('can_edit_messages')) if array.get('can_edit_messages') is not None else None data['can_delete_messages'] = bool(array.get('can_delete_messages')) if array.get('can_delete_messages') is not None else None data['can_invite_users'] = bool(array.get('can_invite_users')) if array.get('can_invite_users') is not None else None data['can_restrict_members'] = bool(array.get('can_restrict_members')) if array.get('can_restrict_members') is not None else None data['can_pin_messages'] = bool(array.get('can_pin_messages')) if array.get('can_pin_messages') is not None else None data['can_promote_members'] = bool(array.get('can_promote_members')) if array.get('can_promote_members') is not None else None data['can_send_messages'] = bool(array.get('can_send_messages')) if array.get('can_send_messages') is not None else None data['can_send_media_messages'] = bool(array.get('can_send_media_messages')) if array.get('can_send_media_messages') is not None else None data['can_send_other_messages'] = bool(array.get('can_send_other_messages')) if array.get('can_send_other_messages') is not None else None data['can_add_web_page_previews'] = bool(array.get('can_add_web_page_previews')) if array.get('can_add_web_page_previews') is not None else None data['_raw'] = array return ChatMember(**data)
python
def from_array(array): """ Deserialize a new ChatMember from a given dictionary. :return: new ChatMember instance. :rtype: ChatMember """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.peer import User data = {} data['user'] = User.from_array(array.get('user')) data['status'] = u(array.get('status')) data['until_date'] = int(array.get('until_date')) if array.get('until_date') is not None else None data['can_be_edited'] = bool(array.get('can_be_edited')) if array.get('can_be_edited') is not None else None data['can_change_info'] = bool(array.get('can_change_info')) if array.get('can_change_info') is not None else None data['can_post_messages'] = bool(array.get('can_post_messages')) if array.get('can_post_messages') is not None else None data['can_edit_messages'] = bool(array.get('can_edit_messages')) if array.get('can_edit_messages') is not None else None data['can_delete_messages'] = bool(array.get('can_delete_messages')) if array.get('can_delete_messages') is not None else None data['can_invite_users'] = bool(array.get('can_invite_users')) if array.get('can_invite_users') is not None else None data['can_restrict_members'] = bool(array.get('can_restrict_members')) if array.get('can_restrict_members') is not None else None data['can_pin_messages'] = bool(array.get('can_pin_messages')) if array.get('can_pin_messages') is not None else None data['can_promote_members'] = bool(array.get('can_promote_members')) if array.get('can_promote_members') is not None else None data['can_send_messages'] = bool(array.get('can_send_messages')) if array.get('can_send_messages') is not None else None data['can_send_media_messages'] = bool(array.get('can_send_media_messages')) if array.get('can_send_media_messages') is not None else None data['can_send_other_messages'] = bool(array.get('can_send_other_messages')) if array.get('can_send_other_messages') is not None else None data['can_add_web_page_previews'] = bool(array.get('can_add_web_page_previews')) if array.get('can_add_web_page_previews') is not None else None data['_raw'] = array return ChatMember(**data)
Deserialize a new ChatMember from a given dictionary. :return: new ChatMember instance. :rtype: ChatMember
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/peer.py#L657-L689
delph-in/pydelphin
delphin/mrs/mrx.py
loads
def loads(s, single=False): """ Deserialize MRX string representations Args: s (str): a MRX string single (bool): if `True`, only return the first Xmrs object Returns: a generator of Xmrs objects (unless *single* is `True`) """ corpus = etree.fromstring(s) if single: ds = _deserialize_mrs(next(corpus)) else: ds = (_deserialize_mrs(mrs_elem) for mrs_elem in corpus) return ds
python
def loads(s, single=False): """ Deserialize MRX string representations Args: s (str): a MRX string single (bool): if `True`, only return the first Xmrs object Returns: a generator of Xmrs objects (unless *single* is `True`) """ corpus = etree.fromstring(s) if single: ds = _deserialize_mrs(next(corpus)) else: ds = (_deserialize_mrs(mrs_elem) for mrs_elem in corpus) return ds
Deserialize MRX string representations Args: s (str): a MRX string single (bool): if `True`, only return the first Xmrs object Returns: a generator of Xmrs objects (unless *single* is `True`)
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/mrx.py#L45-L60
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InlineQueryResultArticle.to_array
def to_array(self): """ Serializes this InlineQueryResultArticle to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultArticle, self).to_array() # 'type' and 'id' given by superclass array['title'] = u(self.title) # py2: type unicode, py3: type str array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.url is not None: array['url'] = u(self.url) # py2: type unicode, py3: type str if self.hide_url is not None: array['hide_url'] = bool(self.hide_url) # type bool if self.description is not None: array['description'] = u(self.description) # py2: type unicode, py3: type str if self.thumb_url is not None: array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.thumb_width is not None: array['thumb_width'] = int(self.thumb_width) # type int if self.thumb_height is not None: array['thumb_height'] = int(self.thumb_height) # type int return array
python
def to_array(self): """ Serializes this InlineQueryResultArticle to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultArticle, self).to_array() # 'type' and 'id' given by superclass array['title'] = u(self.title) # py2: type unicode, py3: type str array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.url is not None: array['url'] = u(self.url) # py2: type unicode, py3: type str if self.hide_url is not None: array['hide_url'] = bool(self.hide_url) # type bool if self.description is not None: array['description'] = u(self.description) # py2: type unicode, py3: type str if self.thumb_url is not None: array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.thumb_width is not None: array['thumb_width'] = int(self.thumb_width) # type int if self.thumb_height is not None: array['thumb_height'] = int(self.thumb_height) # type int return array
Serializes this InlineQueryResultArticle to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L167-L192
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InlineQueryResultGif.to_array
def to_array(self): """ Serializes this InlineQueryResultGif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultGif, self).to_array() # 'type' and 'id' given by superclass array['gif_url'] = u(self.gif_url) # py2: type unicode, py3: type str array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.gif_width is not None: array['gif_width'] = int(self.gif_width) # type int if self.gif_height is not None: array['gif_height'] = int(self.gif_height) # type int if self.gif_duration is not None: array['gif_duration'] = int(self.gif_duration) # type int if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
python
def to_array(self): """ Serializes this InlineQueryResultGif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultGif, self).to_array() # 'type' and 'id' given by superclass array['gif_url'] = u(self.gif_url) # py2: type unicode, py3: type str array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.gif_width is not None: array['gif_width'] = int(self.gif_width) # type int if self.gif_height is not None: array['gif_height'] = int(self.gif_height) # type int if self.gif_duration is not None: array['gif_duration'] = int(self.gif_duration) # type int if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
Serializes this InlineQueryResultGif to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L600-L627
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InlineQueryResultAudio.to_array
def to_array(self): """ Serializes this InlineQueryResultAudio to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultAudio, self).to_array() # 'type' and 'id' given by superclass array['audio_url'] = u(self.audio_url) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.performer is not None: array['performer'] = u(self.performer) # py2: type unicode, py3: type str if self.audio_duration is not None: array['audio_duration'] = int(self.audio_duration) # type int if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
python
def to_array(self): """ Serializes this InlineQueryResultAudio to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultAudio, self).to_array() # 'type' and 'id' given by superclass array['audio_url'] = u(self.audio_url) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.performer is not None: array['performer'] = u(self.performer) # py2: type unicode, py3: type str if self.audio_duration is not None: array['audio_duration'] = int(self.audio_duration) # type int if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
Serializes this InlineQueryResultAudio to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L1264-L1287
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InlineQueryResultLocation.to_array
def to_array(self): """ Serializes this InlineQueryResultLocation to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultLocation, self).to_array() # 'type' and 'id' given by superclass array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str if self.live_period is not None: array['live_period'] = int(self.live_period) # type int if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent if self.thumb_url is not None: array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.thumb_width is not None: array['thumb_width'] = int(self.thumb_width) # type int if self.thumb_height is not None: array['thumb_height'] = int(self.thumb_height) # type int return array
python
def to_array(self): """ Serializes this InlineQueryResultLocation to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultLocation, self).to_array() # 'type' and 'id' given by superclass array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str if self.live_period is not None: array['live_period'] = int(self.live_period) # type int if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent if self.thumb_url is not None: array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.thumb_width is not None: array['thumb_width'] = int(self.thumb_width) # type int if self.thumb_height is not None: array['thumb_height'] = int(self.thumb_height) # type int return array
Serializes this InlineQueryResultLocation to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L1884-L1908
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InlineQueryResultContact.to_array
def to_array(self): """ Serializes this InlineQueryResultContact to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultContact, self).to_array() # 'type' and 'id' given by superclass array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent if self.thumb_url is not None: array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.thumb_width is not None: array['thumb_width'] = int(self.thumb_width) # type int if self.thumb_height is not None: array['thumb_height'] = int(self.thumb_height) # type int return array
python
def to_array(self): """ Serializes this InlineQueryResultContact to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultContact, self).to_array() # 'type' and 'id' given by superclass array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent if self.thumb_url is not None: array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.thumb_width is not None: array['thumb_width'] = int(self.thumb_width) # type int if self.thumb_height is not None: array['thumb_height'] = int(self.thumb_height) # type int return array
Serializes this InlineQueryResultContact to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L2321-L2344
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InlineQueryResultGame.to_array
def to_array(self): """ Serializes this InlineQueryResultGame to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultGame, self).to_array() # 'type' and 'id' given by superclass array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup return array
python
def to_array(self): """ Serializes this InlineQueryResultGame to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultGame, self).to_array() # 'type' and 'id' given by superclass array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup return array
Serializes this InlineQueryResultGame to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L2467-L2479
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InlineQueryResultCachedGif.to_array
def to_array(self): """ Serializes this InlineQueryResultCachedGif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedGif, self).to_array() # 'type' and 'id' given by superclass array['gif_file_id'] = u(self.gif_file_id) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
python
def to_array(self): """ Serializes this InlineQueryResultCachedGif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedGif, self).to_array() # 'type' and 'id' given by superclass array['gif_file_id'] = u(self.gif_file_id) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
Serializes this InlineQueryResultCachedGif to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L2811-L2831
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InlineQueryResultCachedDocument.to_array
def to_array(self): """ Serializes this InlineQueryResultCachedDocument to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedDocument, self).to_array() # 'type' and 'id' given by superclass array['title'] = u(self.title) # py2: type unicode, py3: type str array['document_file_id'] = u(self.document_file_id) # py2: type unicode, py3: type str if self.description is not None: array['description'] = u(self.description) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
python
def to_array(self): """ Serializes this InlineQueryResultCachedDocument to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedDocument, self).to_array() # 'type' and 'id' given by superclass array['title'] = u(self.title) # py2: type unicode, py3: type str array['document_file_id'] = u(self.document_file_id) # py2: type unicode, py3: type str if self.description is not None: array['description'] = u(self.description) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
Serializes this InlineQueryResultCachedDocument to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L3306-L3327
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InlineQueryResultCachedVoice.to_array
def to_array(self): """ Serializes this InlineQueryResultCachedVoice to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedVoice, self).to_array() # 'type' and 'id' given by superclass array['voice_file_id'] = u(self.voice_file_id) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
python
def to_array(self): """ Serializes this InlineQueryResultCachedVoice to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedVoice, self).to_array() # 'type' and 'id' given by superclass array['voice_file_id'] = u(self.voice_file_id) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None: array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent return array
Serializes this InlineQueryResultCachedVoice to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L3664-L3683
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InlineQueryResultCachedAudio.from_array
def from_array(array): """ Deserialize a new InlineQueryResultCachedAudio from a given dictionary. :return: new InlineQueryResultCachedAudio instance. :rtype: InlineQueryResultCachedAudio """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup data = {} # 'type' is given by class type data['id'] = u(array.get('id')) data['audio_file_id'] = u(array.get('audio_file_id')) data['caption'] = u(array.get('caption')) if array.get('caption') is not None else None data['parse_mode'] = u(array.get('parse_mode')) if array.get('parse_mode') is not None else None data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None data['input_message_content'] = InputMessageContent.from_array(array.get('input_message_content')) if array.get('input_message_content') is not None else None instance = InlineQueryResultCachedAudio(**data) instance._raw = array return instance
python
def from_array(array): """ Deserialize a new InlineQueryResultCachedAudio from a given dictionary. :return: new InlineQueryResultCachedAudio instance. :rtype: InlineQueryResultCachedAudio """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup data = {} # 'type' is given by class type data['id'] = u(array.get('id')) data['audio_file_id'] = u(array.get('audio_file_id')) data['caption'] = u(array.get('caption')) if array.get('caption') is not None else None data['parse_mode'] = u(array.get('parse_mode')) if array.get('parse_mode') is not None else None data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None data['input_message_content'] = InputMessageContent.from_array(array.get('input_message_content')) if array.get('input_message_content') is not None else None instance = InlineQueryResultCachedAudio(**data) instance._raw = array return instance
Deserialize a new InlineQueryResultCachedAudio from a given dictionary. :return: new InlineQueryResultCachedAudio instance. :rtype: InlineQueryResultCachedAudio
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L3850-L3875
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InputTextMessageContent.to_array
def to_array(self): """ Serializes this InputTextMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputTextMessageContent, self).to_array() array['message_text'] = u(self.message_text) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_web_page_preview is not None: array['disable_web_page_preview'] = bool(self.disable_web_page_preview) # type bool return array
python
def to_array(self): """ Serializes this InputTextMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputTextMessageContent, self).to_array() array['message_text'] = u(self.message_text) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_web_page_preview is not None: array['disable_web_page_preview'] = bool(self.disable_web_page_preview) # type bool return array
Serializes this InputTextMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L3958-L3971
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InputLocationMessageContent.to_array
def to_array(self): """ Serializes this InputLocationMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputLocationMessageContent, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float if self.live_period is not None: array['live_period'] = int(self.live_period) # type int return array
python
def to_array(self): """ Serializes this InputLocationMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputLocationMessageContent, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float if self.live_period is not None: array['live_period'] = int(self.live_period) # type int return array
Serializes this InputLocationMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L4077-L4089
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InputLocationMessageContent.from_array
def from_array(array): """ Deserialize a new InputLocationMessageContent from a given dictionary. :return: new InputLocationMessageContent instance. :rtype: InputLocationMessageContent """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['latitude'] = float(array.get('latitude')) data['longitude'] = float(array.get('longitude')) data['live_period'] = int(array.get('live_period')) if array.get('live_period') is not None else None instance = InputLocationMessageContent(**data) instance._raw = array return instance
python
def from_array(array): """ Deserialize a new InputLocationMessageContent from a given dictionary. :return: new InputLocationMessageContent instance. :rtype: InputLocationMessageContent """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['latitude'] = float(array.get('latitude')) data['longitude'] = float(array.get('longitude')) data['live_period'] = int(array.get('live_period')) if array.get('live_period') is not None else None instance = InputLocationMessageContent(**data) instance._raw = array return instance
Deserialize a new InputLocationMessageContent from a given dictionary. :return: new InputLocationMessageContent instance. :rtype: InputLocationMessageContent
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L4093-L4112
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InputVenueMessageContent.to_array
def to_array(self): """ Serializes this InputVenueMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputVenueMessageContent, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str array['address'] = u(self.address) # py2: type unicode, py3: type str if self.foursquare_id is not None: array['foursquare_id'] = u(self.foursquare_id) # py2: type unicode, py3: type str if self.foursquare_type is not None: array['foursquare_type'] = u(self.foursquare_type) # py2: type unicode, py3: type str return array
python
def to_array(self): """ Serializes this InputVenueMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputVenueMessageContent, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str array['address'] = u(self.address) # py2: type unicode, py3: type str if self.foursquare_id is not None: array['foursquare_id'] = u(self.foursquare_id) # py2: type unicode, py3: type str if self.foursquare_type is not None: array['foursquare_type'] = u(self.foursquare_type) # py2: type unicode, py3: type str return array
Serializes this InputVenueMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L4224-L4240
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InputVenueMessageContent.from_array
def from_array(array): """ Deserialize a new InputVenueMessageContent from a given dictionary. :return: new InputVenueMessageContent instance. :rtype: InputVenueMessageContent """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['latitude'] = float(array.get('latitude')) data['longitude'] = float(array.get('longitude')) data['title'] = u(array.get('title')) data['address'] = u(array.get('address')) data['foursquare_id'] = u(array.get('foursquare_id')) if array.get('foursquare_id') is not None else None data['foursquare_type'] = u(array.get('foursquare_type')) if array.get('foursquare_type') is not None else None instance = InputVenueMessageContent(**data) instance._raw = array return instance
python
def from_array(array): """ Deserialize a new InputVenueMessageContent from a given dictionary. :return: new InputVenueMessageContent instance. :rtype: InputVenueMessageContent """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['latitude'] = float(array.get('latitude')) data['longitude'] = float(array.get('longitude')) data['title'] = u(array.get('title')) data['address'] = u(array.get('address')) data['foursquare_id'] = u(array.get('foursquare_id')) if array.get('foursquare_id') is not None else None data['foursquare_type'] = u(array.get('foursquare_type')) if array.get('foursquare_type') is not None else None instance = InputVenueMessageContent(**data) instance._raw = array return instance
Deserialize a new InputVenueMessageContent from a given dictionary. :return: new InputVenueMessageContent instance. :rtype: InputVenueMessageContent
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L4244-L4266
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
InputContactMessageContent.to_array
def to_array(self): """ Serializes this InputContactMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputContactMessageContent, self).to_array() array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.vcard is not None: array['vcard'] = u(self.vcard) # py2: type unicode, py3: type str return array
python
def to_array(self): """ Serializes this InputContactMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputContactMessageContent, self).to_array() array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.vcard is not None: array['vcard'] = u(self.vcard) # py2: type unicode, py3: type str return array
Serializes this InputContactMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L4360-L4374
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/receivable/passport.py
PassportData.from_array
def from_array(array): """ Deserialize a new PassportData from a given dictionary. :return: new PassportData instance. :rtype: PassportData """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.passport import EncryptedCredentials from pytgbot.api_types.receivable.passport import EncryptedPassportElement data = {} data['data'] = EncryptedPassportElement.from_array_list(array.get('data'), list_level=1) data['credentials'] = EncryptedCredentials.from_array(array.get('credentials')) data['_raw'] = array return PassportData(**data)
python
def from_array(array): """ Deserialize a new PassportData from a given dictionary. :return: new PassportData instance. :rtype: PassportData """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.passport import EncryptedCredentials from pytgbot.api_types.receivable.passport import EncryptedPassportElement data = {} data['data'] = EncryptedPassportElement.from_array_list(array.get('data'), list_level=1) data['credentials'] = EncryptedCredentials.from_array(array.get('credentials')) data['_raw'] = array return PassportData(**data)
Deserialize a new PassportData from a given dictionary. :return: new PassportData instance. :rtype: PassportData
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/passport.py#L80-L99
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/receivable/passport.py
EncryptedPassportElement.from_array
def from_array(array): """ Deserialize a new EncryptedPassportElement from a given dictionary. :return: new EncryptedPassportElement instance. :rtype: EncryptedPassportElement """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.passport import PassportFile data = {} data['type'] = u(array.get('type')) data['hash'] = u(array.get('hash')) data['data'] = u(array.get('data')) if array.get('data') is not None else None data['phone_number'] = u(array.get('phone_number')) if array.get('phone_number') is not None else None data['email'] = u(array.get('email')) if array.get('email') is not None else None data['files'] = PassportFile.from_array_list(array.get('files'), list_level=1) if array.get('files') is not None else None data['front_side'] = PassportFile.from_array(array.get('front_side')) if array.get('front_side') is not None else None data['reverse_side'] = PassportFile.from_array(array.get('reverse_side')) if array.get('reverse_side') is not None else None data['selfie'] = PassportFile.from_array(array.get('selfie')) if array.get('selfie') is not None else None data['translation'] = PassportFile.from_array_list(array.get('translation'), list_level=1) if array.get('translation') is not None else None data['_raw'] = array return EncryptedPassportElement(**data)
python
def from_array(array): """ Deserialize a new EncryptedPassportElement from a given dictionary. :return: new EncryptedPassportElement instance. :rtype: EncryptedPassportElement """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.passport import PassportFile data = {} data['type'] = u(array.get('type')) data['hash'] = u(array.get('hash')) data['data'] = u(array.get('data')) if array.get('data') is not None else None data['phone_number'] = u(array.get('phone_number')) if array.get('phone_number') is not None else None data['email'] = u(array.get('email')) if array.get('email') is not None else None data['files'] = PassportFile.from_array_list(array.get('files'), list_level=1) if array.get('files') is not None else None data['front_side'] = PassportFile.from_array(array.get('front_side')) if array.get('front_side') is not None else None data['reverse_side'] = PassportFile.from_array(array.get('reverse_side')) if array.get('reverse_side') is not None else None data['selfie'] = PassportFile.from_array(array.get('selfie')) if array.get('selfie') is not None else None data['translation'] = PassportFile.from_array_list(array.get('translation'), list_level=1) if array.get('translation') is not None else None data['_raw'] = array return EncryptedPassportElement(**data)
Deserialize a new EncryptedPassportElement from a given dictionary. :return: new EncryptedPassportElement instance. :rtype: EncryptedPassportElement
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/passport.py#L419-L445
luckydonald/pytgbot
code_generation/code_generator_template.py
clazz
def clazz(clazz, parent_clazz, description, link, params_string, init_super_args=None): """ Live template for pycharm: y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$description$", link="$lnk$", params_string="$first_param$") """ variables_needed = [] variables_optional = [] imports = set() for param in params_string.split("\n"): variable = parse_param_types(param) # any variable.types has always_is_value => lenght must be 1. assert(not any([type_.always_is_value is not None for type_ in variable.types]) or len(variable.types) == 1) if variable.optional: variables_optional.append(variable) else: variables_needed.append(variable) # end if imports.update(variable.all_imports) # end for imports = list(imports) imports.sort() if isinstance(parent_clazz, str): parent_clazz = to_type(parent_clazz, "parent class") assert isinstance(parent_clazz, Type) clazz_object = Clazz(imports=imports, clazz=clazz, parent_clazz=parent_clazz, link=link, description=description, parameters=variables_needed, keywords=variables_optional ) return clazz_object
python
def clazz(clazz, parent_clazz, description, link, params_string, init_super_args=None): """ Live template for pycharm: y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$description$", link="$lnk$", params_string="$first_param$") """ variables_needed = [] variables_optional = [] imports = set() for param in params_string.split("\n"): variable = parse_param_types(param) # any variable.types has always_is_value => lenght must be 1. assert(not any([type_.always_is_value is not None for type_ in variable.types]) or len(variable.types) == 1) if variable.optional: variables_optional.append(variable) else: variables_needed.append(variable) # end if imports.update(variable.all_imports) # end for imports = list(imports) imports.sort() if isinstance(parent_clazz, str): parent_clazz = to_type(parent_clazz, "parent class") assert isinstance(parent_clazz, Type) clazz_object = Clazz(imports=imports, clazz=clazz, parent_clazz=parent_clazz, link=link, description=description, parameters=variables_needed, keywords=variables_optional ) return clazz_object
Live template for pycharm: y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$description$", link="$lnk$", params_string="$first_param$")
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator_template.py#L52-L82
luckydonald/pytgbot
code_generation/code_generator_template.py
func
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"): """ Live template for pycharm: y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$") """ variables_needed = [] variables_optional = [] imports = set() if params_string: # WHITELISTED_FUNCS have no params for param in params_string.split("\n"): variable = parse_param_types(param) # any variable.types has always_is_value => lenght must be 1. assert (not any([type_.always_is_value is not None for type_ in variable.types]) or len(variable.types) == 1) if variable.optional: variables_optional.append(variable) else: variables_needed.append(variable) # end if imports.update(variable.all_imports) # end for # end if imports = list(imports) imports.sort() returns = Variable(types=as_types(return_type, variable_name="return type"), description=returns) func_object = Function( imports=imports, api_name=command, link=link, description=description, returns=returns, parameters=variables_needed, keywords=variables_optional ) return func_object
python
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"): """ Live template for pycharm: y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$") """ variables_needed = [] variables_optional = [] imports = set() if params_string: # WHITELISTED_FUNCS have no params for param in params_string.split("\n"): variable = parse_param_types(param) # any variable.types has always_is_value => lenght must be 1. assert (not any([type_.always_is_value is not None for type_ in variable.types]) or len(variable.types) == 1) if variable.optional: variables_optional.append(variable) else: variables_needed.append(variable) # end if imports.update(variable.all_imports) # end for # end if imports = list(imports) imports.sort() returns = Variable(types=as_types(return_type, variable_name="return type"), description=returns) func_object = Function( imports=imports, api_name=command, link=link, description=description, returns=returns, parameters=variables_needed, keywords=variables_optional ) return func_object
Live template for pycharm: y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$")
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator_template.py#L86-L115
luckydonald/pytgbot
code_generation/code_generator_template.py
to_type
def to_type(type_string, variable_name) -> Type: """ Returns a :class:`Type` object of a given type name. Lookup is done via :var:`code_generator_settings.CLASS_TYPE_PATHS` :param type_string: The type as string. E.g "bool". Need to be valid python. :param variable_name: Only for logging, if an unrecognized type is found. :return: a :class:`Type` instance :rtype: Type """ # type_string = type_string.strip() # remove "list of " and set .is_list accordingly. # is_list, type_string = can_strip_prefix(type_string, "list of ") # var_type = Type(string=type_string, is_list=is_list) var_type = Type(type_string) # remove "list of " and set .is_list accordingly. is_list = True while is_list: is_list, var_type.string = can_strip_prefix(var_type.string, "list of ") if is_list: var_type.is_list += 1 # end if # end for if var_type.string == "True": var_type.string = "bool" var_type.always_is_value = "True" # end if if var_type.string in ["int", "bool", "float", "object", "None", "str"]: var_type.is_builtin = True elif var_type.string == "unicode_type": var_type.string = "unicode_type" var_type.is_builtin = False var_type.import_path = "luckydonaldUtils.encoding" var_type.description = "py2: unicode, py3: str" elif var_type.string in CLASS_TYPE_PATHS: var_type.import_path = CLASS_TYPE_PATHS[var_type.string][CLASS_TYPE_PATHS__IMPORT].rstrip(".") var_type.is_builtin = False else: logger.warn( "Added unrecognized type in param <{var}>: {type!r}".format(var=variable_name, type=var_type.string)) # end if return var_type
python
def to_type(type_string, variable_name) -> Type: """ Returns a :class:`Type` object of a given type name. Lookup is done via :var:`code_generator_settings.CLASS_TYPE_PATHS` :param type_string: The type as string. E.g "bool". Need to be valid python. :param variable_name: Only for logging, if an unrecognized type is found. :return: a :class:`Type` instance :rtype: Type """ # type_string = type_string.strip() # remove "list of " and set .is_list accordingly. # is_list, type_string = can_strip_prefix(type_string, "list of ") # var_type = Type(string=type_string, is_list=is_list) var_type = Type(type_string) # remove "list of " and set .is_list accordingly. is_list = True while is_list: is_list, var_type.string = can_strip_prefix(var_type.string, "list of ") if is_list: var_type.is_list += 1 # end if # end for if var_type.string == "True": var_type.string = "bool" var_type.always_is_value = "True" # end if if var_type.string in ["int", "bool", "float", "object", "None", "str"]: var_type.is_builtin = True elif var_type.string == "unicode_type": var_type.string = "unicode_type" var_type.is_builtin = False var_type.import_path = "luckydonaldUtils.encoding" var_type.description = "py2: unicode, py3: str" elif var_type.string in CLASS_TYPE_PATHS: var_type.import_path = CLASS_TYPE_PATHS[var_type.string][CLASS_TYPE_PATHS__IMPORT].rstrip(".") var_type.is_builtin = False else: logger.warn( "Added unrecognized type in param <{var}>: {type!r}".format(var=variable_name, type=var_type.string)) # end if return var_type
Returns a :class:`Type` object of a given type name. Lookup is done via :var:`code_generator_settings.CLASS_TYPE_PATHS` :param type_string: The type as string. E.g "bool". Need to be valid python. :param variable_name: Only for logging, if an unrecognized type is found. :return: a :class:`Type` instance :rtype: Type
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator_template.py#L649-L690
luckydonald/pytgbot
code_generation/code_generator_template.py
can_strip_prefix
def can_strip_prefix(text:str, prefix:str) -> (bool, str): """ If the given text starts with the given prefix, True and the text without that prefix is returned. Else False and the original text is returned. Note: the text always is stripped, before returning. :param text: :param prefix: :return: (bool, str) :class:`bool` whether he text started with given prefix, :class:`str` the text without prefix """ if text.startswith(prefix): return True, text[len(prefix):].strip() return False, text.strip()
python
def can_strip_prefix(text:str, prefix:str) -> (bool, str): """ If the given text starts with the given prefix, True and the text without that prefix is returned. Else False and the original text is returned. Note: the text always is stripped, before returning. :param text: :param prefix: :return: (bool, str) :class:`bool` whether he text started with given prefix, :class:`str` the text without prefix """ if text.startswith(prefix): return True, text[len(prefix):].strip() return False, text.strip()
If the given text starts with the given prefix, True and the text without that prefix is returned. Else False and the original text is returned. Note: the text always is stripped, before returning. :param text: :param prefix: :return: (bool, str) :class:`bool` whether he text started with given prefix, :class:`str` the text without prefix
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator_template.py#L694-L707
luckydonald/pytgbot
code_generation/code_generator_template.py
Function.class_name
def class_name(self) -> str: """ Makes the fist letter big, keep the rest of the camelCaseApiName. """ if not self.api_name: # empty string return self.api_name # end if return self.api_name[0].upper() + self.api_name[1:]
python
def class_name(self) -> str: """ Makes the fist letter big, keep the rest of the camelCaseApiName. """ if not self.api_name: # empty string return self.api_name # end if return self.api_name[0].upper() + self.api_name[1:]
Makes the fist letter big, keep the rest of the camelCaseApiName.
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator_template.py#L224-L231
luckydonald/pytgbot
code_generation/code_generator_template.py
Function.class_name_teleflask_message
def class_name_teleflask_message(self) -> str: """ If it starts with `Send` remove that. """ # strip leading "Send" name = self.class_name # "sendPhoto" -> "SendPhoto" name = name[4:] if name.startswith('Send') else name # "SendPhoto" -> "Photo" name = name + "Message" # "Photo" -> "PhotoMessage" # e.g. "MessageMessage" will be replaced as "TextMessage" # b/c "sendMessage" -> "SendMessage" -> "Message" -> "MessageMessage" ==> "TextMessage" if name in MESSAGE_CLASS_OVERRIDES: return MESSAGE_CLASS_OVERRIDES[name] # end if return name
python
def class_name_teleflask_message(self) -> str: """ If it starts with `Send` remove that. """ # strip leading "Send" name = self.class_name # "sendPhoto" -> "SendPhoto" name = name[4:] if name.startswith('Send') else name # "SendPhoto" -> "Photo" name = name + "Message" # "Photo" -> "PhotoMessage" # e.g. "MessageMessage" will be replaced as "TextMessage" # b/c "sendMessage" -> "SendMessage" -> "Message" -> "MessageMessage" ==> "TextMessage" if name in MESSAGE_CLASS_OVERRIDES: return MESSAGE_CLASS_OVERRIDES[name] # end if return name
If it starts with `Send` remove that.
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator_template.py#L235-L249
luckydonald/pytgbot
code_generation/code_generator_template.py
Import.full
def full(self): """ self.path + "." + self.name """ if self.path: if self.name: return self.path + "." + self.name else: return self.path # end if else: if self.name: return self.name else: return ""
python
def full(self): """ self.path + "." + self.name """ if self.path: if self.name: return self.path + "." + self.name else: return self.path # end if else: if self.name: return self.name else: return ""
self.path + "." + self.name
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator_template.py#L479-L491
luckydonald/pytgbot
pytgbot/api_types/__init__.py
from_array_list
def from_array_list(required_type, result, list_level, is_builtin): """ Tries to parse the `result` as type given in `required_type`, while traversing into lists as often as specified in `list_level`. :param required_type: What it should be parsed as :type required_type: class :param result: The result to parse :param list_level: "list of" * list_level :type list_level: int :param is_builtin: if it is a builtin python type like :class:`int`, :class:`bool`, etc. :type is_builtin: bool :return: the result as `required_type` type """ logger.debug("Trying parsing as {type}, list_level={list_level}, is_builtin={is_builtin}".format( type=required_type.__name__, list_level=list_level, is_builtin=is_builtin )) if list_level > 0: assert isinstance(result, (list, tuple)) return [from_array_list(required_type, obj, list_level-1, is_builtin) for obj in result] # end if if is_builtin: if isinstance(result, required_type): logger.debug("Already is correct type.") return required_type(result) elif isinstance(required_type, unicode_type): # handle str, so emojis work for py2. return u(result) else: import ast logger.warn("Trying parsing with ast.literal_eval()...") return ast.literal_eval(str(result)) # raises ValueError if it could not parse # end if else: return required_type.from_array(result)
python
def from_array_list(required_type, result, list_level, is_builtin): """ Tries to parse the `result` as type given in `required_type`, while traversing into lists as often as specified in `list_level`. :param required_type: What it should be parsed as :type required_type: class :param result: The result to parse :param list_level: "list of" * list_level :type list_level: int :param is_builtin: if it is a builtin python type like :class:`int`, :class:`bool`, etc. :type is_builtin: bool :return: the result as `required_type` type """ logger.debug("Trying parsing as {type}, list_level={list_level}, is_builtin={is_builtin}".format( type=required_type.__name__, list_level=list_level, is_builtin=is_builtin )) if list_level > 0: assert isinstance(result, (list, tuple)) return [from_array_list(required_type, obj, list_level-1, is_builtin) for obj in result] # end if if is_builtin: if isinstance(result, required_type): logger.debug("Already is correct type.") return required_type(result) elif isinstance(required_type, unicode_type): # handle str, so emojis work for py2. return u(result) else: import ast logger.warn("Trying parsing with ast.literal_eval()...") return ast.literal_eval(str(result)) # raises ValueError if it could not parse # end if else: return required_type.from_array(result)
Tries to parse the `result` as type given in `required_type`, while traversing into lists as often as specified in `list_level`. :param required_type: What it should be parsed as :type required_type: class :param result: The result to parse :param list_level: "list of" * list_level :type list_level: int :param is_builtin: if it is a builtin python type like :class:`int`, :class:`bool`, etc. :type is_builtin: bool :return: the result as `required_type` type
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/__init__.py#L94-L130
luckydonald/pytgbot
pytgbot/api_types/__init__.py
as_array
def as_array(obj): """ Creates an json-like representation of a variable, supporting types with a `.to_array()` function. :rtype: dict|list|str|int|float|bool|None """ if hasattr(obj, "to_array"): return obj.to_array() elif isinstance(obj, (list, tuple)): return [as_array(x) for x in obj] elif isinstance(obj, dict): return {key:as_array(obj[key]) for key in obj.keys()} else: _json_dumps(obj) # raises error if is wrong json return obj
python
def as_array(obj): """ Creates an json-like representation of a variable, supporting types with a `.to_array()` function. :rtype: dict|list|str|int|float|bool|None """ if hasattr(obj, "to_array"): return obj.to_array() elif isinstance(obj, (list, tuple)): return [as_array(x) for x in obj] elif isinstance(obj, dict): return {key:as_array(obj[key]) for key in obj.keys()} else: _json_dumps(obj) # raises error if is wrong json return obj
Creates an json-like representation of a variable, supporting types with a `.to_array()` function. :rtype: dict|list|str|int|float|bool|None
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/__init__.py#L135-L149
luckydonald/pytgbot
pytgbot/api_types/__init__.py
TgBotApiObject.from_array_list
def from_array_list(cls, result, list_level): """ Tries to parse the `result` as type given in `required_type`, while traversing into lists as often as specified in `list_level`. :param cls: Type as what it should be parsed as. Can be any class extending :class:`TgBotApiObject`. E.g. If you call `Class.from_array_list`, it will automatically be set to `Class`. :type cls: class :param result: The result to parse :param list_level: "list of" * list_level :type list_level: int :return: the result as `required_type` type """ return from_array_list(cls, result, list_level, is_builtin=False)
python
def from_array_list(cls, result, list_level): """ Tries to parse the `result` as type given in `required_type`, while traversing into lists as often as specified in `list_level`. :param cls: Type as what it should be parsed as. Can be any class extending :class:`TgBotApiObject`. E.g. If you call `Class.from_array_list`, it will automatically be set to `Class`. :type cls: class :param result: The result to parse :param list_level: "list of" * list_level :type list_level: int :return: the result as `required_type` type """ return from_array_list(cls, result, list_level, is_builtin=False)
Tries to parse the `result` as type given in `required_type`, while traversing into lists as often as specified in `list_level`. :param cls: Type as what it should be parsed as. Can be any class extending :class:`TgBotApiObject`. E.g. If you call `Class.from_array_list`, it will automatically be set to `Class`. :type cls: class :param result: The result to parse :param list_level: "list of" * list_level :type list_level: int :return: the result as `required_type` type
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/__init__.py#L36-L51
luckydonald/pytgbot
pytgbot/api_types/__init__.py
TgBotApiObject._builtin_from_array_list
def _builtin_from_array_list(required_type, value, list_level): """ Helper method to make :func:`from_array_list` available to all classes extending this, without the need for additional imports. :param required_type: Type as what it should be parsed as. Any builtin. :param value: The result to parse :param list_level: "list of" * list_level :return: """ return from_array_list(required_type, value, list_level, is_builtin=True)
python
def _builtin_from_array_list(required_type, value, list_level): """ Helper method to make :func:`from_array_list` available to all classes extending this, without the need for additional imports. :param required_type: Type as what it should be parsed as. Any builtin. :param value: The result to parse :param list_level: "list of" * list_level :return: """ return from_array_list(required_type, value, list_level, is_builtin=True)
Helper method to make :func:`from_array_list` available to all classes extending this, without the need for additional imports. :param required_type: Type as what it should be parsed as. Any builtin. :param value: The result to parse :param list_level: "list of" * list_level :return:
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/__init__.py#L55-L65
luckydonald/pytgbot
pytgbot/extra/bot_response.py
ResponseBot.do
def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query): """ Return the request params we would send to the api. """ url, params = self._prepare_request(command, query) return { "url": url, "params": params, "files": files, "stream": use_long_polling, "verify": True, # No self signed certificates. Telegram should be trustworthy anyway... "timeout": request_timeout }
python
def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query): """ Return the request params we would send to the api. """ url, params = self._prepare_request(command, query) return { "url": url, "params": params, "files": files, "stream": use_long_polling, "verify": True, # No self signed certificates. Telegram should be trustworthy anyway... "timeout": request_timeout }
Return the request params we would send to the api.
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/extra/bot_response.py#L20-L29
luckydonald/pytgbot
pytgbot/api_types/receivable/updates.py
Update.to_array
def to_array(self): """ Serializes this Update to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Update, self).to_array() array['update_id'] = int(self.update_id) # type int if self.message is not None: array['message'] = self.message.to_array() # type Message if self.edited_message is not None: array['edited_message'] = self.edited_message.to_array() # type Message if self.channel_post is not None: array['channel_post'] = self.channel_post.to_array() # type Message if self.edited_channel_post is not None: array['edited_channel_post'] = self.edited_channel_post.to_array() # type Message if self.inline_query is not None: array['inline_query'] = self.inline_query.to_array() # type InlineQuery if self.chosen_inline_result is not None: array['chosen_inline_result'] = self.chosen_inline_result.to_array() # type ChosenInlineResult if self.callback_query is not None: array['callback_query'] = self.callback_query.to_array() # type CallbackQuery if self.shipping_query is not None: array['shipping_query'] = self.shipping_query.to_array() # type ShippingQuery if self.pre_checkout_query is not None: array['pre_checkout_query'] = self.pre_checkout_query.to_array() # type PreCheckoutQuery return array
python
def to_array(self): """ Serializes this Update to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Update, self).to_array() array['update_id'] = int(self.update_id) # type int if self.message is not None: array['message'] = self.message.to_array() # type Message if self.edited_message is not None: array['edited_message'] = self.edited_message.to_array() # type Message if self.channel_post is not None: array['channel_post'] = self.channel_post.to_array() # type Message if self.edited_channel_post is not None: array['edited_channel_post'] = self.edited_channel_post.to_array() # type Message if self.inline_query is not None: array['inline_query'] = self.inline_query.to_array() # type InlineQuery if self.chosen_inline_result is not None: array['chosen_inline_result'] = self.chosen_inline_result.to_array() # type ChosenInlineResult if self.callback_query is not None: array['callback_query'] = self.callback_query.to_array() # type CallbackQuery if self.shipping_query is not None: array['shipping_query'] = self.shipping_query.to_array() # type ShippingQuery if self.pre_checkout_query is not None: array['pre_checkout_query'] = self.pre_checkout_query.to_array() # type PreCheckoutQuery return array
Serializes this Update to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L149-L176
luckydonald/pytgbot
pytgbot/api_types/receivable/updates.py
WebhookInfo.to_array
def to_array(self): """ Serializes this WebhookInfo to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(WebhookInfo, self).to_array() array['url'] = u(self.url) # py2: type unicode, py3: type str array['has_custom_certificate'] = bool(self.has_custom_certificate) # type bool array['pending_update_count'] = int(self.pending_update_count) # type int if self.last_error_date is not None: array['last_error_date'] = int(self.last_error_date) # type int if self.last_error_message is not None: array['last_error_message'] = u(self.last_error_message) # py2: type unicode, py3: type str if self.max_connections is not None: array['max_connections'] = int(self.max_connections) # type int if self.allowed_updates is not None: array['allowed_updates'] = self._as_array(self.allowed_updates) # type list of str return array
python
def to_array(self): """ Serializes this WebhookInfo to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(WebhookInfo, self).to_array() array['url'] = u(self.url) # py2: type unicode, py3: type str array['has_custom_certificate'] = bool(self.has_custom_certificate) # type bool array['pending_update_count'] = int(self.pending_update_count) # type int if self.last_error_date is not None: array['last_error_date'] = int(self.last_error_date) # type int if self.last_error_message is not None: array['last_error_message'] = u(self.last_error_message) # py2: type unicode, py3: type str if self.max_connections is not None: array['max_connections'] = int(self.max_connections) # type int if self.allowed_updates is not None: array['allowed_updates'] = self._as_array(self.allowed_updates) # type list of str return array
Serializes this WebhookInfo to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L334-L353
luckydonald/pytgbot
pytgbot/api_types/receivable/updates.py
WebhookInfo.from_array
def from_array(array): """ Deserialize a new WebhookInfo from a given dictionary. :return: new WebhookInfo instance. :rtype: WebhookInfo """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['url'] = u(array.get('url')) data['has_custom_certificate'] = bool(array.get('has_custom_certificate')) data['pending_update_count'] = int(array.get('pending_update_count')) data['last_error_date'] = int(array.get('last_error_date')) if array.get('last_error_date') is not None else None data['last_error_message'] = u(array.get('last_error_message')) if array.get('last_error_message') is not None else None data['max_connections'] = int(array.get('max_connections')) if array.get('max_connections') is not None else None data['allowed_updates'] = WebhookInfo._builtin_from_array_list(required_type=unicode_type, value=array.get('allowed_updates'), list_level=1) if array.get('allowed_updates') is not None else None data['_raw'] = array return WebhookInfo(**data)
python
def from_array(array): """ Deserialize a new WebhookInfo from a given dictionary. :return: new WebhookInfo instance. :rtype: WebhookInfo """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['url'] = u(array.get('url')) data['has_custom_certificate'] = bool(array.get('has_custom_certificate')) data['pending_update_count'] = int(array.get('pending_update_count')) data['last_error_date'] = int(array.get('last_error_date')) if array.get('last_error_date') is not None else None data['last_error_message'] = u(array.get('last_error_message')) if array.get('last_error_message') is not None else None data['max_connections'] = int(array.get('max_connections')) if array.get('max_connections') is not None else None data['allowed_updates'] = WebhookInfo._builtin_from_array_list(required_type=unicode_type, value=array.get('allowed_updates'), list_level=1) if array.get('allowed_updates') is not None else None data['_raw'] = array return WebhookInfo(**data)
Deserialize a new WebhookInfo from a given dictionary. :return: new WebhookInfo instance. :rtype: WebhookInfo
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L357-L378
luckydonald/pytgbot
pytgbot/api_types/receivable/updates.py
Message.to_array
def to_array(self): """ Serializes this Message to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Message, self).to_array() array['message_id'] = int(self.message_id) # type int array['date'] = int(self.date) # type int array['chat'] = self.chat.to_array() # type Chat if self.from_peer is not None: array['from'] = self.from_peer.to_array() # type User if self.forward_from is not None: array['forward_from'] = self.forward_from.to_array() # type User if self.forward_from_chat is not None: array['forward_from_chat'] = self.forward_from_chat.to_array() # type Chat if self.forward_from_message_id is not None: array['forward_from_message_id'] = int(self.forward_from_message_id) # type int if self.forward_signature is not None: array['forward_signature'] = u(self.forward_signature) # py2: type unicode, py3: type str if self.forward_date is not None: array['forward_date'] = int(self.forward_date) # type int if self.reply_to_message is not None: array['reply_to_message'] = self.reply_to_message.to_array() # type Message if self.edit_date is not None: array['edit_date'] = int(self.edit_date) # type int if self.media_group_id is not None: array['media_group_id'] = u(self.media_group_id) # py2: type unicode, py3: type str if self.author_signature is not None: array['author_signature'] = u(self.author_signature) # py2: type unicode, py3: type str if self.text is not None: array['text'] = u(self.text) # py2: type unicode, py3: type str if self.entities is not None: array['entities'] = self._as_array(self.entities) # type list of MessageEntity if self.caption_entities is not None: array['caption_entities'] = self._as_array(self.caption_entities) # type list of MessageEntity if self.audio is not None: array['audio'] = self.audio.to_array() # type Audio if self.document is not None: array['document'] = self.document.to_array() # type Document if self.animation is not None: array['animation'] = self.animation.to_array() # type Animation if self.game is not None: array['game'] = self.game.to_array() # type Game if self.photo is not None: array['photo'] = self._as_array(self.photo) # type list of PhotoSize if self.sticker is not None: array['sticker'] = self.sticker.to_array() # type Sticker if self.video is not None: array['video'] = self.video.to_array() # type Video if self.voice is not None: array['voice'] = self.voice.to_array() # type Voice if self.video_note is not None: array['video_note'] = self.video_note.to_array() # type VideoNote if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.contact is not None: array['contact'] = self.contact.to_array() # type Contact if self.location is not None: array['location'] = self.location.to_array() # type Location if self.venue is not None: array['venue'] = self.venue.to_array() # type Venue if self.new_chat_members is not None: array['new_chat_members'] = self._as_array(self.new_chat_members) # type list of User if self.left_chat_member is not None: array['left_chat_member'] = self.left_chat_member.to_array() # type User if self.new_chat_title is not None: array['new_chat_title'] = u(self.new_chat_title) # py2: type unicode, py3: type str if self.new_chat_photo is not None: array['new_chat_photo'] = self._as_array(self.new_chat_photo) # type list of PhotoSize if self.delete_chat_photo is not None: array['delete_chat_photo'] = bool(self.delete_chat_photo) # type bool if self.group_chat_created is not None: array['group_chat_created'] = bool(self.group_chat_created) # type bool if self.supergroup_chat_created is not None: array['supergroup_chat_created'] = bool(self.supergroup_chat_created) # type bool if self.channel_chat_created is not None: array['channel_chat_created'] = bool(self.channel_chat_created) # type bool if self.migrate_to_chat_id is not None: array['migrate_to_chat_id'] = int(self.migrate_to_chat_id) # type int if self.migrate_from_chat_id is not None: array['migrate_from_chat_id'] = int(self.migrate_from_chat_id) # type int if self.pinned_message is not None: array['pinned_message'] = self.pinned_message.to_array() # type Message if self.invoice is not None: array['invoice'] = self.invoice.to_array() # type Invoice if self.successful_payment is not None: array['successful_payment'] = self.successful_payment.to_array() # type SuccessfulPayment if self.connected_website is not None: array['connected_website'] = u(self.connected_website) # py2: type unicode, py3: type str if self.passport_data is not None: array['passport_data'] = self.passport_data.to_array() # type PassportData return array
python
def to_array(self): """ Serializes this Message to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Message, self).to_array() array['message_id'] = int(self.message_id) # type int array['date'] = int(self.date) # type int array['chat'] = self.chat.to_array() # type Chat if self.from_peer is not None: array['from'] = self.from_peer.to_array() # type User if self.forward_from is not None: array['forward_from'] = self.forward_from.to_array() # type User if self.forward_from_chat is not None: array['forward_from_chat'] = self.forward_from_chat.to_array() # type Chat if self.forward_from_message_id is not None: array['forward_from_message_id'] = int(self.forward_from_message_id) # type int if self.forward_signature is not None: array['forward_signature'] = u(self.forward_signature) # py2: type unicode, py3: type str if self.forward_date is not None: array['forward_date'] = int(self.forward_date) # type int if self.reply_to_message is not None: array['reply_to_message'] = self.reply_to_message.to_array() # type Message if self.edit_date is not None: array['edit_date'] = int(self.edit_date) # type int if self.media_group_id is not None: array['media_group_id'] = u(self.media_group_id) # py2: type unicode, py3: type str if self.author_signature is not None: array['author_signature'] = u(self.author_signature) # py2: type unicode, py3: type str if self.text is not None: array['text'] = u(self.text) # py2: type unicode, py3: type str if self.entities is not None: array['entities'] = self._as_array(self.entities) # type list of MessageEntity if self.caption_entities is not None: array['caption_entities'] = self._as_array(self.caption_entities) # type list of MessageEntity if self.audio is not None: array['audio'] = self.audio.to_array() # type Audio if self.document is not None: array['document'] = self.document.to_array() # type Document if self.animation is not None: array['animation'] = self.animation.to_array() # type Animation if self.game is not None: array['game'] = self.game.to_array() # type Game if self.photo is not None: array['photo'] = self._as_array(self.photo) # type list of PhotoSize if self.sticker is not None: array['sticker'] = self.sticker.to_array() # type Sticker if self.video is not None: array['video'] = self.video.to_array() # type Video if self.voice is not None: array['voice'] = self.voice.to_array() # type Voice if self.video_note is not None: array['video_note'] = self.video_note.to_array() # type VideoNote if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.contact is not None: array['contact'] = self.contact.to_array() # type Contact if self.location is not None: array['location'] = self.location.to_array() # type Location if self.venue is not None: array['venue'] = self.venue.to_array() # type Venue if self.new_chat_members is not None: array['new_chat_members'] = self._as_array(self.new_chat_members) # type list of User if self.left_chat_member is not None: array['left_chat_member'] = self.left_chat_member.to_array() # type User if self.new_chat_title is not None: array['new_chat_title'] = u(self.new_chat_title) # py2: type unicode, py3: type str if self.new_chat_photo is not None: array['new_chat_photo'] = self._as_array(self.new_chat_photo) # type list of PhotoSize if self.delete_chat_photo is not None: array['delete_chat_photo'] = bool(self.delete_chat_photo) # type bool if self.group_chat_created is not None: array['group_chat_created'] = bool(self.group_chat_created) # type bool if self.supergroup_chat_created is not None: array['supergroup_chat_created'] = bool(self.supergroup_chat_created) # type bool if self.channel_chat_created is not None: array['channel_chat_created'] = bool(self.channel_chat_created) # type bool if self.migrate_to_chat_id is not None: array['migrate_to_chat_id'] = int(self.migrate_to_chat_id) # type int if self.migrate_from_chat_id is not None: array['migrate_from_chat_id'] = int(self.migrate_from_chat_id) # type int if self.pinned_message is not None: array['pinned_message'] = self.pinned_message.to_array() # type Message if self.invoice is not None: array['invoice'] = self.invoice.to_array() # type Invoice if self.successful_payment is not None: array['successful_payment'] = self.successful_payment.to_array() # type SuccessfulPayment if self.connected_website is not None: array['connected_website'] = u(self.connected_website) # py2: type unicode, py3: type str if self.passport_data is not None: array['passport_data'] = self.passport_data.to_array() # type PassportData return array
Serializes this Message to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L845-L938
luckydonald/pytgbot
pytgbot/api_types/receivable/updates.py
Message.from_array
def from_array(array): """ Deserialize a new Message from a given dictionary. :return: new Message instance. :rtype: Message """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from ..receivable.peer import User, Chat from ..receivable.media import Animation, Audio, Contact, Document, Game, Location, MessageEntity, PhotoSize from ..receivable.media import Sticker, Venue, Video, VideoNote, Voice from ..receivable.payments import Invoice, SuccessfulPayment from ..receivable.passport import PassportData data = {} data['message_id'] = int(array.get('message_id')) data['date'] = int(array.get('date')) data['chat'] = Chat.from_array(array.get('chat')) data['from_peer'] = User.from_array(array.get('from')) if array.get('from') is not None else None data['forward_from'] = User.from_array(array.get('forward_from')) if array.get('forward_from') is not None else None data['forward_from_chat'] = Chat.from_array(array.get('forward_from_chat')) if array.get('forward_from_chat') is not None else None data['forward_from_message_id'] = int(array.get('forward_from_message_id')) if array.get('forward_from_message_id') is not None else None data['forward_signature'] = u(array.get('forward_signature')) if array.get('forward_signature') is not None else None data['forward_date'] = int(array.get('forward_date')) if array.get('forward_date') is not None else None data['reply_to_message'] = Message.from_array(array.get('reply_to_message')) if array.get('reply_to_message') is not None else None data['edit_date'] = int(array.get('edit_date')) if array.get('edit_date') is not None else None data['media_group_id'] = u(array.get('media_group_id')) if array.get('media_group_id') is not None else None data['author_signature'] = u(array.get('author_signature')) if array.get('author_signature') is not None else None data['text'] = u(array.get('text')) if array.get('text') is not None else None data['entities'] = MessageEntity.from_array_list(array.get('entities'), list_level=1) if array.get('entities') is not None else None data['caption_entities'] = MessageEntity.from_array_list(array.get('caption_entities'), list_level=1) if array.get('caption_entities') is not None else None data['audio'] = Audio.from_array(array.get('audio')) if array.get('audio') is not None else None data['document'] = Document.from_array(array.get('document')) if array.get('document') is not None else None data['animation'] = Animation.from_array(array.get('animation')) if array.get('animation') is not None else None data['game'] = Game.from_array(array.get('game')) if array.get('game') is not None else None data['photo'] = PhotoSize.from_array_list(array.get('photo'), list_level=1) if array.get('photo') is not None else None data['sticker'] = Sticker.from_array(array.get('sticker')) if array.get('sticker') is not None else None data['video'] = Video.from_array(array.get('video')) if array.get('video') is not None else None data['voice'] = Voice.from_array(array.get('voice')) if array.get('voice') is not None else None data['video_note'] = VideoNote.from_array(array.get('video_note')) if array.get('video_note') is not None else None data['caption'] = u(array.get('caption')) if array.get('caption') is not None else None data['contact'] = Contact.from_array(array.get('contact')) if array.get('contact') is not None else None data['location'] = Location.from_array(array.get('location')) if array.get('location') is not None else None data['venue'] = Venue.from_array(array.get('venue')) if array.get('venue') is not None else None data['new_chat_members'] = User.from_array_list(array.get('new_chat_members'), list_level=1) if array.get('new_chat_members') is not None else None data['left_chat_member'] = User.from_array(array.get('left_chat_member')) if array.get('left_chat_member') is not None else None data['new_chat_title'] = u(array.get('new_chat_title')) if array.get('new_chat_title') is not None else None data['new_chat_photo'] = PhotoSize.from_array_list(array.get('new_chat_photo'), list_level=1) if array.get('new_chat_photo') is not None else None data['delete_chat_photo'] = bool(array.get('delete_chat_photo')) if array.get('delete_chat_photo') is not None else None data['group_chat_created'] = bool(array.get('group_chat_created')) if array.get('group_chat_created') is not None else None data['supergroup_chat_created'] = bool(array.get('supergroup_chat_created')) if array.get('supergroup_chat_created') is not None else None data['channel_chat_created'] = bool(array.get('channel_chat_created')) if array.get('channel_chat_created') is not None else None data['migrate_to_chat_id'] = int(array.get('migrate_to_chat_id')) if array.get('migrate_to_chat_id') is not None else None data['migrate_from_chat_id'] = int(array.get('migrate_from_chat_id')) if array.get('migrate_from_chat_id') is not None else None data['pinned_message'] = Message.from_array(array.get('pinned_message')) if array.get('pinned_message') is not None else None data['invoice'] = Invoice.from_array(array.get('invoice')) if array.get('invoice') is not None else None data['successful_payment'] = SuccessfulPayment.from_array(array.get('successful_payment')) if array.get('successful_payment') is not None else None data['connected_website'] = u(array.get('connected_website')) if array.get('connected_website') is not None else None data['passport_data'] = PassportData.from_array(array.get('passport_data')) if array.get('passport_data') is not None else None data['_raw'] = array return Message(**data)
python
def from_array(array): """ Deserialize a new Message from a given dictionary. :return: new Message instance. :rtype: Message """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from ..receivable.peer import User, Chat from ..receivable.media import Animation, Audio, Contact, Document, Game, Location, MessageEntity, PhotoSize from ..receivable.media import Sticker, Venue, Video, VideoNote, Voice from ..receivable.payments import Invoice, SuccessfulPayment from ..receivable.passport import PassportData data = {} data['message_id'] = int(array.get('message_id')) data['date'] = int(array.get('date')) data['chat'] = Chat.from_array(array.get('chat')) data['from_peer'] = User.from_array(array.get('from')) if array.get('from') is not None else None data['forward_from'] = User.from_array(array.get('forward_from')) if array.get('forward_from') is not None else None data['forward_from_chat'] = Chat.from_array(array.get('forward_from_chat')) if array.get('forward_from_chat') is not None else None data['forward_from_message_id'] = int(array.get('forward_from_message_id')) if array.get('forward_from_message_id') is not None else None data['forward_signature'] = u(array.get('forward_signature')) if array.get('forward_signature') is not None else None data['forward_date'] = int(array.get('forward_date')) if array.get('forward_date') is not None else None data['reply_to_message'] = Message.from_array(array.get('reply_to_message')) if array.get('reply_to_message') is not None else None data['edit_date'] = int(array.get('edit_date')) if array.get('edit_date') is not None else None data['media_group_id'] = u(array.get('media_group_id')) if array.get('media_group_id') is not None else None data['author_signature'] = u(array.get('author_signature')) if array.get('author_signature') is not None else None data['text'] = u(array.get('text')) if array.get('text') is not None else None data['entities'] = MessageEntity.from_array_list(array.get('entities'), list_level=1) if array.get('entities') is not None else None data['caption_entities'] = MessageEntity.from_array_list(array.get('caption_entities'), list_level=1) if array.get('caption_entities') is not None else None data['audio'] = Audio.from_array(array.get('audio')) if array.get('audio') is not None else None data['document'] = Document.from_array(array.get('document')) if array.get('document') is not None else None data['animation'] = Animation.from_array(array.get('animation')) if array.get('animation') is not None else None data['game'] = Game.from_array(array.get('game')) if array.get('game') is not None else None data['photo'] = PhotoSize.from_array_list(array.get('photo'), list_level=1) if array.get('photo') is not None else None data['sticker'] = Sticker.from_array(array.get('sticker')) if array.get('sticker') is not None else None data['video'] = Video.from_array(array.get('video')) if array.get('video') is not None else None data['voice'] = Voice.from_array(array.get('voice')) if array.get('voice') is not None else None data['video_note'] = VideoNote.from_array(array.get('video_note')) if array.get('video_note') is not None else None data['caption'] = u(array.get('caption')) if array.get('caption') is not None else None data['contact'] = Contact.from_array(array.get('contact')) if array.get('contact') is not None else None data['location'] = Location.from_array(array.get('location')) if array.get('location') is not None else None data['venue'] = Venue.from_array(array.get('venue')) if array.get('venue') is not None else None data['new_chat_members'] = User.from_array_list(array.get('new_chat_members'), list_level=1) if array.get('new_chat_members') is not None else None data['left_chat_member'] = User.from_array(array.get('left_chat_member')) if array.get('left_chat_member') is not None else None data['new_chat_title'] = u(array.get('new_chat_title')) if array.get('new_chat_title') is not None else None data['new_chat_photo'] = PhotoSize.from_array_list(array.get('new_chat_photo'), list_level=1) if array.get('new_chat_photo') is not None else None data['delete_chat_photo'] = bool(array.get('delete_chat_photo')) if array.get('delete_chat_photo') is not None else None data['group_chat_created'] = bool(array.get('group_chat_created')) if array.get('group_chat_created') is not None else None data['supergroup_chat_created'] = bool(array.get('supergroup_chat_created')) if array.get('supergroup_chat_created') is not None else None data['channel_chat_created'] = bool(array.get('channel_chat_created')) if array.get('channel_chat_created') is not None else None data['migrate_to_chat_id'] = int(array.get('migrate_to_chat_id')) if array.get('migrate_to_chat_id') is not None else None data['migrate_from_chat_id'] = int(array.get('migrate_from_chat_id')) if array.get('migrate_from_chat_id') is not None else None data['pinned_message'] = Message.from_array(array.get('pinned_message')) if array.get('pinned_message') is not None else None data['invoice'] = Invoice.from_array(array.get('invoice')) if array.get('invoice') is not None else None data['successful_payment'] = SuccessfulPayment.from_array(array.get('successful_payment')) if array.get('successful_payment') is not None else None data['connected_website'] = u(array.get('connected_website')) if array.get('connected_website') is not None else None data['passport_data'] = PassportData.from_array(array.get('passport_data')) if array.get('passport_data') is not None else None data['_raw'] = array return Message(**data)
Deserialize a new Message from a given dictionary. :return: new Message instance. :rtype: Message
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L942-L1006
luckydonald/pytgbot
pytgbot/api_types/receivable/updates.py
CallbackQuery.to_array
def to_array(self): """ Serializes this CallbackQuery to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(CallbackQuery, self).to_array() array['id'] = u(self.id) # py2: type unicode, py3: type str array['from'] = self.from_peer.to_array() # type User array['chat_instance'] = u(self.chat_instance) # py2: type unicode, py3: type str if self.message is not None: array['message'] = self.message.to_array() # type Message if self.inline_message_id is not None: array['inline_message_id'] = u(self.inline_message_id) # py2: type unicode, py3: type str if self.data is not None: array['data'] = u(self.data) # py2: type unicode, py3: type str if self.game_short_name is not None: array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str return array
python
def to_array(self): """ Serializes this CallbackQuery to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(CallbackQuery, self).to_array() array['id'] = u(self.id) # py2: type unicode, py3: type str array['from'] = self.from_peer.to_array() # type User array['chat_instance'] = u(self.chat_instance) # py2: type unicode, py3: type str if self.message is not None: array['message'] = self.message.to_array() # type Message if self.inline_message_id is not None: array['inline_message_id'] = u(self.inline_message_id) # py2: type unicode, py3: type str if self.data is not None: array['data'] = u(self.data) # py2: type unicode, py3: type str if self.game_short_name is not None: array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str return array
Serializes this CallbackQuery to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L1140-L1159
luckydonald/pytgbot
pytgbot/api_types/receivable/updates.py
CallbackQuery.from_array
def from_array(array): """ Deserialize a new CallbackQuery from a given dictionary. :return: new CallbackQuery instance. :rtype: CallbackQuery """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from ..receivable.peer import User data = {} data['id'] = u(array.get('id')) data['from_peer'] = User.from_array(array.get('from')) data['chat_instance'] = u(array.get('chat_instance')) data['message'] = Message.from_array(array.get('message')) if array.get('message') is not None else None data['inline_message_id'] = u(array.get('inline_message_id')) if array.get('inline_message_id') is not None else None data['data'] = u(array.get('data')) if array.get('data') is not None else None data['game_short_name'] = u(array.get('game_short_name')) if array.get('game_short_name') is not None else None data['_raw'] = array return CallbackQuery(**data)
python
def from_array(array): """ Deserialize a new CallbackQuery from a given dictionary. :return: new CallbackQuery instance. :rtype: CallbackQuery """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from ..receivable.peer import User data = {} data['id'] = u(array.get('id')) data['from_peer'] = User.from_array(array.get('from')) data['chat_instance'] = u(array.get('chat_instance')) data['message'] = Message.from_array(array.get('message')) if array.get('message') is not None else None data['inline_message_id'] = u(array.get('inline_message_id')) if array.get('inline_message_id') is not None else None data['data'] = u(array.get('data')) if array.get('data') is not None else None data['game_short_name'] = u(array.get('game_short_name')) if array.get('game_short_name') is not None else None data['_raw'] = array return CallbackQuery(**data)
Deserialize a new CallbackQuery from a given dictionary. :return: new CallbackQuery instance. :rtype: CallbackQuery
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L1163-L1186
luckydonald/pytgbot
pytgbot/api_types/receivable/updates.py
ResponseParameters.to_array
def to_array(self): """ Serializes this ResponseParameters to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ResponseParameters, self).to_array() if self.migrate_to_chat_id is not None: array['migrate_to_chat_id'] = int(self.migrate_to_chat_id) # type int if self.retry_after is not None: array['retry_after'] = int(self.retry_after) # type int return array
python
def to_array(self): """ Serializes this ResponseParameters to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ResponseParameters, self).to_array() if self.migrate_to_chat_id is not None: array['migrate_to_chat_id'] = int(self.migrate_to_chat_id) # type int if self.retry_after is not None: array['retry_after'] = int(self.retry_after) # type int return array
Serializes this ResponseParameters to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L1279-L1291
luckydonald/pytgbot
pytgbot/api_types/receivable/updates.py
ResponseParameters.from_array
def from_array(array): """ Deserialize a new ResponseParameters from a given dictionary. :return: new ResponseParameters instance. :rtype: ResponseParameters """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['migrate_to_chat_id'] = int(array.get('migrate_to_chat_id')) if array.get('migrate_to_chat_id') is not None else None data['retry_after'] = int(array.get('retry_after')) if array.get('retry_after') is not None else None data['_raw'] = array return ResponseParameters(**data)
python
def from_array(array): """ Deserialize a new ResponseParameters from a given dictionary. :return: new ResponseParameters instance. :rtype: ResponseParameters """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['migrate_to_chat_id'] = int(array.get('migrate_to_chat_id')) if array.get('migrate_to_chat_id') is not None else None data['retry_after'] = int(array.get('retry_after')) if array.get('retry_after') is not None else None data['_raw'] = array return ResponseParameters(**data)
Deserialize a new ResponseParameters from a given dictionary. :return: new ResponseParameters instance. :rtype: ResponseParameters
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/updates.py#L1295-L1311
delph-in/pydelphin
delphin/mrs/xmrs.py
Rmrs
def Rmrs(top=None, index=None, xarg=None, eps=None, args=None, hcons=None, icons=None, lnk=None, surface=None, identifier=None, vars=None): """ Construct an :class:`Xmrs` from RMRS components. Robust Minimal Recursion Semantics (RMRS) are like MRS, but all predications have a nodeid ("anchor"), and arguments are not contained by the source predications, but instead reference the nodeid of their predication. Args: top: the TOP (or maybe LTOP) variable index: the INDEX variable xarg: the XARG variable eps: an iterable of EPs args: a nested mapping of `{nodeid: {rargname: value}}` hcons: an iterable of HandleConstraint objects icons: an iterable of IndividualConstraint objects lnk: the Lnk object associating the MRS to the surface form surface: the surface string identifier: a discourse-utterance id vars: a mapping of variables to a list of `(property, value)` pairs Example: >>> m = Rmrs( >>> top='h0', >>> index='e2', >>> eps=[ElementaryPredication( >>> 10000, >>> Pred.surface('_rain_v_1_rel'), >>> 'h1' >>> )], >>> args={10000: {'ARG0': 'e2'}}, >>> hcons=[HandleConstraint('h0', 'qeq', 'h1'), >>> vars={'e2': {'SF': 'prop-or-ques', 'TENSE': 'present'}} >>> ) """ eps = list(eps or []) args = list(args or []) if vars is None: vars = {} for arg in args: if arg.nodeid is None: raise XmrsStructureError("RMRS args must have a nodeid.") # make the EPs more MRS-like (with arguments) for ep in eps: if ep.nodeid is None: raise XmrsStructureError("RMRS EPs must have a nodeid.") epargs = ep.args for rargname, value in args.get(ep.nodeid, {}).items(): epargs[rargname] = value hcons = list(hcons or []) icons = list(icons or []) return Xmrs(top=top, index=index, xarg=xarg, eps=eps, hcons=hcons, icons=icons, vars=vars, lnk=lnk, surface=surface, identifier=identifier)
python
def Rmrs(top=None, index=None, xarg=None, eps=None, args=None, hcons=None, icons=None, lnk=None, surface=None, identifier=None, vars=None): """ Construct an :class:`Xmrs` from RMRS components. Robust Minimal Recursion Semantics (RMRS) are like MRS, but all predications have a nodeid ("anchor"), and arguments are not contained by the source predications, but instead reference the nodeid of their predication. Args: top: the TOP (or maybe LTOP) variable index: the INDEX variable xarg: the XARG variable eps: an iterable of EPs args: a nested mapping of `{nodeid: {rargname: value}}` hcons: an iterable of HandleConstraint objects icons: an iterable of IndividualConstraint objects lnk: the Lnk object associating the MRS to the surface form surface: the surface string identifier: a discourse-utterance id vars: a mapping of variables to a list of `(property, value)` pairs Example: >>> m = Rmrs( >>> top='h0', >>> index='e2', >>> eps=[ElementaryPredication( >>> 10000, >>> Pred.surface('_rain_v_1_rel'), >>> 'h1' >>> )], >>> args={10000: {'ARG0': 'e2'}}, >>> hcons=[HandleConstraint('h0', 'qeq', 'h1'), >>> vars={'e2': {'SF': 'prop-or-ques', 'TENSE': 'present'}} >>> ) """ eps = list(eps or []) args = list(args or []) if vars is None: vars = {} for arg in args: if arg.nodeid is None: raise XmrsStructureError("RMRS args must have a nodeid.") # make the EPs more MRS-like (with arguments) for ep in eps: if ep.nodeid is None: raise XmrsStructureError("RMRS EPs must have a nodeid.") epargs = ep.args for rargname, value in args.get(ep.nodeid, {}).items(): epargs[rargname] = value hcons = list(hcons or []) icons = list(icons or []) return Xmrs(top=top, index=index, xarg=xarg, eps=eps, hcons=hcons, icons=icons, vars=vars, lnk=lnk, surface=surface, identifier=identifier)
Construct an :class:`Xmrs` from RMRS components. Robust Minimal Recursion Semantics (RMRS) are like MRS, but all predications have a nodeid ("anchor"), and arguments are not contained by the source predications, but instead reference the nodeid of their predication. Args: top: the TOP (or maybe LTOP) variable index: the INDEX variable xarg: the XARG variable eps: an iterable of EPs args: a nested mapping of `{nodeid: {rargname: value}}` hcons: an iterable of HandleConstraint objects icons: an iterable of IndividualConstraint objects lnk: the Lnk object associating the MRS to the surface form surface: the surface string identifier: a discourse-utterance id vars: a mapping of variables to a list of `(property, value)` pairs Example: >>> m = Rmrs( >>> top='h0', >>> index='e2', >>> eps=[ElementaryPredication( >>> 10000, >>> Pred.surface('_rain_v_1_rel'), >>> 'h1' >>> )], >>> args={10000: {'ARG0': 'e2'}}, >>> hcons=[HandleConstraint('h0', 'qeq', 'h1'), >>> vars={'e2': {'SF': 'prop-or-ques', 'TENSE': 'present'}} >>> )
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L853-L910
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.from_xmrs
def from_xmrs(cls, xmrs, **kwargs): """ Facilitate conversion among subclasses. Args: xmrs (:class:`Xmrs`): instance to convert from; possibly an instance of a subclass, such as :class:`Mrs` or :class:`Dmrs` **kwargs: additional keyword arguments that may be used by a subclass's redefinition of :meth:`from_xmrs`. """ x = cls() x.__dict__.update(xmrs.__dict__) return x
python
def from_xmrs(cls, xmrs, **kwargs): """ Facilitate conversion among subclasses. Args: xmrs (:class:`Xmrs`): instance to convert from; possibly an instance of a subclass, such as :class:`Mrs` or :class:`Dmrs` **kwargs: additional keyword arguments that may be used by a subclass's redefinition of :meth:`from_xmrs`. """ x = cls() x.__dict__.update(xmrs.__dict__) return x
Facilitate conversion among subclasses. Args: xmrs (:class:`Xmrs`): instance to convert from; possibly an instance of a subclass, such as :class:`Mrs` or :class:`Dmrs` **kwargs: additional keyword arguments that may be used by a subclass's redefinition of :meth:`from_xmrs`.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L105-L118
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.add_eps
def add_eps(self, eps): """ Incorporate the list of EPs given by *eps*. """ # (nodeid, pred, label, args, lnk, surface, base) _nodeids, _eps, _vars = self._nodeids, self._eps, self._vars for ep in eps: try: if not isinstance(ep, ElementaryPredication): ep = ElementaryPredication(*ep) except TypeError: raise XmrsError('Invalid EP data: {}'.format(repr(ep))) # eplen = len(ep) # if eplen < 3: # raise XmrsError( # 'EPs must have length >= 3: (nodeid, pred, label, ...)' # ) nodeid, lbl = ep.nodeid, ep.label if nodeid in _eps: raise XmrsError( 'EP already exists in Xmrs: {} ({})' .format(nodeid, ep[1]) ) _nodeids.append(nodeid) _eps[nodeid] = ep if lbl is not None: _vars[lbl]['refs']['LBL'].append(nodeid) for role, val in ep.args.items(): # if the val is not in _vars, it might still be a # variable; check with var_re if val in _vars or var_re.match(val): vardict = _vars[val] vardict['refs'][role].append(nodeid)
python
def add_eps(self, eps): """ Incorporate the list of EPs given by *eps*. """ # (nodeid, pred, label, args, lnk, surface, base) _nodeids, _eps, _vars = self._nodeids, self._eps, self._vars for ep in eps: try: if not isinstance(ep, ElementaryPredication): ep = ElementaryPredication(*ep) except TypeError: raise XmrsError('Invalid EP data: {}'.format(repr(ep))) # eplen = len(ep) # if eplen < 3: # raise XmrsError( # 'EPs must have length >= 3: (nodeid, pred, label, ...)' # ) nodeid, lbl = ep.nodeid, ep.label if nodeid in _eps: raise XmrsError( 'EP already exists in Xmrs: {} ({})' .format(nodeid, ep[1]) ) _nodeids.append(nodeid) _eps[nodeid] = ep if lbl is not None: _vars[lbl]['refs']['LBL'].append(nodeid) for role, val in ep.args.items(): # if the val is not in _vars, it might still be a # variable; check with var_re if val in _vars or var_re.match(val): vardict = _vars[val] vardict['refs'][role].append(nodeid)
Incorporate the list of EPs given by *eps*.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L120-L152
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.add_hcons
def add_hcons(self, hcons): """ Incorporate the list of HandleConstraints given by *hcons*. """ # (hi, relation, lo) _vars = self._vars _hcons = self._hcons for hc in hcons: try: if not isinstance(hc, HandleConstraint): hc = HandleConstraint(*hc) except TypeError: raise XmrsError('Invalid HCONS data: {}'.format(repr(hc))) hi = hc.hi lo = hc.lo if hi in _hcons: raise XmrsError( 'Handle constraint already exists for hole %s.' % hi ) _hcons[hi] = hc # the following should also ensure lo and hi are in _vars if 'hcrefs' not in _vars[lo]: _vars[lo]['hcrefs'] = [] for role, refs in _vars[hi]['refs'].items(): for nodeid in refs: _vars[lo]['hcrefs'].append((nodeid, role, hi))
python
def add_hcons(self, hcons): """ Incorporate the list of HandleConstraints given by *hcons*. """ # (hi, relation, lo) _vars = self._vars _hcons = self._hcons for hc in hcons: try: if not isinstance(hc, HandleConstraint): hc = HandleConstraint(*hc) except TypeError: raise XmrsError('Invalid HCONS data: {}'.format(repr(hc))) hi = hc.hi lo = hc.lo if hi in _hcons: raise XmrsError( 'Handle constraint already exists for hole %s.' % hi ) _hcons[hi] = hc # the following should also ensure lo and hi are in _vars if 'hcrefs' not in _vars[lo]: _vars[lo]['hcrefs'] = [] for role, refs in _vars[hi]['refs'].items(): for nodeid in refs: _vars[lo]['hcrefs'].append((nodeid, role, hi))
Incorporate the list of HandleConstraints given by *hcons*.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L159-L185
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.add_icons
def add_icons(self, icons): """ Incorporate the individual constraints given by *icons*. """ _vars, _icons = self._vars, self._icons for ic in icons: try: if not isinstance(ic, IndividualConstraint): ic = IndividualConstraint(*ic) except TypeError: raise XmrsError('Invalid ICONS data: {}'.format(repr(ic))) left = ic.left right = ic.right if left not in _icons: _icons[left] = [] _icons[left].append(ic) # the following should also ensure left and right are in _vars if 'icrefs' not in _vars[right]: _vars[right]['icrefs'] = [] _vars[right]['icrefs'].append(ic) _vars[left]
python
def add_icons(self, icons): """ Incorporate the individual constraints given by *icons*. """ _vars, _icons = self._vars, self._icons for ic in icons: try: if not isinstance(ic, IndividualConstraint): ic = IndividualConstraint(*ic) except TypeError: raise XmrsError('Invalid ICONS data: {}'.format(repr(ic))) left = ic.left right = ic.right if left not in _icons: _icons[left] = [] _icons[left].append(ic) # the following should also ensure left and right are in _vars if 'icrefs' not in _vars[right]: _vars[right]['icrefs'] = [] _vars[right]['icrefs'].append(ic) _vars[left]
Incorporate the individual constraints given by *icons*.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L187-L207
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.nodeid
def nodeid(self, iv, quantifier=False): """ Return the nodeid of the predication selected by *iv*. Args: iv: the intrinsic variable of the predication to select quantifier: if `True`, treat *iv* as a bound variable and find its quantifier; otherwise the non-quantifier will be returned """ return next(iter(self.nodeids(ivs=[iv], quantifier=quantifier)), None)
python
def nodeid(self, iv, quantifier=False): """ Return the nodeid of the predication selected by *iv*. Args: iv: the intrinsic variable of the predication to select quantifier: if `True`, treat *iv* as a bound variable and find its quantifier; otherwise the non-quantifier will be returned """ return next(iter(self.nodeids(ivs=[iv], quantifier=quantifier)), None)
Return the nodeid of the predication selected by *iv*. Args: iv: the intrinsic variable of the predication to select quantifier: if `True`, treat *iv* as a bound variable and find its quantifier; otherwise the non-quantifier will be returned
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L255-L265
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.nodeids
def nodeids(self, ivs=None, quantifier=None): """ Return the list of nodeids given by *ivs*, or all nodeids. Args: ivs: the intrinsic variables of the predications to select; if `None`, return all nodeids (but see *quantifier*) quantifier: if `True`, only return nodeids of quantifiers; if `False`, only return non-quantifiers; if `None` (the default), return both """ if ivs is None: nids = list(self._nodeids) else: _vars = self._vars nids = [] for iv in ivs: if iv in _vars and IVARG_ROLE in _vars[iv]['refs']: nids.extend(_vars[iv]['refs'][IVARG_ROLE]) else: raise KeyError(iv) if quantifier is not None: nids = [n for n in nids if self.ep(n).is_quantifier()==quantifier] return nids
python
def nodeids(self, ivs=None, quantifier=None): """ Return the list of nodeids given by *ivs*, or all nodeids. Args: ivs: the intrinsic variables of the predications to select; if `None`, return all nodeids (but see *quantifier*) quantifier: if `True`, only return nodeids of quantifiers; if `False`, only return non-quantifiers; if `None` (the default), return both """ if ivs is None: nids = list(self._nodeids) else: _vars = self._vars nids = [] for iv in ivs: if iv in _vars and IVARG_ROLE in _vars[iv]['refs']: nids.extend(_vars[iv]['refs'][IVARG_ROLE]) else: raise KeyError(iv) if quantifier is not None: nids = [n for n in nids if self.ep(n).is_quantifier()==quantifier] return nids
Return the list of nodeids given by *ivs*, or all nodeids. Args: ivs: the intrinsic variables of the predications to select; if `None`, return all nodeids (but see *quantifier*) quantifier: if `True`, only return nodeids of quantifiers; if `False`, only return non-quantifiers; if `None` (the default), return both
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L267-L290
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.eps
def eps(self, nodeids=None): """ Return the EPs with the given *nodeid*, or all EPs. Args: nodeids: an iterable of nodeids of EPs to return; if `None`, return all EPs """ if nodeids is None: nodeids = self._nodeids _eps = self._eps return [_eps[nodeid] for nodeid in nodeids]
python
def eps(self, nodeids=None): """ Return the EPs with the given *nodeid*, or all EPs. Args: nodeids: an iterable of nodeids of EPs to return; if `None`, return all EPs """ if nodeids is None: nodeids = self._nodeids _eps = self._eps return [_eps[nodeid] for nodeid in nodeids]
Return the EPs with the given *nodeid*, or all EPs. Args: nodeids: an iterable of nodeids of EPs to return; if `None`, return all EPs
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L298-L308
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.icons
def icons(self, left=None): """ Return the ICONS with left variable *left*, or all ICONS. Args: left: the left variable of the ICONS to return; if `None`, return all ICONS """ if left is not None: return self._icons[left] else: return list(chain.from_iterable(self._icons.values()))
python
def icons(self, left=None): """ Return the ICONS with left variable *left*, or all ICONS. Args: left: the left variable of the ICONS to return; if `None`, return all ICONS """ if left is not None: return self._icons[left] else: return list(chain.from_iterable(self._icons.values()))
Return the ICONS with left variable *left*, or all ICONS. Args: left: the left variable of the ICONS to return; if `None`, return all ICONS
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L322-L333
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.properties
def properties(self, var_or_nodeid, as_list=False): """ Return a dictionary of variable properties for *var_or_nodeid*. Args: var_or_nodeid: if a variable, return the properties associated with the variable; if a nodeid, return the properties associated with the intrinsic variable of the predication given by the nodeid """ props = [] if var_or_nodeid in self._vars: props = self._vars[var_or_nodeid]['props'] elif var_or_nodeid in self._eps: var = self._eps[var_or_nodeid][3].get(IVARG_ROLE) props = self._vars.get(var, {}).get('props', []) else: raise KeyError(var_or_nodeid) if not as_list: props = dict(props) return props
python
def properties(self, var_or_nodeid, as_list=False): """ Return a dictionary of variable properties for *var_or_nodeid*. Args: var_or_nodeid: if a variable, return the properties associated with the variable; if a nodeid, return the properties associated with the intrinsic variable of the predication given by the nodeid """ props = [] if var_or_nodeid in self._vars: props = self._vars[var_or_nodeid]['props'] elif var_or_nodeid in self._eps: var = self._eps[var_or_nodeid][3].get(IVARG_ROLE) props = self._vars.get(var, {}).get('props', []) else: raise KeyError(var_or_nodeid) if not as_list: props = dict(props) return props
Return a dictionary of variable properties for *var_or_nodeid*. Args: var_or_nodeid: if a variable, return the properties associated with the variable; if a nodeid, return the properties associated with the intrinsic variable of the predication given by the nodeid
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L343-L363
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.preds
def preds(self, nodeids=None): """ Return the Pred objects for *nodeids*, or all Preds. Args: nodeids: an iterable of nodeids of predications to return Preds from; if `None`, return all Preds """ if nodeids is None: nodeids = self._nodeids _eps = self._eps return [_eps[nid][1] for nid in nodeids]
python
def preds(self, nodeids=None): """ Return the Pred objects for *nodeids*, or all Preds. Args: nodeids: an iterable of nodeids of predications to return Preds from; if `None`, return all Preds """ if nodeids is None: nodeids = self._nodeids _eps = self._eps return [_eps[nid][1] for nid in nodeids]
Return the Pred objects for *nodeids*, or all Preds. Args: nodeids: an iterable of nodeids of predications to return Preds from; if `None`, return all Preds
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L371-L381
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.labels
def labels(self, nodeids=None): """ Return the list of labels for *nodeids*, or all labels. Args: nodeids: an iterable of nodeids for predications to get labels from; if `None`, return labels for all predications Note: This returns the label of each predication, even if it's shared by another predication. Thus, `zip(nodeids, xmrs.labels(nodeids))` will pair nodeids with their labels. Returns: A list of labels """ if nodeids is None: nodeids = self._nodeids _eps = self._eps return [_eps[nid][2] for nid in nodeids]
python
def labels(self, nodeids=None): """ Return the list of labels for *nodeids*, or all labels. Args: nodeids: an iterable of nodeids for predications to get labels from; if `None`, return labels for all predications Note: This returns the label of each predication, even if it's shared by another predication. Thus, `zip(nodeids, xmrs.labels(nodeids))` will pair nodeids with their labels. Returns: A list of labels """ if nodeids is None: nodeids = self._nodeids _eps = self._eps return [_eps[nid][2] for nid in nodeids]
Return the list of labels for *nodeids*, or all labels. Args: nodeids: an iterable of nodeids for predications to get labels from; if `None`, return labels for all predications Note: This returns the label of each predication, even if it's shared by another predication. Thus, `zip(nodeids, xmrs.labels(nodeids))` will pair nodeids with their labels. Returns: A list of labels
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L389-L407
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.outgoing_args
def outgoing_args(self, nodeid): """ Return the arguments going from *nodeid* to other predications. Valid arguments include regular variable arguments and scopal (label-selecting or HCONS) arguments. MOD/EQ links, intrinsic arguments, and constant arguments are not included. Args: nodeid: the nodeid of the EP that is the arguments' source Returns: dict: `{role: tgt}` """ _vars = self._vars _hcons = self._hcons args = self.args(nodeid) # args is a copy; we can edit it for arg, val in list(args.items()): # don't include constant args or intrinsic args if arg == IVARG_ROLE or val not in _vars: del args[arg] else: refs = _vars[val]['refs'] # don't include if not HCONS or pointing to other IV or LBL if not (val in _hcons or IVARG_ROLE in refs or 'LBL' in refs): del args[arg] return args
python
def outgoing_args(self, nodeid): """ Return the arguments going from *nodeid* to other predications. Valid arguments include regular variable arguments and scopal (label-selecting or HCONS) arguments. MOD/EQ links, intrinsic arguments, and constant arguments are not included. Args: nodeid: the nodeid of the EP that is the arguments' source Returns: dict: `{role: tgt}` """ _vars = self._vars _hcons = self._hcons args = self.args(nodeid) # args is a copy; we can edit it for arg, val in list(args.items()): # don't include constant args or intrinsic args if arg == IVARG_ROLE or val not in _vars: del args[arg] else: refs = _vars[val]['refs'] # don't include if not HCONS or pointing to other IV or LBL if not (val in _hcons or IVARG_ROLE in refs or 'LBL' in refs): del args[arg] return args
Return the arguments going from *nodeid* to other predications. Valid arguments include regular variable arguments and scopal (label-selecting or HCONS) arguments. MOD/EQ links, intrinsic arguments, and constant arguments are not included. Args: nodeid: the nodeid of the EP that is the arguments' source Returns: dict: `{role: tgt}`
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L427-L453
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.incoming_args
def incoming_args(self, nodeid): """ Return the arguments that target *nodeid*. Valid arguments include regular variable arguments and scopal (label-selecting or HCONS) arguments. MOD/EQ links and intrinsic arguments are not included. Args: nodeid: the nodeid of the EP that is the arguments' target Returns: dict: `{source_nodeid: {rargname: value}}` """ _vars = self._vars ep = self._eps[nodeid] lbl = ep[2] iv = ep[3].get(IVARG_ROLE) in_args_list = [] # variable args if iv in _vars: for role, nids in _vars[iv]['refs'].items(): # ignore intrinsic args, even if shared if role != IVARG_ROLE: in_args_list.append((nids, role, iv)) if lbl in _vars: for role, nids in _vars[lbl]['refs'].items(): # basic label equality isn't "incoming"; ignore if role != 'LBL': in_args_list.append((nids, role, lbl)) for nid, role, hi in _vars[lbl].get('hcrefs', []): in_args_list.append(([nid], role, hi)) in_args = {} for nids, role, tgt in in_args_list: for nid in nids: if nid not in in_args: in_args[nid] = {} in_args[nid][role] = tgt return in_args
python
def incoming_args(self, nodeid): """ Return the arguments that target *nodeid*. Valid arguments include regular variable arguments and scopal (label-selecting or HCONS) arguments. MOD/EQ links and intrinsic arguments are not included. Args: nodeid: the nodeid of the EP that is the arguments' target Returns: dict: `{source_nodeid: {rargname: value}}` """ _vars = self._vars ep = self._eps[nodeid] lbl = ep[2] iv = ep[3].get(IVARG_ROLE) in_args_list = [] # variable args if iv in _vars: for role, nids in _vars[iv]['refs'].items(): # ignore intrinsic args, even if shared if role != IVARG_ROLE: in_args_list.append((nids, role, iv)) if lbl in _vars: for role, nids in _vars[lbl]['refs'].items(): # basic label equality isn't "incoming"; ignore if role != 'LBL': in_args_list.append((nids, role, lbl)) for nid, role, hi in _vars[lbl].get('hcrefs', []): in_args_list.append(([nid], role, hi)) in_args = {} for nids, role, tgt in in_args_list: for nid in nids: if nid not in in_args: in_args[nid] = {} in_args[nid][role] = tgt return in_args
Return the arguments that target *nodeid*. Valid arguments include regular variable arguments and scopal (label-selecting or HCONS) arguments. MOD/EQ links and intrinsic arguments are not included. Args: nodeid: the nodeid of the EP that is the arguments' target Returns: dict: `{source_nodeid: {rargname: value}}`
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L455-L492
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.labelset_heads
def labelset_heads(self, label): """ Return the heads of the labelset selected by *label*. Args: label: the label from which to find head nodes/EPs. Returns: An iterable of nodeids. """ _eps = self._eps _vars = self._vars _hcons = self._hcons nodeids = {nodeid: _eps[nodeid][3].get(IVARG_ROLE, None) for nodeid in _vars[label]['refs']['LBL']} if len(nodeids) <= 1: return list(nodeids) scope_sets = {} for nid in nodeids: scope_sets[nid] = _ivs_in_scope(nid, _eps, _vars, _hcons) out = {} for n in nodeids: out[n] = 0 for role, val in _eps[n][3].items(): if role == IVARG_ROLE or role == CONSTARG_ROLE: continue elif any(val in s for n2, s in scope_sets.items() if n2 != n): out[n] += 1 candidates = [n for n, out_deg in out.items() if out_deg == 0] rank = {} for n in candidates: iv = nodeids[n] pred = _eps[n][1] if iv in _vars and self.nodeid(iv, quantifier=True) is not None: rank[n] = 0 elif pred.is_quantifier(): rank[n] = 0 elif pred.type == Pred.ABSTRACT: rank[n] = 2 else: rank[n] = 1 return sorted(candidates, key=lambda n: rank[n])
python
def labelset_heads(self, label): """ Return the heads of the labelset selected by *label*. Args: label: the label from which to find head nodes/EPs. Returns: An iterable of nodeids. """ _eps = self._eps _vars = self._vars _hcons = self._hcons nodeids = {nodeid: _eps[nodeid][3].get(IVARG_ROLE, None) for nodeid in _vars[label]['refs']['LBL']} if len(nodeids) <= 1: return list(nodeids) scope_sets = {} for nid in nodeids: scope_sets[nid] = _ivs_in_scope(nid, _eps, _vars, _hcons) out = {} for n in nodeids: out[n] = 0 for role, val in _eps[n][3].items(): if role == IVARG_ROLE or role == CONSTARG_ROLE: continue elif any(val in s for n2, s in scope_sets.items() if n2 != n): out[n] += 1 candidates = [n for n, out_deg in out.items() if out_deg == 0] rank = {} for n in candidates: iv = nodeids[n] pred = _eps[n][1] if iv in _vars and self.nodeid(iv, quantifier=True) is not None: rank[n] = 0 elif pred.is_quantifier(): rank[n] = 0 elif pred.type == Pred.ABSTRACT: rank[n] = 2 else: rank[n] = 1 return sorted(candidates, key=lambda n: rank[n])
Return the heads of the labelset selected by *label*. Args: label: the label from which to find head nodes/EPs. Returns: An iterable of nodeids.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L505-L549
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.subgraph
def subgraph(self, nodeids): """ Return an Xmrs object with only the specified *nodeids*. Necessary variables and arguments are also included in order to connect any nodes that are connected in the original Xmrs. Args: nodeids: the nodeids of the nodes/EPs to include in the subgraph. Returns: An :class:`Xmrs` object. """ _eps, _vars = self._eps, self._vars _hcons, _icons = self._hcons, self._icons top = index = xarg = None eps = [_eps[nid] for nid in nodeids] lbls = set(ep[2] for ep in eps) hcons = [] icons = [] subvars = {} if self.top: top = self.top tophc = _hcons.get(top, None) if tophc is not None and tophc[2] in lbls: subvars[top] = {} elif top not in lbls: top = None # nevermind, set it back to None # do index after we know if it is an EPs intrinsic variable. # what about xarg? I'm not really sure.. just put it in if self.xarg: xarg = self.xarg subvars[self.xarg] = _vars[self.xarg]['props'] subvars.update((lbl, {}) for lbl in lbls) subvars.update( (var, _vars[var]['props']) for ep in eps for var in ep[3].values() if var in _vars ) if self.index in subvars: index = self.index # hcons and icons; only if the targets exist in the new subgraph for var in subvars: hc = _hcons.get(var, None) if hc is not None and hc[2] in lbls: hcons.append(hc) for ic in _icons.get(var, []): if ic[0] in subvars and ic[2] in subvars: icons.append(ic) return Xmrs( top=top, index=index, xarg=xarg, eps=eps, hcons=hcons, icons=icons, vars=subvars, lnk=self.lnk, surface=self.surface, identifier=self.identifier )
python
def subgraph(self, nodeids): """ Return an Xmrs object with only the specified *nodeids*. Necessary variables and arguments are also included in order to connect any nodes that are connected in the original Xmrs. Args: nodeids: the nodeids of the nodes/EPs to include in the subgraph. Returns: An :class:`Xmrs` object. """ _eps, _vars = self._eps, self._vars _hcons, _icons = self._hcons, self._icons top = index = xarg = None eps = [_eps[nid] for nid in nodeids] lbls = set(ep[2] for ep in eps) hcons = [] icons = [] subvars = {} if self.top: top = self.top tophc = _hcons.get(top, None) if tophc is not None and tophc[2] in lbls: subvars[top] = {} elif top not in lbls: top = None # nevermind, set it back to None # do index after we know if it is an EPs intrinsic variable. # what about xarg? I'm not really sure.. just put it in if self.xarg: xarg = self.xarg subvars[self.xarg] = _vars[self.xarg]['props'] subvars.update((lbl, {}) for lbl in lbls) subvars.update( (var, _vars[var]['props']) for ep in eps for var in ep[3].values() if var in _vars ) if self.index in subvars: index = self.index # hcons and icons; only if the targets exist in the new subgraph for var in subvars: hc = _hcons.get(var, None) if hc is not None and hc[2] in lbls: hcons.append(hc) for ic in _icons.get(var, []): if ic[0] in subvars and ic[2] in subvars: icons.append(ic) return Xmrs( top=top, index=index, xarg=xarg, eps=eps, hcons=hcons, icons=icons, vars=subvars, lnk=self.lnk, surface=self.surface, identifier=self.identifier )
Return an Xmrs object with only the specified *nodeids*. Necessary variables and arguments are also included in order to connect any nodes that are connected in the original Xmrs. Args: nodeids: the nodeids of the nodes/EPs to include in the subgraph. Returns: An :class:`Xmrs` object.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L551-L604
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.is_connected
def is_connected(self): """ Return `True` if the Xmrs represents a connected graph. Subgraphs can be connected through things like arguments, QEQs, and label equalities. """ nids = set(self._nodeids) # the nids left to find if len(nids) == 0: raise XmrsError('Cannot compute connectedness of an empty Xmrs.') # build a basic dict graph of relations edges = [] # label connections for lbl in self.labels(): lblset = self.labelset(lbl) edges.extend((x, y) for x in lblset for y in lblset if x != y) # argument connections _vars = self._vars for nid in nids: for rarg, tgt in self.args(nid).items(): if tgt not in _vars: continue if IVARG_ROLE in _vars[tgt]['refs']: tgtnids = list(_vars[tgt]['refs'][IVARG_ROLE]) elif tgt in self._hcons: tgtnids = list(self.labelset(self.hcon(tgt)[2])) elif 'LBL' in _vars[tgt]['refs']: tgtnids = list(_vars[tgt]['refs']['LBL']) else: tgtnids = [] # connections are bidirectional edges.extend((nid, t) for t in tgtnids if nid != t) edges.extend((t, nid) for t in tgtnids if nid != t) g = {nid: set() for nid in nids} for x, y in edges: g[x].add(y) connected_nids = _bfs(g) if connected_nids == nids: return True elif connected_nids.difference(nids): raise XmrsError( 'Possibly bogus nodeids: {}' .format(', '.join(connected_nids.difference(nids))) ) return False
python
def is_connected(self): """ Return `True` if the Xmrs represents a connected graph. Subgraphs can be connected through things like arguments, QEQs, and label equalities. """ nids = set(self._nodeids) # the nids left to find if len(nids) == 0: raise XmrsError('Cannot compute connectedness of an empty Xmrs.') # build a basic dict graph of relations edges = [] # label connections for lbl in self.labels(): lblset = self.labelset(lbl) edges.extend((x, y) for x in lblset for y in lblset if x != y) # argument connections _vars = self._vars for nid in nids: for rarg, tgt in self.args(nid).items(): if tgt not in _vars: continue if IVARG_ROLE in _vars[tgt]['refs']: tgtnids = list(_vars[tgt]['refs'][IVARG_ROLE]) elif tgt in self._hcons: tgtnids = list(self.labelset(self.hcon(tgt)[2])) elif 'LBL' in _vars[tgt]['refs']: tgtnids = list(_vars[tgt]['refs']['LBL']) else: tgtnids = [] # connections are bidirectional edges.extend((nid, t) for t in tgtnids if nid != t) edges.extend((t, nid) for t in tgtnids if nid != t) g = {nid: set() for nid in nids} for x, y in edges: g[x].add(y) connected_nids = _bfs(g) if connected_nids == nids: return True elif connected_nids.difference(nids): raise XmrsError( 'Possibly bogus nodeids: {}' .format(', '.join(connected_nids.difference(nids))) ) return False
Return `True` if the Xmrs represents a connected graph. Subgraphs can be connected through things like arguments, QEQs, and label equalities.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L606-L650
delph-in/pydelphin
delphin/mrs/xmrs.py
Xmrs.validate
def validate(self): """ Check that the Xmrs is well-formed. The Xmrs is analyzed and a list of problems is compiled. If any problems exist, an :exc:`XmrsError` is raised with the list joined as the error message. A well-formed Xmrs has the following properties: * All predications have an intrinsic variable * Every intrinsic variable belongs one predication and maybe one quantifier * Every predication has no more than one quantifier * All predications have a label * The graph of predications form a net (i.e. are connected). Connectivity can be established with variable arguments, QEQs, or label-equality. * The lo-handle for each QEQ must exist as the label of a predication """ errors = [] ivs, bvs = {}, {} _vars = self._vars _hcons = self._hcons labels = defaultdict(set) # ep_args = {} for ep in self.eps(): nid, lbl, args, is_q = ( ep.nodeid, ep.label, ep.args, ep.is_quantifier() ) if lbl is None: errors.append('EP ({}) is missing a label.'.format(nid)) labels[lbl].add(nid) iv = args.get(IVARG_ROLE) if iv is None: errors.append('EP {nid} is missing an intrinsic variable.' .format(nid)) if is_q: if iv in bvs: errors.append('{} is the bound variable for more than ' 'one quantifier.'.format(iv)) bvs[iv] = nid else: if iv in ivs: errors.append('{} is the intrinsic variable for more ' 'than one EP.'.format(iv)) ivs[iv] = nid # ep_args[nid] = args for hc in _hcons.values(): if hc[2] not in labels: errors.append('Lo variable of HCONS ({} {} {}) is not the ' 'label of any EP.'.format(*hc)) if not self.is_connected(): errors.append('Xmrs structure is not connected.') if errors: raise XmrsError('\n'.join(errors))
python
def validate(self): """ Check that the Xmrs is well-formed. The Xmrs is analyzed and a list of problems is compiled. If any problems exist, an :exc:`XmrsError` is raised with the list joined as the error message. A well-formed Xmrs has the following properties: * All predications have an intrinsic variable * Every intrinsic variable belongs one predication and maybe one quantifier * Every predication has no more than one quantifier * All predications have a label * The graph of predications form a net (i.e. are connected). Connectivity can be established with variable arguments, QEQs, or label-equality. * The lo-handle for each QEQ must exist as the label of a predication """ errors = [] ivs, bvs = {}, {} _vars = self._vars _hcons = self._hcons labels = defaultdict(set) # ep_args = {} for ep in self.eps(): nid, lbl, args, is_q = ( ep.nodeid, ep.label, ep.args, ep.is_quantifier() ) if lbl is None: errors.append('EP ({}) is missing a label.'.format(nid)) labels[lbl].add(nid) iv = args.get(IVARG_ROLE) if iv is None: errors.append('EP {nid} is missing an intrinsic variable.' .format(nid)) if is_q: if iv in bvs: errors.append('{} is the bound variable for more than ' 'one quantifier.'.format(iv)) bvs[iv] = nid else: if iv in ivs: errors.append('{} is the intrinsic variable for more ' 'than one EP.'.format(iv)) ivs[iv] = nid # ep_args[nid] = args for hc in _hcons.values(): if hc[2] not in labels: errors.append('Lo variable of HCONS ({} {} {}) is not the ' 'label of any EP.'.format(*hc)) if not self.is_connected(): errors.append('Xmrs structure is not connected.') if errors: raise XmrsError('\n'.join(errors))
Check that the Xmrs is well-formed. The Xmrs is analyzed and a list of problems is compiled. If any problems exist, an :exc:`XmrsError` is raised with the list joined as the error message. A well-formed Xmrs has the following properties: * All predications have an intrinsic variable * Every intrinsic variable belongs one predication and maybe one quantifier * Every predication has no more than one quantifier * All predications have a label * The graph of predications form a net (i.e. are connected). Connectivity can be established with variable arguments, QEQs, or label-equality. * The lo-handle for each QEQ must exist as the label of a predication
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L664-L719