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/mrs/xmrs.py | Mrs.to_dict | def to_dict(self, short_pred=True, properties=True):
"""
Encode the Mrs as a dictionary suitable for JSON serialization.
"""
def _lnk(obj): return {'from': obj.cfrom, 'to': obj.cto}
def _ep(ep, short_pred=True):
p = ep.pred.short_form() if short_pred else ep.pred.string
d = dict(label=ep.label, predicate=p, arguments=ep.args)
if ep.lnk is not None: d['lnk'] = _lnk(ep)
return d
def _hcons(hc): return {'relation':hc[1], 'high':hc[0], 'low':hc[2]}
def _icons(ic): return {'relation':ic[1], 'left':ic[0], 'right':ic[2]}
def _var(v):
d = {'type': var_sort(v)}
if properties and self.properties(v):
d['properties'] = self.properties(v)
return d
d = dict(
relations=[_ep(ep, short_pred=short_pred) for ep in self.eps()],
constraints=([_hcons(hc) for hc in self.hcons()] +
[_icons(ic) for ic in self.icons()]),
variables={v: _var(v) for v in self.variables()}
)
if self.top is not None: d['top'] = self.top
if self.index is not None: d['index'] = self.index
# if self.xarg is not None: d['xarg'] = self.xarg
# if self.lnk is not None: d['lnk'] = self.lnk
# if self.surface is not None: d['surface'] = self.surface
# if self.identifier is not None: d['identifier'] = self.identifier
return d | python | def to_dict(self, short_pred=True, properties=True):
"""
Encode the Mrs as a dictionary suitable for JSON serialization.
"""
def _lnk(obj): return {'from': obj.cfrom, 'to': obj.cto}
def _ep(ep, short_pred=True):
p = ep.pred.short_form() if short_pred else ep.pred.string
d = dict(label=ep.label, predicate=p, arguments=ep.args)
if ep.lnk is not None: d['lnk'] = _lnk(ep)
return d
def _hcons(hc): return {'relation':hc[1], 'high':hc[0], 'low':hc[2]}
def _icons(ic): return {'relation':ic[1], 'left':ic[0], 'right':ic[2]}
def _var(v):
d = {'type': var_sort(v)}
if properties and self.properties(v):
d['properties'] = self.properties(v)
return d
d = dict(
relations=[_ep(ep, short_pred=short_pred) for ep in self.eps()],
constraints=([_hcons(hc) for hc in self.hcons()] +
[_icons(ic) for ic in self.icons()]),
variables={v: _var(v) for v in self.variables()}
)
if self.top is not None: d['top'] = self.top
if self.index is not None: d['index'] = self.index
# if self.xarg is not None: d['xarg'] = self.xarg
# if self.lnk is not None: d['lnk'] = self.lnk
# if self.surface is not None: d['surface'] = self.surface
# if self.identifier is not None: d['identifier'] = self.identifier
return d | Encode the Mrs as a dictionary suitable for JSON serialization. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L783-L813 |
delph-in/pydelphin | delphin/mrs/xmrs.py | Mrs.from_dict | def from_dict(cls, d):
"""
Decode a dictionary, as from :meth:`to_dict`, into an Mrs object.
"""
def _lnk(o):
return None if o is None else Lnk.charspan(o['from'], o['to'])
def _ep(ep):
return ElementaryPredication(
nodeid=None,
pred=Pred.surface_or_abstract(ep['predicate']),
label=ep['label'],
args=ep.get('arguments', {}),
lnk=_lnk(ep.get('lnk')),
surface=ep.get('surface'),
base=ep.get('base')
)
eps = [_ep(rel) for rel in d.get('relations', [])]
hcons = [(c['high'], c['relation'], c['low'])
for c in d.get('constraints', []) if 'high' in c]
icons = [(c['high'], c['relation'], c['low'])
for c in d.get('constraints', []) if 'left' in c]
variables = {var: list(data.get('properties', {}).items())
for var, data in d.get('variables', {}).items()}
return cls(
top=d.get('top'),
index=d.get('index'),
xarg=d.get('xarg'),
rels=eps,
hcons=hcons,
icons=icons,
lnk=_lnk(d.get('lnk')),
surface=d.get('surface'),
identifier=d.get('identifier'),
vars=variables
) | python | def from_dict(cls, d):
"""
Decode a dictionary, as from :meth:`to_dict`, into an Mrs object.
"""
def _lnk(o):
return None if o is None else Lnk.charspan(o['from'], o['to'])
def _ep(ep):
return ElementaryPredication(
nodeid=None,
pred=Pred.surface_or_abstract(ep['predicate']),
label=ep['label'],
args=ep.get('arguments', {}),
lnk=_lnk(ep.get('lnk')),
surface=ep.get('surface'),
base=ep.get('base')
)
eps = [_ep(rel) for rel in d.get('relations', [])]
hcons = [(c['high'], c['relation'], c['low'])
for c in d.get('constraints', []) if 'high' in c]
icons = [(c['high'], c['relation'], c['low'])
for c in d.get('constraints', []) if 'left' in c]
variables = {var: list(data.get('properties', {}).items())
for var, data in d.get('variables', {}).items()}
return cls(
top=d.get('top'),
index=d.get('index'),
xarg=d.get('xarg'),
rels=eps,
hcons=hcons,
icons=icons,
lnk=_lnk(d.get('lnk')),
surface=d.get('surface'),
identifier=d.get('identifier'),
vars=variables
) | Decode a dictionary, as from :meth:`to_dict`, into an Mrs object. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L816-L850 |
delph-in/pydelphin | delphin/mrs/xmrs.py | Dmrs.to_dict | def to_dict(self, short_pred=True, properties=True):
"""
Encode the Dmrs as a dictionary suitable for JSON serialization.
"""
qs = set(self.nodeids(quantifier=True))
def _lnk(obj): return {'from': obj.cfrom, 'to': obj.cto}
def _node(node, short_pred=True):
p = node.pred.short_form() if short_pred else node.pred.string
d = dict(nodeid=node.nodeid, predicate=p)
if node.lnk is not None: d['lnk'] = _lnk(node)
if properties and node.sortinfo:
if node.nodeid not in qs:
d['sortinfo'] = node.sortinfo
if node.surface is not None: d['surface'] = node.surface
if node.base is not None: d['base'] = node.base
if node.carg is not None: d['carg'] = node.carg
return d
def _link(link): return {
'from': link.start, 'to': link.end,
'rargname': link.rargname, 'post': link.post
}
d = dict(
nodes=[_node(n) for n in nodes(self)],
links=[_link(l) for l in links(self)]
)
# if self.top is not None: ... currently handled by links
if self.index is not None:
idx = self.nodeid(self.index)
if idx is not None:
d['index'] = idx
if self.xarg is not None:
xarg = self.nodeid(self.index)
if xarg is not None:
d['index'] = xarg
if self.lnk is not None: d['lnk'] = _lnk(self)
if self.surface is not None: d['surface'] = self.surface
if self.identifier is not None: d['identifier'] = self.identifier
return d | python | def to_dict(self, short_pred=True, properties=True):
"""
Encode the Dmrs as a dictionary suitable for JSON serialization.
"""
qs = set(self.nodeids(quantifier=True))
def _lnk(obj): return {'from': obj.cfrom, 'to': obj.cto}
def _node(node, short_pred=True):
p = node.pred.short_form() if short_pred else node.pred.string
d = dict(nodeid=node.nodeid, predicate=p)
if node.lnk is not None: d['lnk'] = _lnk(node)
if properties and node.sortinfo:
if node.nodeid not in qs:
d['sortinfo'] = node.sortinfo
if node.surface is not None: d['surface'] = node.surface
if node.base is not None: d['base'] = node.base
if node.carg is not None: d['carg'] = node.carg
return d
def _link(link): return {
'from': link.start, 'to': link.end,
'rargname': link.rargname, 'post': link.post
}
d = dict(
nodes=[_node(n) for n in nodes(self)],
links=[_link(l) for l in links(self)]
)
# if self.top is not None: ... currently handled by links
if self.index is not None:
idx = self.nodeid(self.index)
if idx is not None:
d['index'] = idx
if self.xarg is not None:
xarg = self.nodeid(self.index)
if xarg is not None:
d['index'] = xarg
if self.lnk is not None: d['lnk'] = _lnk(self)
if self.surface is not None: d['surface'] = self.surface
if self.identifier is not None: d['identifier'] = self.identifier
return d | Encode the Dmrs as a dictionary suitable for JSON serialization. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L1011-L1049 |
delph-in/pydelphin | delphin/mrs/xmrs.py | Dmrs.from_dict | def from_dict(cls, d):
"""
Decode a dictionary, as from :meth:`to_dict`, into a Dmrs object.
"""
def _node(obj):
return Node(
obj.get('nodeid'),
Pred.surface_or_abstract(obj.get('predicate')),
sortinfo=obj.get('sortinfo'),
lnk=_lnk(obj.get('lnk')),
surface=obj.get('surface'),
base=obj.get('base'),
carg=obj.get('carg')
)
def _link(obj):
return Link(obj.get('from'), obj.get('to'),
obj.get('rargname'), obj.get('post'))
def _lnk(o):
return None if o is None else Lnk.charspan(o['from'], o['to'])
return cls(
nodes=[_node(n) for n in d.get('nodes', [])],
links=[_link(l) for l in d.get('links', [])],
lnk=_lnk(d.get('lnk')),
surface=d.get('surface'),
identifier=d.get('identifier')
) | python | def from_dict(cls, d):
"""
Decode a dictionary, as from :meth:`to_dict`, into a Dmrs object.
"""
def _node(obj):
return Node(
obj.get('nodeid'),
Pred.surface_or_abstract(obj.get('predicate')),
sortinfo=obj.get('sortinfo'),
lnk=_lnk(obj.get('lnk')),
surface=obj.get('surface'),
base=obj.get('base'),
carg=obj.get('carg')
)
def _link(obj):
return Link(obj.get('from'), obj.get('to'),
obj.get('rargname'), obj.get('post'))
def _lnk(o):
return None if o is None else Lnk.charspan(o['from'], o['to'])
return cls(
nodes=[_node(n) for n in d.get('nodes', [])],
links=[_link(l) for l in d.get('links', [])],
lnk=_lnk(d.get('lnk')),
surface=d.get('surface'),
identifier=d.get('identifier')
) | Decode a dictionary, as from :meth:`to_dict`, into a Dmrs object. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L1052-L1077 |
delph-in/pydelphin | delphin/mrs/xmrs.py | Dmrs.to_triples | def to_triples(self, short_pred=True, properties=True):
"""
Encode the Dmrs as triples suitable for PENMAN serialization.
"""
ts = []
qs = set(self.nodeids(quantifier=True))
for n in nodes(self):
pred = n.pred.short_form() if short_pred else n.pred.string
ts.append((n.nodeid, 'predicate', pred))
if n.lnk is not None:
ts.append((n.nodeid, 'lnk', '"{}"'.format(str(n.lnk))))
if n.carg is not None:
ts.append((n.nodeid, 'carg', '"{}"'.format(n.carg)))
if properties and n.nodeid not in qs:
for key, value in n.sortinfo.items():
ts.append((n.nodeid, key.lower(), value))
for l in links(self):
if safe_int(l.start) == LTOP_NODEID:
ts.append((l.start, 'top', l.end))
else:
relation = '{}-{}'.format(l.rargname.upper(), l.post)
ts.append((l.start, relation, l.end))
return ts | python | def to_triples(self, short_pred=True, properties=True):
"""
Encode the Dmrs as triples suitable for PENMAN serialization.
"""
ts = []
qs = set(self.nodeids(quantifier=True))
for n in nodes(self):
pred = n.pred.short_form() if short_pred else n.pred.string
ts.append((n.nodeid, 'predicate', pred))
if n.lnk is not None:
ts.append((n.nodeid, 'lnk', '"{}"'.format(str(n.lnk))))
if n.carg is not None:
ts.append((n.nodeid, 'carg', '"{}"'.format(n.carg)))
if properties and n.nodeid not in qs:
for key, value in n.sortinfo.items():
ts.append((n.nodeid, key.lower(), value))
for l in links(self):
if safe_int(l.start) == LTOP_NODEID:
ts.append((l.start, 'top', l.end))
else:
relation = '{}-{}'.format(l.rargname.upper(), l.post)
ts.append((l.start, relation, l.end))
return ts | Encode the Dmrs as triples suitable for PENMAN serialization. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L1079-L1102 |
delph-in/pydelphin | delphin/mrs/xmrs.py | Dmrs.from_triples | def from_triples(cls, triples, remap_nodeids=True):
"""
Decode triples, as from :meth:`to_triples`, into a Dmrs object.
"""
top_nid = str(LTOP_NODEID)
top = lnk = surface = identifier = None
nids, nd, edges = [], {}, []
for src, rel, tgt in triples:
src, tgt = str(src), str(tgt) # hack for int-converted src/tgt
if src == top_nid and rel == 'top':
top = tgt
continue
elif src not in nd:
if top is None:
top=src
nids.append(src)
nd[src] = {'pred': None, 'lnk': None, 'carg': None, 'si': []}
if rel == 'predicate':
nd[src]['pred'] = Pred.surface_or_abstract(tgt)
elif rel == 'lnk':
cfrom, cto = tgt.strip('"<>').split(':')
nd[src]['lnk'] = Lnk.charspan(int(cfrom), int(cto))
elif rel == 'carg':
if (tgt[0], tgt[-1]) == ('"', '"'):
tgt = tgt[1:-1]
nd[src]['carg'] = tgt
elif rel.islower():
nd[src]['si'].append((rel, tgt))
else:
rargname, post = rel.rsplit('-', 1)
edges.append((src, tgt, rargname, post))
if remap_nodeids:
nidmap = dict((nid, FIRST_NODEID+i) for i, nid in enumerate(nids))
else:
nidmap = dict((nid, nid) for nid in nids)
nodes = [
Node(
nodeid=nidmap[nid],
pred=nd[nid]['pred'],
sortinfo=nd[nid]['si'],
lnk=nd[nid]['lnk'],
carg=nd[nid]['carg']
) for i, nid in enumerate(nids)
]
links = [Link(nidmap[s], nidmap[t], r, p) for s, t, r, p in edges]
if top:
links.append(Link(LTOP_NODEID, nidmap[top], None, H_POST))
return cls(
nodes=nodes,
links=links,
lnk=lnk,
surface=surface,
identifier=identifier
) | python | def from_triples(cls, triples, remap_nodeids=True):
"""
Decode triples, as from :meth:`to_triples`, into a Dmrs object.
"""
top_nid = str(LTOP_NODEID)
top = lnk = surface = identifier = None
nids, nd, edges = [], {}, []
for src, rel, tgt in triples:
src, tgt = str(src), str(tgt) # hack for int-converted src/tgt
if src == top_nid and rel == 'top':
top = tgt
continue
elif src not in nd:
if top is None:
top=src
nids.append(src)
nd[src] = {'pred': None, 'lnk': None, 'carg': None, 'si': []}
if rel == 'predicate':
nd[src]['pred'] = Pred.surface_or_abstract(tgt)
elif rel == 'lnk':
cfrom, cto = tgt.strip('"<>').split(':')
nd[src]['lnk'] = Lnk.charspan(int(cfrom), int(cto))
elif rel == 'carg':
if (tgt[0], tgt[-1]) == ('"', '"'):
tgt = tgt[1:-1]
nd[src]['carg'] = tgt
elif rel.islower():
nd[src]['si'].append((rel, tgt))
else:
rargname, post = rel.rsplit('-', 1)
edges.append((src, tgt, rargname, post))
if remap_nodeids:
nidmap = dict((nid, FIRST_NODEID+i) for i, nid in enumerate(nids))
else:
nidmap = dict((nid, nid) for nid in nids)
nodes = [
Node(
nodeid=nidmap[nid],
pred=nd[nid]['pred'],
sortinfo=nd[nid]['si'],
lnk=nd[nid]['lnk'],
carg=nd[nid]['carg']
) for i, nid in enumerate(nids)
]
links = [Link(nidmap[s], nidmap[t], r, p) for s, t, r, p in edges]
if top:
links.append(Link(LTOP_NODEID, nidmap[top], None, H_POST))
return cls(
nodes=nodes,
links=links,
lnk=lnk,
surface=surface,
identifier=identifier
) | Decode triples, as from :meth:`to_triples`, into a Dmrs object. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/xmrs.py#L1105-L1158 |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | Invoice.to_array | def to_array(self):
"""
Serializes this Invoice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Invoice, self).to_array()
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['description'] = u(self.description) # py2: type unicode, py3: type str
array['start_parameter'] = u(self.start_parameter) # py2: type unicode, py3: type str
array['currency'] = u(self.currency) # py2: type unicode, py3: type str
array['total_amount'] = int(self.total_amount) # type int
return array | python | def to_array(self):
"""
Serializes this Invoice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Invoice, self).to_array()
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['description'] = u(self.description) # py2: type unicode, py3: type str
array['start_parameter'] = u(self.start_parameter) # py2: type unicode, py3: type str
array['currency'] = u(self.currency) # py2: type unicode, py3: type str
array['total_amount'] = int(self.total_amount) # type int
return array | Serializes this Invoice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L88-L101 |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | ShippingAddress.to_array | def to_array(self):
"""
Serializes this ShippingAddress to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ShippingAddress, self).to_array()
array['country_code'] = u(self.country_code) # py2: type unicode, py3: type str
array['state'] = u(self.state) # py2: type unicode, py3: type str
array['city'] = u(self.city) # py2: type unicode, py3: type str
array['street_line1'] = u(self.street_line1) # py2: type unicode, py3: type str
array['street_line2'] = u(self.street_line2) # py2: type unicode, py3: type str
array['post_code'] = u(self.post_code) # py2: type unicode, py3: type str
return array | python | def to_array(self):
"""
Serializes this ShippingAddress to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ShippingAddress, self).to_array()
array['country_code'] = u(self.country_code) # py2: type unicode, py3: type str
array['state'] = u(self.state) # py2: type unicode, py3: type str
array['city'] = u(self.city) # py2: type unicode, py3: type str
array['street_line1'] = u(self.street_line1) # py2: type unicode, py3: type str
array['street_line2'] = u(self.street_line2) # py2: type unicode, py3: type str
array['post_code'] = u(self.post_code) # py2: type unicode, py3: type str
return array | Serializes this ShippingAddress to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L243-L257 |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | OrderInfo.to_array | def to_array(self):
"""
Serializes this OrderInfo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(OrderInfo, self).to_array()
if self.name is not None:
array['name'] = u(self.name) # py2: type unicode, py3: type str
if self.phone_number is not None:
array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str
if self.email is not None:
array['email'] = u(self.email) # py2: type unicode, py3: type str
if self.shipping_address is not None:
array['shipping_address'] = self.shipping_address.to_array() # type ShippingAddress
return array | python | def to_array(self):
"""
Serializes this OrderInfo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(OrderInfo, self).to_array()
if self.name is not None:
array['name'] = u(self.name) # py2: type unicode, py3: type str
if self.phone_number is not None:
array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str
if self.email is not None:
array['email'] = u(self.email) # py2: type unicode, py3: type str
if self.shipping_address is not None:
array['shipping_address'] = self.shipping_address.to_array() # type ShippingAddress
return array | Serializes this OrderInfo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L377-L393 |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | OrderInfo.from_array | def from_array(array):
"""
Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['name'] = u(array.get('name')) if array.get('name') 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['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address')) if array.get('shipping_address') is not None else None
data['_raw'] = array
return OrderInfo(**data) | python | def from_array(array):
"""
Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['name'] = u(array.get('name')) if array.get('name') 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['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address')) if array.get('shipping_address') is not None else None
data['_raw'] = array
return OrderInfo(**data) | Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L397-L415 |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | SuccessfulPayment.to_array | def to_array(self):
"""
Serializes this SuccessfulPayment to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(SuccessfulPayment, self).to_array()
array['currency'] = u(self.currency) # py2: type unicode, py3: type str
array['total_amount'] = int(self.total_amount) # type int
array['invoice_payload'] = u(self.invoice_payload) # py2: type unicode, py3: type str
array['telegram_payment_charge_id'] = u(self.telegram_payment_charge_id) # py2: type unicode, py3: type str
array['provider_payment_charge_id'] = u(self.provider_payment_charge_id) # py2: type unicode, py3: type str
if self.shipping_option_id is not None:
array['shipping_option_id'] = u(self.shipping_option_id) # py2: type unicode, py3: type str
if self.order_info is not None:
array['order_info'] = self.order_info.to_array() # type OrderInfo
return array | python | def to_array(self):
"""
Serializes this SuccessfulPayment to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(SuccessfulPayment, self).to_array()
array['currency'] = u(self.currency) # py2: type unicode, py3: type str
array['total_amount'] = int(self.total_amount) # type int
array['invoice_payload'] = u(self.invoice_payload) # py2: type unicode, py3: type str
array['telegram_payment_charge_id'] = u(self.telegram_payment_charge_id) # py2: type unicode, py3: type str
array['provider_payment_charge_id'] = u(self.provider_payment_charge_id) # py2: type unicode, py3: type str
if self.shipping_option_id is not None:
array['shipping_option_id'] = u(self.shipping_option_id) # py2: type unicode, py3: type str
if self.order_info is not None:
array['order_info'] = self.order_info.to_array() # type OrderInfo
return array | Serializes this SuccessfulPayment to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L544-L561 |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | SuccessfulPayment.from_array | def from_array(array):
"""
Deserialize a new SuccessfulPayment from a given dictionary.
:return: new SuccessfulPayment instance.
:rtype: SuccessfulPayment
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['currency'] = u(array.get('currency'))
data['total_amount'] = int(array.get('total_amount'))
data['invoice_payload'] = u(array.get('invoice_payload'))
data['telegram_payment_charge_id'] = u(array.get('telegram_payment_charge_id'))
data['provider_payment_charge_id'] = u(array.get('provider_payment_charge_id'))
data['shipping_option_id'] = u(array.get('shipping_option_id')) if array.get('shipping_option_id') is not None else None
data['order_info'] = OrderInfo.from_array(array.get('order_info')) if array.get('order_info') is not None else None
data['_raw'] = array
return SuccessfulPayment(**data) | python | def from_array(array):
"""
Deserialize a new SuccessfulPayment from a given dictionary.
:return: new SuccessfulPayment instance.
:rtype: SuccessfulPayment
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['currency'] = u(array.get('currency'))
data['total_amount'] = int(array.get('total_amount'))
data['invoice_payload'] = u(array.get('invoice_payload'))
data['telegram_payment_charge_id'] = u(array.get('telegram_payment_charge_id'))
data['provider_payment_charge_id'] = u(array.get('provider_payment_charge_id'))
data['shipping_option_id'] = u(array.get('shipping_option_id')) if array.get('shipping_option_id') is not None else None
data['order_info'] = OrderInfo.from_array(array.get('order_info')) if array.get('order_info') is not None else None
data['_raw'] = array
return SuccessfulPayment(**data) | Deserialize a new SuccessfulPayment from a given dictionary.
:return: new SuccessfulPayment instance.
:rtype: SuccessfulPayment | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L565-L586 |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | ShippingQuery.to_array | def to_array(self):
"""
Serializes this ShippingQuery to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ShippingQuery, self).to_array()
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['from'] = self.from_peer.to_array() # type User
array['invoice_payload'] = u(self.invoice_payload) # py2: type unicode, py3: type str
array['shipping_address'] = self.shipping_address.to_array() # type ShippingAddress
return array | python | def to_array(self):
"""
Serializes this ShippingQuery to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ShippingQuery, self).to_array()
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['from'] = self.from_peer.to_array() # type User
array['invoice_payload'] = u(self.invoice_payload) # py2: type unicode, py3: type str
array['shipping_address'] = self.shipping_address.to_array() # type ShippingAddress
return array | Serializes this ShippingQuery to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L689-L701 |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | ShippingQuery.from_array | def from_array(array):
"""
Deserialize a new ShippingQuery from a given dictionary.
:return: new ShippingQuery instance.
:rtype: ShippingQuery
"""
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['id'] = u(array.get('id'))
data['from_peer'] = User.from_array(array.get('from'))
data['invoice_payload'] = u(array.get('invoice_payload'))
data['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address'))
data['_raw'] = array
return ShippingQuery(**data) | python | def from_array(array):
"""
Deserialize a new ShippingQuery from a given dictionary.
:return: new ShippingQuery instance.
:rtype: ShippingQuery
"""
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['id'] = u(array.get('id'))
data['from_peer'] = User.from_array(array.get('from'))
data['invoice_payload'] = u(array.get('invoice_payload'))
data['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address'))
data['_raw'] = array
return ShippingQuery(**data) | Deserialize a new ShippingQuery from a given dictionary.
:return: new ShippingQuery instance.
:rtype: ShippingQuery | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L705-L724 |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | PreCheckoutQuery.to_array | def to_array(self):
"""
Serializes this PreCheckoutQuery to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PreCheckoutQuery, self).to_array()
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['from'] = self.from_peer.to_array() # type User
array['currency'] = u(self.currency) # py2: type unicode, py3: type str
array['total_amount'] = int(self.total_amount) # type int
array['invoice_payload'] = u(self.invoice_payload) # py2: type unicode, py3: type str
if self.shipping_option_id is not None:
array['shipping_option_id'] = u(self.shipping_option_id) # py2: type unicode, py3: type str
if self.order_info is not None:
array['order_info'] = self.order_info.to_array() # type OrderInfo
return array | python | def to_array(self):
"""
Serializes this PreCheckoutQuery to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PreCheckoutQuery, self).to_array()
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['from'] = self.from_peer.to_array() # type User
array['currency'] = u(self.currency) # py2: type unicode, py3: type str
array['total_amount'] = int(self.total_amount) # type int
array['invoice_payload'] = u(self.invoice_payload) # py2: type unicode, py3: type str
if self.shipping_option_id is not None:
array['shipping_option_id'] = u(self.shipping_option_id) # py2: type unicode, py3: type str
if self.order_info is not None:
array['order_info'] = self.order_info.to_array() # type OrderInfo
return array | Serializes this PreCheckoutQuery to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L854-L871 |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | PreCheckoutQuery.from_array | def from_array(array):
"""
Deserialize a new PreCheckoutQuery from a given dictionary.
:return: new PreCheckoutQuery instance.
:rtype: PreCheckoutQuery
"""
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['id'] = u(array.get('id'))
data['from_peer'] = User.from_array(array.get('from'))
data['currency'] = u(array.get('currency'))
data['total_amount'] = int(array.get('total_amount'))
data['invoice_payload'] = u(array.get('invoice_payload'))
data['shipping_option_id'] = u(array.get('shipping_option_id')) if array.get('shipping_option_id') is not None else None
data['order_info'] = OrderInfo.from_array(array.get('order_info')) if array.get('order_info') is not None else None
data['_raw'] = array
return PreCheckoutQuery(**data) | python | def from_array(array):
"""
Deserialize a new PreCheckoutQuery from a given dictionary.
:return: new PreCheckoutQuery instance.
:rtype: PreCheckoutQuery
"""
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['id'] = u(array.get('id'))
data['from_peer'] = User.from_array(array.get('from'))
data['currency'] = u(array.get('currency'))
data['total_amount'] = int(array.get('total_amount'))
data['invoice_payload'] = u(array.get('invoice_payload'))
data['shipping_option_id'] = u(array.get('shipping_option_id')) if array.get('shipping_option_id') is not None else None
data['order_info'] = OrderInfo.from_array(array.get('order_info')) if array.get('order_info') is not None else None
data['_raw'] = array
return PreCheckoutQuery(**data) | Deserialize a new PreCheckoutQuery from a given dictionary.
:return: new PreCheckoutQuery instance.
:rtype: PreCheckoutQuery | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L875-L897 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/input_media.py | InputMediaPhoto.to_array | def to_array(self):
"""
Serializes this InputMediaPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaPhoto, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # 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
return array | python | def to_array(self):
"""
Serializes this InputMediaPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaPhoto, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # 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
return array | Serializes this InputMediaPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/input_media.py#L72-L90 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/input_media.py | InputMediaAnimation.to_array | def to_array(self):
"""
Serializes this InputMediaAnimation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaAnimation, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # py2: type unicode, py3: type str
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = self.thumb.to_array() # type InputFile
elif isinstance(self.thumb, str):
array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str
else:
raise TypeError('Unknown type, must be one of InputFile, str.')
# end if
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.width is not None:
array['width'] = int(self.width) # type int
if self.height is not None:
array['height'] = int(self.height) # type int
if self.duration is not None:
array['duration'] = int(self.duration) # type int
return array | python | def to_array(self):
"""
Serializes this InputMediaAnimation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaAnimation, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # py2: type unicode, py3: type str
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = self.thumb.to_array() # type InputFile
elif isinstance(self.thumb, str):
array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str
else:
raise TypeError('Unknown type, must be one of InputFile, str.')
# end if
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.width is not None:
array['width'] = int(self.width) # type int
if self.height is not None:
array['height'] = int(self.height) # type int
if self.duration is not None:
array['duration'] = int(self.duration) # type int
return array | Serializes this InputMediaAnimation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/input_media.py#L457-L490 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/input_media.py | InputMediaAudio.to_array | def to_array(self):
"""
Serializes this InputMediaAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaAudio, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # py2: type unicode, py3: type str
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = self.thumb.to_array() # type InputFile
elif isinstance(self.thumb, str):
array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str
else:
raise TypeError('Unknown type, must be one of InputFile, str.')
# end if
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.duration is not None:
array['duration'] = int(self.duration) # type int
if self.performer is not None:
array['performer'] = u(self.performer) # py2: type unicode, py3: type str
if self.title is not None:
array['title'] = u(self.title) # py2: type unicode, py3: type str
return array | python | def to_array(self):
"""
Serializes this InputMediaAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaAudio, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # py2: type unicode, py3: type str
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = self.thumb.to_array() # type InputFile
elif isinstance(self.thumb, str):
array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str
else:
raise TypeError('Unknown type, must be one of InputFile, str.')
# end if
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.duration is not None:
array['duration'] = int(self.duration) # type int
if self.performer is not None:
array['performer'] = u(self.performer) # py2: type unicode, py3: type str
if self.title is not None:
array['title'] = u(self.title) # py2: type unicode, py3: type str
return array | Serializes this InputMediaAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/input_media.py#L658-L693 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/input_media.py | InputMediaDocument.to_array | def to_array(self):
"""
Serializes this InputMediaDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaDocument, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # py2: type unicode, py3: type str
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = self.thumb.to_array() # type InputFile
elif isinstance(self.thumb, str):
array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str
else:
raise TypeError('Unknown type, must be one of InputFile, str.')
# end if
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
return array | python | def to_array(self):
"""
Serializes this InputMediaDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaDocument, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # py2: type unicode, py3: type str
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = self.thumb.to_array() # type InputFile
elif isinstance(self.thumb, str):
array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str
else:
raise TypeError('Unknown type, must be one of InputFile, str.')
# end if
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
return array | Serializes this InputMediaDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/input_media.py#L834-L861 |
delph-in/pydelphin | delphin/mrs/prolog.py | dump | def dump(destination, ms, single=False, pretty_print=False, **kwargs):
"""
Serialize Xmrs objects to the Prolog representation and write to a file.
Args:
destination: filename or file object where data will be written
ms: an iterator of Xmrs objects to serialize (unless the
*single* option is `True`)
single: if `True`, treat *ms* as a single Xmrs object
instead of as an iterator
pretty_print: if `True`, add newlines and indentation
"""
text = dumps(ms,
single=single,
pretty_print=pretty_print,
**kwargs)
if hasattr(destination, 'write'):
print(text, file=destination)
else:
with open(destination, 'w') as fh:
print(text, file=fh) | python | def dump(destination, ms, single=False, pretty_print=False, **kwargs):
"""
Serialize Xmrs objects to the Prolog representation and write to a file.
Args:
destination: filename or file object where data will be written
ms: an iterator of Xmrs objects to serialize (unless the
*single* option is `True`)
single: if `True`, treat *ms* as a single Xmrs object
instead of as an iterator
pretty_print: if `True`, add newlines and indentation
"""
text = dumps(ms,
single=single,
pretty_print=pretty_print,
**kwargs)
if hasattr(destination, 'write'):
print(text, file=destination)
else:
with open(destination, 'w') as fh:
print(text, file=fh) | Serialize Xmrs objects to the Prolog representation and write to a file.
Args:
destination: filename or file object where data will be written
ms: an iterator of Xmrs objects to serialize (unless the
*single* option is `True`)
single: if `True`, treat *ms* as a single Xmrs object
instead of as an iterator
pretty_print: if `True`, add newlines and indentation | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/prolog.py#L32-L53 |
delph-in/pydelphin | delphin/mrs/prolog.py | dumps | def dumps(ms, single=False, pretty_print=False, **kwargs):
"""
Serialize an Xmrs object to the Prolog representation
Args:
ms: an iterator of Xmrs objects to serialize (unless the
*single* option is `True`)
single: if `True`, treat *ms* as a single Xmrs object instead
of as an iterator
pretty_print: if `True`, add newlines and indentation
Returns:
the Prolog string representation of a corpus of Xmrs
"""
if single:
ms = [ms]
return serialize(ms, pretty_print=pretty_print, **kwargs) | python | def dumps(ms, single=False, pretty_print=False, **kwargs):
"""
Serialize an Xmrs object to the Prolog representation
Args:
ms: an iterator of Xmrs objects to serialize (unless the
*single* option is `True`)
single: if `True`, treat *ms* as a single Xmrs object instead
of as an iterator
pretty_print: if `True`, add newlines and indentation
Returns:
the Prolog string representation of a corpus of Xmrs
"""
if single:
ms = [ms]
return serialize(ms, pretty_print=pretty_print, **kwargs) | Serialize an Xmrs object to the Prolog representation
Args:
ms: an iterator of Xmrs objects to serialize (unless the
*single* option is `True`)
single: if `True`, treat *ms* as a single Xmrs object instead
of as an iterator
pretty_print: if `True`, add newlines and indentation
Returns:
the Prolog string representation of a corpus of Xmrs | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/prolog.py#L56-L71 |
delph-in/pydelphin | delphin/mrs/vpm.py | load | def load(source, semi=None):
"""
Read a variable-property mapping from *source* and return the VPM.
Args:
source: a filename or file-like object containing the VPM
definitions
semi (:class:`~delphin.mrs.semi.SemI`, optional): if provided,
it is passed to the VPM constructor
Returns:
a :class:`VPM` instance
"""
if hasattr(source, 'read'):
return _load(source, semi)
else:
with open(source, 'r') as fh:
return _load(fh, semi) | python | def load(source, semi=None):
"""
Read a variable-property mapping from *source* and return the VPM.
Args:
source: a filename or file-like object containing the VPM
definitions
semi (:class:`~delphin.mrs.semi.SemI`, optional): if provided,
it is passed to the VPM constructor
Returns:
a :class:`VPM` instance
"""
if hasattr(source, 'read'):
return _load(source, semi)
else:
with open(source, 'r') as fh:
return _load(fh, semi) | Read a variable-property mapping from *source* and return the VPM.
Args:
source: a filename or file-like object containing the VPM
definitions
semi (:class:`~delphin.mrs.semi.SemI`, optional): if provided,
it is passed to the VPM constructor
Returns:
a :class:`VPM` instance | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/vpm.py#L25-L41 |
delph-in/pydelphin | delphin/mrs/vpm.py | _valmatch | def _valmatch(vs, ss, op, varsort, semi, section):
"""
Return `True` if for every paired *v* and *s* from *vs* and *ss*:
v <> s (subsumption or equality if *semi* is `None`)
v == s (equality)
s == '*'
s == '!' and v == `None`
s == '[xyz]' and varsort == 'xyz'
"""
if op in _EQUAL_OPS or semi is None:
return all(
s == v or # value equality
(s == '*' and v is not None) or # non-null wildcard
(
v is None and ( # value is null (any or with matching varsort)
s == '!' or
(s[0], s[-1], s[1:-1]) == ('[', ']', varsort)
)
)
for v, s in zip(vs, ss)
)
else:
pass | python | def _valmatch(vs, ss, op, varsort, semi, section):
"""
Return `True` if for every paired *v* and *s* from *vs* and *ss*:
v <> s (subsumption or equality if *semi* is `None`)
v == s (equality)
s == '*'
s == '!' and v == `None`
s == '[xyz]' and varsort == 'xyz'
"""
if op in _EQUAL_OPS or semi is None:
return all(
s == v or # value equality
(s == '*' and v is not None) or # non-null wildcard
(
v is None and ( # value is null (any or with matching varsort)
s == '!' or
(s[0], s[-1], s[1:-1]) == ('[', ']', varsort)
)
)
for v, s in zip(vs, ss)
)
else:
pass | Return `True` if for every paired *v* and *s* from *vs* and *ss*:
v <> s (subsumption or equality if *semi* is `None`)
v == s (equality)
s == '*'
s == '!' and v == `None`
s == '[xyz]' and varsort == 'xyz' | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/vpm.py#L151-L173 |
delph-in/pydelphin | delphin/mrs/vpm.py | VPM.apply | def apply(self, var, props, reverse=False):
"""
Apply the VPM to variable *var* and properties *props*.
Args:
var: a variable
props: a dictionary mapping properties to values
reverse: if `True`, apply the rules in reverse (e.g. from
grammar-external to grammar-internal forms)
Returns:
a tuple (v, p) of the mapped variable and properties
"""
vs, vid = sort_vid_split(var)
if reverse:
# variable type mapping is disabled in reverse
# tms = [(b, op, a) for a, op, b in self._typemap if op in _RL_OPS]
tms = []
else:
tms = [(a, op, b) for a, op, b in self._typemap if op in _LR_OPS]
for src, op, tgt in tms:
if _valmatch([vs], src, op, None, self._semi, 'variables'):
vs = vs if tgt == ['*'] else tgt[0]
break
newvar = '{}{}'.format(vs, vid)
newprops = {}
for featsets, valmap in self._propmap:
if reverse:
tgtfeats, srcfeats = featsets
pms = [(b, op, a) for a, op, b in valmap if op in _RL_OPS]
else:
srcfeats, tgtfeats = featsets
pms = [(a, op, b) for a, op, b in valmap if op in _LR_OPS]
vals = [props.get(f) for f in srcfeats]
for srcvals, op, tgtvals in pms:
if _valmatch(vals, srcvals, op, vs, self._semi, 'properties'):
for i, featval in enumerate(zip(tgtfeats, tgtvals)):
k, v = featval
if v == '*':
print(i, len(vals), vals, k, v)
if i < len(vals) and vals[i] is not None:
newprops[k] = vals[i]
elif v != '!':
newprops[k] = v
break
return newvar, newprops | python | def apply(self, var, props, reverse=False):
"""
Apply the VPM to variable *var* and properties *props*.
Args:
var: a variable
props: a dictionary mapping properties to values
reverse: if `True`, apply the rules in reverse (e.g. from
grammar-external to grammar-internal forms)
Returns:
a tuple (v, p) of the mapped variable and properties
"""
vs, vid = sort_vid_split(var)
if reverse:
# variable type mapping is disabled in reverse
# tms = [(b, op, a) for a, op, b in self._typemap if op in _RL_OPS]
tms = []
else:
tms = [(a, op, b) for a, op, b in self._typemap if op in _LR_OPS]
for src, op, tgt in tms:
if _valmatch([vs], src, op, None, self._semi, 'variables'):
vs = vs if tgt == ['*'] else tgt[0]
break
newvar = '{}{}'.format(vs, vid)
newprops = {}
for featsets, valmap in self._propmap:
if reverse:
tgtfeats, srcfeats = featsets
pms = [(b, op, a) for a, op, b in valmap if op in _RL_OPS]
else:
srcfeats, tgtfeats = featsets
pms = [(a, op, b) for a, op, b in valmap if op in _LR_OPS]
vals = [props.get(f) for f in srcfeats]
for srcvals, op, tgtvals in pms:
if _valmatch(vals, srcvals, op, vs, self._semi, 'properties'):
for i, featval in enumerate(zip(tgtfeats, tgtvals)):
k, v = featval
if v == '*':
print(i, len(vals), vals, k, v)
if i < len(vals) and vals[i] is not None:
newprops[k] = vals[i]
elif v != '!':
newprops[k] = v
break
return newvar, newprops | Apply the VPM to variable *var* and properties *props*.
Args:
var: a variable
props: a dictionary mapping properties to values
reverse: if `True`, apply the rules in reverse (e.g. from
grammar-external to grammar-internal forms)
Returns:
a tuple (v, p) of the mapped variable and properties | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/vpm.py#L102-L148 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/payments.py | OrderInfo.from_array | def from_array(array):
"""
Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo
"""
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.payments import ShippingAddress
data = {}
data['name'] = u(array.get('name')) if array.get('name') 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['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address')) if array.get('shipping_address') is not None else None
data['_raw'] = array
return OrderInfo(**data) | python | def from_array(array):
"""
Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo
"""
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.payments import ShippingAddress
data = {}
data['name'] = u(array.get('name')) if array.get('name') 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['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address')) if array.get('shipping_address') is not None else None
data['_raw'] = array
return OrderInfo(**data) | Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/payments.py#L411-L431 |
delph-in/pydelphin | delphin/commands.py | convert | def convert(path, source_fmt, target_fmt, select='result:mrs',
properties=True, show_status=False, predicate_modifiers=False,
color=False, pretty_print=False, indent=None):
"""
Convert between various DELPH-IN Semantics representations.
Args:
path (str, file): filename, testsuite directory, open file, or
stream of input representations
source_fmt (str): convert from this format
target_fmt (str): convert to this format
select (str): TSQL query for selecting data (ignored if *path*
is not a testsuite directory; default: `"result:mrs"`)
properties (bool): include morphosemantic properties if `True`
(default: `True`)
show_status (bool): show disconnected EDS nodes (ignored if
*target_fmt* is not `"eds"`; default: `False`)
predicate_modifiers (bool): apply EDS predicate modification
for certain kinds of patterns (ignored if *target_fmt* is
not an EDS format; default: `False`)
color (bool): apply syntax highlighting if `True` and
*target_fmt* is `"simplemrs"` (default: `False`)
pretty_print (bool): if `True`, format the output with
newlines and default indentation (default: `False`)
indent (int, optional): specifies an explicit number of spaces
for indentation (implies *pretty_print*)
Returns:
str: the converted representation
"""
if source_fmt.startswith('eds') and not target_fmt.startswith('eds'):
raise ValueError(
'Conversion from EDS to non-EDS currently not supported.')
if indent:
pretty_print = True
indent = 4 if indent is True else safe_int(indent)
if len(tsql.inspect_query('select ' + select)['projection']) != 1:
raise ValueError('Exactly 1 column must be given in selection query: '
'(e.g., result:mrs)')
# read
loads = _get_codec(source_fmt)
if path is None:
xs = loads(sys.stdin.read())
elif hasattr(path, 'read'):
xs = loads(path.read())
elif os.path.isdir(path):
ts = itsdb.TestSuite(path)
xs = [
next(iter(loads(r[0])), None)
for r in tsql.select(select, ts)
]
else:
xs = loads(open(path, 'r').read())
# write
dumps = _get_codec(target_fmt, load=False)
kwargs = {}
if color: kwargs['color'] = color
if pretty_print: kwargs['pretty_print'] = pretty_print
if indent: kwargs['indent'] = indent
if target_fmt == 'eds':
kwargs['pretty_print'] = pretty_print
kwargs['show_status'] = show_status
if target_fmt.startswith('eds'):
kwargs['predicate_modifiers'] = predicate_modifiers
kwargs['properties'] = properties
# this is not a great way to improve robustness when converting
# many representations, but it'll do until v1.0.0. Also, it only
# improves robustness on the output, not the input.
# Note that all the code below is to replace the following:
# return dumps(xs, **kwargs)
head, joiner, tail = _get_output_details(target_fmt)
parts = []
if pretty_print:
joiner = joiner.strip() + '\n'
def _trim(s):
if head and s.startswith(head):
s = s[len(head):].lstrip('\n')
if tail and s.endswith(tail):
s = s[:-len(tail)].rstrip('\n')
return s
for x in xs:
try:
s = dumps([x], **kwargs)
except (PyDelphinException, KeyError, IndexError):
logging.exception('could not convert representation')
else:
s = _trim(s)
parts.append(s)
# set these after so head and tail are used correctly in _trim
if pretty_print:
if head:
head += '\n'
if tail:
tail = '\n' + tail
return head + joiner.join(parts) + tail | python | def convert(path, source_fmt, target_fmt, select='result:mrs',
properties=True, show_status=False, predicate_modifiers=False,
color=False, pretty_print=False, indent=None):
"""
Convert between various DELPH-IN Semantics representations.
Args:
path (str, file): filename, testsuite directory, open file, or
stream of input representations
source_fmt (str): convert from this format
target_fmt (str): convert to this format
select (str): TSQL query for selecting data (ignored if *path*
is not a testsuite directory; default: `"result:mrs"`)
properties (bool): include morphosemantic properties if `True`
(default: `True`)
show_status (bool): show disconnected EDS nodes (ignored if
*target_fmt* is not `"eds"`; default: `False`)
predicate_modifiers (bool): apply EDS predicate modification
for certain kinds of patterns (ignored if *target_fmt* is
not an EDS format; default: `False`)
color (bool): apply syntax highlighting if `True` and
*target_fmt* is `"simplemrs"` (default: `False`)
pretty_print (bool): if `True`, format the output with
newlines and default indentation (default: `False`)
indent (int, optional): specifies an explicit number of spaces
for indentation (implies *pretty_print*)
Returns:
str: the converted representation
"""
if source_fmt.startswith('eds') and not target_fmt.startswith('eds'):
raise ValueError(
'Conversion from EDS to non-EDS currently not supported.')
if indent:
pretty_print = True
indent = 4 if indent is True else safe_int(indent)
if len(tsql.inspect_query('select ' + select)['projection']) != 1:
raise ValueError('Exactly 1 column must be given in selection query: '
'(e.g., result:mrs)')
# read
loads = _get_codec(source_fmt)
if path is None:
xs = loads(sys.stdin.read())
elif hasattr(path, 'read'):
xs = loads(path.read())
elif os.path.isdir(path):
ts = itsdb.TestSuite(path)
xs = [
next(iter(loads(r[0])), None)
for r in tsql.select(select, ts)
]
else:
xs = loads(open(path, 'r').read())
# write
dumps = _get_codec(target_fmt, load=False)
kwargs = {}
if color: kwargs['color'] = color
if pretty_print: kwargs['pretty_print'] = pretty_print
if indent: kwargs['indent'] = indent
if target_fmt == 'eds':
kwargs['pretty_print'] = pretty_print
kwargs['show_status'] = show_status
if target_fmt.startswith('eds'):
kwargs['predicate_modifiers'] = predicate_modifiers
kwargs['properties'] = properties
# this is not a great way to improve robustness when converting
# many representations, but it'll do until v1.0.0. Also, it only
# improves robustness on the output, not the input.
# Note that all the code below is to replace the following:
# return dumps(xs, **kwargs)
head, joiner, tail = _get_output_details(target_fmt)
parts = []
if pretty_print:
joiner = joiner.strip() + '\n'
def _trim(s):
if head and s.startswith(head):
s = s[len(head):].lstrip('\n')
if tail and s.endswith(tail):
s = s[:-len(tail)].rstrip('\n')
return s
for x in xs:
try:
s = dumps([x], **kwargs)
except (PyDelphinException, KeyError, IndexError):
logging.exception('could not convert representation')
else:
s = _trim(s)
parts.append(s)
# set these after so head and tail are used correctly in _trim
if pretty_print:
if head:
head += '\n'
if tail:
tail = '\n' + tail
return head + joiner.join(parts) + tail | Convert between various DELPH-IN Semantics representations.
Args:
path (str, file): filename, testsuite directory, open file, or
stream of input representations
source_fmt (str): convert from this format
target_fmt (str): convert to this format
select (str): TSQL query for selecting data (ignored if *path*
is not a testsuite directory; default: `"result:mrs"`)
properties (bool): include morphosemantic properties if `True`
(default: `True`)
show_status (bool): show disconnected EDS nodes (ignored if
*target_fmt* is not `"eds"`; default: `False`)
predicate_modifiers (bool): apply EDS predicate modification
for certain kinds of patterns (ignored if *target_fmt* is
not an EDS format; default: `False`)
color (bool): apply syntax highlighting if `True` and
*target_fmt* is `"simplemrs"` (default: `False`)
pretty_print (bool): if `True`, format the output with
newlines and default indentation (default: `False`)
indent (int, optional): specifies an explicit number of spaces
for indentation (implies *pretty_print*)
Returns:
str: the converted representation | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/commands.py#L29-L127 |
delph-in/pydelphin | delphin/commands.py | select | def select(dataspec, testsuite, mode='list', cast=True):
"""
Select data from [incr tsdb()] profiles.
Args:
query (str): TSQL select query (e.g., `'i-id i-input mrs'` or
`'* from item where readings > 0'`)
testsuite (str, TestSuite): testsuite or path to testsuite
containing data to select
mode (str): see :func:`delphin.itsdb.select_rows` for a
description of the *mode* parameter (default: `list`)
cast (bool): if `True`, cast column values to their datatype
according to the relations file (default: `True`)
Returns:
a generator that yields selected data
"""
if isinstance(testsuite, itsdb.ItsdbProfile):
testsuite = itsdb.TestSuite(testsuite.root)
elif not isinstance(testsuite, itsdb.TestSuite):
testsuite = itsdb.TestSuite(testsuite)
return tsql.select(dataspec, testsuite, mode=mode, cast=cast) | python | def select(dataspec, testsuite, mode='list', cast=True):
"""
Select data from [incr tsdb()] profiles.
Args:
query (str): TSQL select query (e.g., `'i-id i-input mrs'` or
`'* from item where readings > 0'`)
testsuite (str, TestSuite): testsuite or path to testsuite
containing data to select
mode (str): see :func:`delphin.itsdb.select_rows` for a
description of the *mode* parameter (default: `list`)
cast (bool): if `True`, cast column values to their datatype
according to the relations file (default: `True`)
Returns:
a generator that yields selected data
"""
if isinstance(testsuite, itsdb.ItsdbProfile):
testsuite = itsdb.TestSuite(testsuite.root)
elif not isinstance(testsuite, itsdb.TestSuite):
testsuite = itsdb.TestSuite(testsuite)
return tsql.select(dataspec, testsuite, mode=mode, cast=cast) | Select data from [incr tsdb()] profiles.
Args:
query (str): TSQL select query (e.g., `'i-id i-input mrs'` or
`'* from item where readings > 0'`)
testsuite (str, TestSuite): testsuite or path to testsuite
containing data to select
mode (str): see :func:`delphin.itsdb.select_rows` for a
description of the *mode* parameter (default: `list`)
cast (bool): if `True`, cast column values to their datatype
according to the relations file (default: `True`)
Returns:
a generator that yields selected data | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/commands.py#L298-L318 |
delph-in/pydelphin | delphin/commands.py | mkprof | def mkprof(destination, source=None, relations=None, where=None,
in_place=False, skeleton=False, full=False, gzip=False):
"""
Create [incr tsdb()] profiles or skeletons.
Data for the testsuite may come from an existing testsuite or from
a list of sentences. There are four main usage patterns:
- `source="testsuite/"` -- read data from `testsuite/`
- `source=None, in_place=True` -- read data from *destination*
- `source=None, in_place=False` -- read sentences from stdin
- `source="sents.txt"` -- read sentences from `sents.txt`
For the latter two, the *relations* parameter must be specified.
Args:
destination (str): path of the new testsuite
source (str): path to a source testsuite or a file containing
sentences; if not given and *in_place* is `False`,
sentences are read from stdin
relations (str): path to a relations file to use for the
created testsuite; if `None` and *source* is given, the
relations file of the source testsuite is used
where (str): TSQL condition to filter records by; ignored if
*source* is not a testsuite
in_place (bool): if `True` and *source* is not given, use
*destination* as the source for data (default: `False`)
skeleton (bool): if `True`, only write tsdb-core files
(default: `False`)
full (bool): if `True`, copy all data from the source
testsuite (requires *source* to be a testsuite path;
default: `False`)
gzip (bool): if `True`, non-empty tables will be compressed
with gzip
"""
# basic validation
if skeleton and full:
raise ValueError("'skeleton' is incompatible with 'full'")
elif skeleton and in_place:
raise ValueError("'skeleton' is incompatible with 'in_place'")
elif in_place and source is not None:
raise ValueError("'in_place' is incompatible with 'source'")
if in_place:
source = destination
if full and (source is None or not os.path.isdir(source)):
raise ValueError("'full' must be used with a source testsuite")
if relations is None and source is not None and os.path.isdir(source):
relations = os.path.join(source, 'relations')
elif relations is None or not os.path.isfile(relations):
raise ValueError('invalid or missing relations file: {}'
.format(relations))
# setup destination testsuite
_prepare_output_directory(destination)
dts = itsdb.TestSuite(path=destination, relations=relations)
# input is sentences on stdin
if source is None:
dts.write({'item': _lines_to_rows(sys.stdin, dts.relations)},
gzip=gzip)
# input is sentence file
elif os.path.isfile(source):
with open(source) as fh:
dts.write({'item': _lines_to_rows(fh, dts.relations)},
gzip=gzip)
# input is source testsuite
elif os.path.isdir(source):
sts = itsdb.TestSuite(source)
tables = dts.relations.tables if full else itsdb.tsdb_core_files
where = '' if where is None else 'where ' + where
for table in tables:
if sts.size(table) > 0:
# filter the data, but use all if the query fails
# (e.g., if the filter and table cannot be joined)
try:
rows = tsql.select(
'* from {} {}'.format(table, where), sts, cast=False)
except itsdb.ItsdbError:
rows = sts[table]
dts.write({table: rows}, gzip=gzip)
dts.reload()
# unless a skeleton was requested, make empty files for other tables
if not skeleton:
for table in dts.relations:
if len(dts[table]) == 0:
dts.write({table: []})
# summarize what was done
if sys.stdout.isatty():
_red = lambda s: '\x1b[1;31m{}\x1b[0m'.format(s)
else:
_red = lambda s: s
fmt = '{:>8} bytes\t{}'
for filename in ['relations'] + list(dts.relations.tables):
path = os.path.join(destination, filename)
if os.path.isfile(path):
stat = os.stat(path)
print(fmt.format(stat.st_size, filename))
elif os.path.isfile(path + '.gz'):
stat = os.stat(path + '.gz')
print(fmt.format(stat.st_size, _red(filename + '.gz'))) | python | def mkprof(destination, source=None, relations=None, where=None,
in_place=False, skeleton=False, full=False, gzip=False):
"""
Create [incr tsdb()] profiles or skeletons.
Data for the testsuite may come from an existing testsuite or from
a list of sentences. There are four main usage patterns:
- `source="testsuite/"` -- read data from `testsuite/`
- `source=None, in_place=True` -- read data from *destination*
- `source=None, in_place=False` -- read sentences from stdin
- `source="sents.txt"` -- read sentences from `sents.txt`
For the latter two, the *relations* parameter must be specified.
Args:
destination (str): path of the new testsuite
source (str): path to a source testsuite or a file containing
sentences; if not given and *in_place* is `False`,
sentences are read from stdin
relations (str): path to a relations file to use for the
created testsuite; if `None` and *source* is given, the
relations file of the source testsuite is used
where (str): TSQL condition to filter records by; ignored if
*source* is not a testsuite
in_place (bool): if `True` and *source* is not given, use
*destination* as the source for data (default: `False`)
skeleton (bool): if `True`, only write tsdb-core files
(default: `False`)
full (bool): if `True`, copy all data from the source
testsuite (requires *source* to be a testsuite path;
default: `False`)
gzip (bool): if `True`, non-empty tables will be compressed
with gzip
"""
# basic validation
if skeleton and full:
raise ValueError("'skeleton' is incompatible with 'full'")
elif skeleton and in_place:
raise ValueError("'skeleton' is incompatible with 'in_place'")
elif in_place and source is not None:
raise ValueError("'in_place' is incompatible with 'source'")
if in_place:
source = destination
if full and (source is None or not os.path.isdir(source)):
raise ValueError("'full' must be used with a source testsuite")
if relations is None and source is not None and os.path.isdir(source):
relations = os.path.join(source, 'relations')
elif relations is None or not os.path.isfile(relations):
raise ValueError('invalid or missing relations file: {}'
.format(relations))
# setup destination testsuite
_prepare_output_directory(destination)
dts = itsdb.TestSuite(path=destination, relations=relations)
# input is sentences on stdin
if source is None:
dts.write({'item': _lines_to_rows(sys.stdin, dts.relations)},
gzip=gzip)
# input is sentence file
elif os.path.isfile(source):
with open(source) as fh:
dts.write({'item': _lines_to_rows(fh, dts.relations)},
gzip=gzip)
# input is source testsuite
elif os.path.isdir(source):
sts = itsdb.TestSuite(source)
tables = dts.relations.tables if full else itsdb.tsdb_core_files
where = '' if where is None else 'where ' + where
for table in tables:
if sts.size(table) > 0:
# filter the data, but use all if the query fails
# (e.g., if the filter and table cannot be joined)
try:
rows = tsql.select(
'* from {} {}'.format(table, where), sts, cast=False)
except itsdb.ItsdbError:
rows = sts[table]
dts.write({table: rows}, gzip=gzip)
dts.reload()
# unless a skeleton was requested, make empty files for other tables
if not skeleton:
for table in dts.relations:
if len(dts[table]) == 0:
dts.write({table: []})
# summarize what was done
if sys.stdout.isatty():
_red = lambda s: '\x1b[1;31m{}\x1b[0m'.format(s)
else:
_red = lambda s: s
fmt = '{:>8} bytes\t{}'
for filename in ['relations'] + list(dts.relations.tables):
path = os.path.join(destination, filename)
if os.path.isfile(path):
stat = os.stat(path)
print(fmt.format(stat.st_size, filename))
elif os.path.isfile(path + '.gz'):
stat = os.stat(path + '.gz')
print(fmt.format(stat.st_size, _red(filename + '.gz'))) | Create [incr tsdb()] profiles or skeletons.
Data for the testsuite may come from an existing testsuite or from
a list of sentences. There are four main usage patterns:
- `source="testsuite/"` -- read data from `testsuite/`
- `source=None, in_place=True` -- read data from *destination*
- `source=None, in_place=False` -- read sentences from stdin
- `source="sents.txt"` -- read sentences from `sents.txt`
For the latter two, the *relations* parameter must be specified.
Args:
destination (str): path of the new testsuite
source (str): path to a source testsuite or a file containing
sentences; if not given and *in_place* is `False`,
sentences are read from stdin
relations (str): path to a relations file to use for the
created testsuite; if `None` and *source* is given, the
relations file of the source testsuite is used
where (str): TSQL condition to filter records by; ignored if
*source* is not a testsuite
in_place (bool): if `True` and *source* is not given, use
*destination* as the source for data (default: `False`)
skeleton (bool): if `True`, only write tsdb-core files
(default: `False`)
full (bool): if `True`, copy all data from the source
testsuite (requires *source* to be a testsuite path;
default: `False`)
gzip (bool): if `True`, non-empty tables will be compressed
with gzip | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/commands.py#L324-L422 |
delph-in/pydelphin | delphin/commands.py | process | def process(grammar, testsuite, source=None, select=None,
generate=False, transfer=False, options=None,
all_items=False, result_id=None, gzip=False):
"""
Process (e.g., parse) a [incr tsdb()] profile.
Results are written to directly to *testsuite*.
If *select* is `None`, the defaults depend on the task:
========== =========================
Task Default value of *select*
========== =========================
Parsing `item:i-input`
Transfer `result:mrs`
Generation `result:mrs`
========== =========================
Args:
grammar (str): path to a compiled grammar image
testsuite (str): path to a [incr tsdb()] testsuite where data
will be read from (see *source*) and written to
source (str): path to a [incr tsdb()] testsuite; if `None`,
*testsuite* is used as the source of data
select (str): TSQL query for selecting processor inputs
(default depends on the processor type)
generate (bool): if `True`, generate instead of parse
(default: `False`)
transfer (bool): if `True`, transfer instead of parse
(default: `False`)
options (list): list of ACE command-line options to use when
invoking the ACE subprocess; unsupported options will
give an error message
all_items (bool): if `True`, don't exclude ignored items
(those with `i-wf==2`) when parsing
result_id (int): if given, only keep items with the specified
`result-id`
gzip (bool): if `True`, non-empty tables will be compressed
with gzip
"""
from delphin.interfaces import ace
if generate and transfer:
raise ValueError("'generate' is incompatible with 'transfer'")
if source is None:
source = testsuite
if select is None:
select = 'result:mrs' if (generate or transfer) else 'item:i-input'
if generate:
processor = ace.AceGenerator
elif transfer:
processor = ace.AceTransferer
else:
if not all_items:
select += ' where i-wf != 2'
processor = ace.AceParser
if result_id is not None:
select += ' where result-id == {}'.format(result_id)
source = itsdb.TestSuite(source)
target = itsdb.TestSuite(testsuite)
column, tablename, condition = _interpret_selection(select, source)
table = itsdb.Table(
source[tablename].fields,
tsql.select(
'* from {} {}'.format(tablename, condition),
source,
cast=False))
with processor(grammar, cmdargs=options) as cpu:
target.process(cpu, ':' + column, source=table, gzip=gzip) | python | def process(grammar, testsuite, source=None, select=None,
generate=False, transfer=False, options=None,
all_items=False, result_id=None, gzip=False):
"""
Process (e.g., parse) a [incr tsdb()] profile.
Results are written to directly to *testsuite*.
If *select* is `None`, the defaults depend on the task:
========== =========================
Task Default value of *select*
========== =========================
Parsing `item:i-input`
Transfer `result:mrs`
Generation `result:mrs`
========== =========================
Args:
grammar (str): path to a compiled grammar image
testsuite (str): path to a [incr tsdb()] testsuite where data
will be read from (see *source*) and written to
source (str): path to a [incr tsdb()] testsuite; if `None`,
*testsuite* is used as the source of data
select (str): TSQL query for selecting processor inputs
(default depends on the processor type)
generate (bool): if `True`, generate instead of parse
(default: `False`)
transfer (bool): if `True`, transfer instead of parse
(default: `False`)
options (list): list of ACE command-line options to use when
invoking the ACE subprocess; unsupported options will
give an error message
all_items (bool): if `True`, don't exclude ignored items
(those with `i-wf==2`) when parsing
result_id (int): if given, only keep items with the specified
`result-id`
gzip (bool): if `True`, non-empty tables will be compressed
with gzip
"""
from delphin.interfaces import ace
if generate and transfer:
raise ValueError("'generate' is incompatible with 'transfer'")
if source is None:
source = testsuite
if select is None:
select = 'result:mrs' if (generate or transfer) else 'item:i-input'
if generate:
processor = ace.AceGenerator
elif transfer:
processor = ace.AceTransferer
else:
if not all_items:
select += ' where i-wf != 2'
processor = ace.AceParser
if result_id is not None:
select += ' where result-id == {}'.format(result_id)
source = itsdb.TestSuite(source)
target = itsdb.TestSuite(testsuite)
column, tablename, condition = _interpret_selection(select, source)
table = itsdb.Table(
source[tablename].fields,
tsql.select(
'* from {} {}'.format(tablename, condition),
source,
cast=False))
with processor(grammar, cmdargs=options) as cpu:
target.process(cpu, ':' + column, source=table, gzip=gzip) | Process (e.g., parse) a [incr tsdb()] profile.
Results are written to directly to *testsuite*.
If *select* is `None`, the defaults depend on the task:
========== =========================
Task Default value of *select*
========== =========================
Parsing `item:i-input`
Transfer `result:mrs`
Generation `result:mrs`
========== =========================
Args:
grammar (str): path to a compiled grammar image
testsuite (str): path to a [incr tsdb()] testsuite where data
will be read from (see *source*) and written to
source (str): path to a [incr tsdb()] testsuite; if `None`,
*testsuite* is used as the source of data
select (str): TSQL query for selecting processor inputs
(default depends on the processor type)
generate (bool): if `True`, generate instead of parse
(default: `False`)
transfer (bool): if `True`, transfer instead of parse
(default: `False`)
options (list): list of ACE command-line options to use when
invoking the ACE subprocess; unsupported options will
give an error message
all_items (bool): if `True`, don't exclude ignored items
(those with `i-wf==2`) when parsing
result_id (int): if given, only keep items with the specified
`result-id`
gzip (bool): if `True`, non-empty tables will be compressed
with gzip | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/commands.py#L448-L518 |
delph-in/pydelphin | delphin/commands.py | repp | def repp(file, config=None, module=None, active=None,
format=None, trace_level=0):
"""
Tokenize with a Regular Expression PreProcessor (REPP).
Results are printed directly to stdout. If more programmatic
access is desired, the :mod:`delphin.repp` module provides a
similar interface.
Args:
file (str, file): filename, open file, or stream of sentence
inputs
config (str): path to a PET REPP configuration (.set) file
module (str): path to a top-level REPP module; other modules
are found by external group calls
active (list): select which modules are active; if `None`, all
are used; incompatible with *config* (default: `None`)
format (str): the output format (`"yy"`, `"string"`, `"line"`,
or `"triple"`; default: `"yy"`)
trace_level (int): if `0` no trace info is printed; if `1`,
applied rules are printed, if greather than `1`, both
applied and unapplied rules (in order) are printed
(default: `0`)
"""
from delphin.repp import REPP
if config is not None and module is not None:
raise ValueError("cannot specify both 'config' and 'module'")
if config is not None and active:
raise ValueError("'active' cannot be used with 'config'")
if config:
r = REPP.from_config(config)
elif module:
r = REPP.from_file(module, active=active)
else:
r = REPP() # just tokenize
if hasattr(file, 'read'):
for line in file:
_repp(r, line, format, trace_level)
else:
with io.open(file, encoding='utf-8') as fh:
for line in fh:
_repp(r, line, format, trace_level) | python | def repp(file, config=None, module=None, active=None,
format=None, trace_level=0):
"""
Tokenize with a Regular Expression PreProcessor (REPP).
Results are printed directly to stdout. If more programmatic
access is desired, the :mod:`delphin.repp` module provides a
similar interface.
Args:
file (str, file): filename, open file, or stream of sentence
inputs
config (str): path to a PET REPP configuration (.set) file
module (str): path to a top-level REPP module; other modules
are found by external group calls
active (list): select which modules are active; if `None`, all
are used; incompatible with *config* (default: `None`)
format (str): the output format (`"yy"`, `"string"`, `"line"`,
or `"triple"`; default: `"yy"`)
trace_level (int): if `0` no trace info is printed; if `1`,
applied rules are printed, if greather than `1`, both
applied and unapplied rules (in order) are printed
(default: `0`)
"""
from delphin.repp import REPP
if config is not None and module is not None:
raise ValueError("cannot specify both 'config' and 'module'")
if config is not None and active:
raise ValueError("'active' cannot be used with 'config'")
if config:
r = REPP.from_config(config)
elif module:
r = REPP.from_file(module, active=active)
else:
r = REPP() # just tokenize
if hasattr(file, 'read'):
for line in file:
_repp(r, line, format, trace_level)
else:
with io.open(file, encoding='utf-8') as fh:
for line in fh:
_repp(r, line, format, trace_level) | Tokenize with a Regular Expression PreProcessor (REPP).
Results are printed directly to stdout. If more programmatic
access is desired, the :mod:`delphin.repp` module provides a
similar interface.
Args:
file (str, file): filename, open file, or stream of sentence
inputs
config (str): path to a PET REPP configuration (.set) file
module (str): path to a top-level REPP module; other modules
are found by external group calls
active (list): select which modules are active; if `None`, all
are used; incompatible with *config* (default: `None`)
format (str): the output format (`"yy"`, `"string"`, `"line"`,
or `"triple"`; default: `"yy"`)
trace_level (int): if `0` no trace info is printed; if `1`,
applied rules are printed, if greather than `1`, both
applied and unapplied rules (in order) are printed
(default: `0`) | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/commands.py#L544-L587 |
delph-in/pydelphin | delphin/commands.py | compare | def compare(testsuite, gold, select='i-id i-input mrs'):
"""
Compare two [incr tsdb()] profiles.
Args:
testsuite (str, TestSuite): path to the test [incr tsdb()]
testsuite or a :class:`TestSuite` object
gold (str, TestSuite): path to the gold [incr tsdb()]
testsuite or a :class:`TestSuite` object
select: TSQL query to select (id, input, mrs) triples
(default: `i-id i-input mrs`)
Yields:
dict: Comparison results as::
{"id": "item identifier",
"input": "input sentence",
"test": number_of_unique_results_in_test,
"shared": number_of_shared_results,
"gold": number_of_unique_results_in_gold}
"""
from delphin.mrs import simplemrs, compare as mrs_compare
if not isinstance(testsuite, itsdb.TestSuite):
if isinstance(testsuite, itsdb.ItsdbProfile):
testsuite = testsuite.root
testsuite = itsdb.TestSuite(testsuite)
if not isinstance(gold, itsdb.TestSuite):
if isinstance(gold, itsdb.ItsdbProfile):
gold = gold.root
gold = itsdb.TestSuite(gold)
queryobj = tsql.inspect_query('select ' + select)
if len(queryobj['projection']) != 3:
raise ValueError('select does not return 3 fields: ' + select)
input_select = '{} {}'.format(queryobj['projection'][0],
queryobj['projection'][1])
i_inputs = dict(tsql.select(input_select, testsuite))
matched_rows = itsdb.match_rows(
tsql.select(select, testsuite),
tsql.select(select, gold),
0)
for (key, testrows, goldrows) in matched_rows:
(test_unique, shared, gold_unique) = mrs_compare.compare_bags(
[simplemrs.loads_one(row[2]) for row in testrows],
[simplemrs.loads_one(row[2]) for row in goldrows])
yield {'id': key,
'input': i_inputs[key],
'test': test_unique,
'shared': shared,
'gold': gold_unique} | python | def compare(testsuite, gold, select='i-id i-input mrs'):
"""
Compare two [incr tsdb()] profiles.
Args:
testsuite (str, TestSuite): path to the test [incr tsdb()]
testsuite or a :class:`TestSuite` object
gold (str, TestSuite): path to the gold [incr tsdb()]
testsuite or a :class:`TestSuite` object
select: TSQL query to select (id, input, mrs) triples
(default: `i-id i-input mrs`)
Yields:
dict: Comparison results as::
{"id": "item identifier",
"input": "input sentence",
"test": number_of_unique_results_in_test,
"shared": number_of_shared_results,
"gold": number_of_unique_results_in_gold}
"""
from delphin.mrs import simplemrs, compare as mrs_compare
if not isinstance(testsuite, itsdb.TestSuite):
if isinstance(testsuite, itsdb.ItsdbProfile):
testsuite = testsuite.root
testsuite = itsdb.TestSuite(testsuite)
if not isinstance(gold, itsdb.TestSuite):
if isinstance(gold, itsdb.ItsdbProfile):
gold = gold.root
gold = itsdb.TestSuite(gold)
queryobj = tsql.inspect_query('select ' + select)
if len(queryobj['projection']) != 3:
raise ValueError('select does not return 3 fields: ' + select)
input_select = '{} {}'.format(queryobj['projection'][0],
queryobj['projection'][1])
i_inputs = dict(tsql.select(input_select, testsuite))
matched_rows = itsdb.match_rows(
tsql.select(select, testsuite),
tsql.select(select, gold),
0)
for (key, testrows, goldrows) in matched_rows:
(test_unique, shared, gold_unique) = mrs_compare.compare_bags(
[simplemrs.loads_one(row[2]) for row in testrows],
[simplemrs.loads_one(row[2]) for row in goldrows])
yield {'id': key,
'input': i_inputs[key],
'test': test_unique,
'shared': shared,
'gold': gold_unique} | Compare two [incr tsdb()] profiles.
Args:
testsuite (str, TestSuite): path to the test [incr tsdb()]
testsuite or a :class:`TestSuite` object
gold (str, TestSuite): path to the gold [incr tsdb()]
testsuite or a :class:`TestSuite` object
select: TSQL query to select (id, input, mrs) triples
(default: `i-id i-input mrs`)
Yields:
dict: Comparison results as::
{"id": "item identifier",
"input": "input sentence",
"test": number_of_unique_results_in_test,
"shared": number_of_shared_results,
"gold": number_of_unique_results_in_gold} | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/commands.py#L625-L678 |
delph-in/pydelphin | delphin/mrs/eds.py | non_argument_modifiers | def non_argument_modifiers(role='ARG1', only_connecting=True):
"""
Return a function that finds non-argument modifier dependencies.
Args:
role (str): the role that is assigned to the dependency
only_connecting (bool): if `True`, only return dependencies
that connect separate components in the basic dependencies;
if `False`, all non-argument modifier dependencies are
included
Returns:
a function with signature `func(xmrs, deps)` that returns a
mapping of non-argument modifier dependencies
Examples:
The default function behaves like the LKB:
>>> func = non_argument_modifiers()
A variation is similar to DMRS's MOD/EQ links:
>>> func = non_argument_modifiers(role="MOD", only_connecting=False)
"""
def func(xmrs, deps):
edges = []
for src in deps:
for _, tgt in deps[src]:
edges.append((src, tgt))
components = _connected_components(xmrs.nodeids(), edges)
ccmap = {}
for i, component in enumerate(components):
for n in component:
ccmap[n] = i
addl = {}
if not only_connecting or len(components) > 1:
lsh = xmrs.labelset_heads
lblheads = {v: lsh(v) for v, vd in xmrs._vars.items()
if 'LBL' in vd['refs']}
for heads in lblheads.values():
if len(heads) > 1:
first = heads[0]
joined = set([ccmap[first]])
for other in heads[1:]:
occ = ccmap[other]
srt = var_sort(xmrs.args(other).get(role, 'u0'))
needs_edge = not only_connecting or occ not in joined
edge_available = srt == 'u'
if needs_edge and edge_available:
addl.setdefault(other, []).append((role, first))
joined.add(occ)
return addl
return func | python | def non_argument_modifiers(role='ARG1', only_connecting=True):
"""
Return a function that finds non-argument modifier dependencies.
Args:
role (str): the role that is assigned to the dependency
only_connecting (bool): if `True`, only return dependencies
that connect separate components in the basic dependencies;
if `False`, all non-argument modifier dependencies are
included
Returns:
a function with signature `func(xmrs, deps)` that returns a
mapping of non-argument modifier dependencies
Examples:
The default function behaves like the LKB:
>>> func = non_argument_modifiers()
A variation is similar to DMRS's MOD/EQ links:
>>> func = non_argument_modifiers(role="MOD", only_connecting=False)
"""
def func(xmrs, deps):
edges = []
for src in deps:
for _, tgt in deps[src]:
edges.append((src, tgt))
components = _connected_components(xmrs.nodeids(), edges)
ccmap = {}
for i, component in enumerate(components):
for n in component:
ccmap[n] = i
addl = {}
if not only_connecting or len(components) > 1:
lsh = xmrs.labelset_heads
lblheads = {v: lsh(v) for v, vd in xmrs._vars.items()
if 'LBL' in vd['refs']}
for heads in lblheads.values():
if len(heads) > 1:
first = heads[0]
joined = set([ccmap[first]])
for other in heads[1:]:
occ = ccmap[other]
srt = var_sort(xmrs.args(other).get(role, 'u0'))
needs_edge = not only_connecting or occ not in joined
edge_available = srt == 'u'
if needs_edge and edge_available:
addl.setdefault(other, []).append((role, first))
joined.add(occ)
return addl
return func | Return a function that finds non-argument modifier dependencies.
Args:
role (str): the role that is assigned to the dependency
only_connecting (bool): if `True`, only return dependencies
that connect separate components in the basic dependencies;
if `False`, all non-argument modifier dependencies are
included
Returns:
a function with signature `func(xmrs, deps)` that returns a
mapping of non-argument modifier dependencies
Examples:
The default function behaves like the LKB:
>>> func = non_argument_modifiers()
A variation is similar to DMRS's MOD/EQ links:
>>> func = non_argument_modifiers(role="MOD", only_connecting=False) | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L277-L332 |
delph-in/pydelphin | delphin/mrs/eds.py | load | def load(fh, single=False):
"""
Deserialize :class:`Eds` from a file (handle or filename)
Args:
fh (str, file): input filename or file object
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of :class:`Eds` objects (unless the *single* option
is `True`)
"""
if isinstance(fh, stringtypes):
s = open(fh, 'r').read()
else:
s = fh.read()
return loads(s, single=single) | python | def load(fh, single=False):
"""
Deserialize :class:`Eds` from a file (handle or filename)
Args:
fh (str, file): input filename or file object
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of :class:`Eds` objects (unless the *single* option
is `True`)
"""
if isinstance(fh, stringtypes):
s = open(fh, 'r').read()
else:
s = fh.read()
return loads(s, single=single) | Deserialize :class:`Eds` from a file (handle or filename)
Args:
fh (str, file): input filename or file object
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of :class:`Eds` objects (unless the *single* option
is `True`) | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L370-L385 |
delph-in/pydelphin | delphin/mrs/eds.py | loads | def loads(s, single=False):
"""
Deserialize :class:`Eds` string representations
Args:
s (str): Eds string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of :class:`Eds` objects (unless the *single* option
is `True`)
"""
es = deserialize(s)
if single:
return next(es)
return es | python | def loads(s, single=False):
"""
Deserialize :class:`Eds` string representations
Args:
s (str): Eds string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of :class:`Eds` objects (unless the *single* option
is `True`)
"""
es = deserialize(s)
if single:
return next(es)
return es | Deserialize :class:`Eds` string representations
Args:
s (str): Eds string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of :class:`Eds` objects (unless the *single* option
is `True`) | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L388-L402 |
delph-in/pydelphin | delphin/mrs/eds.py | dumps | def dumps(ms, single=False,
properties=False, pretty_print=True,
show_status=False, predicate_modifiers=False, **kwargs):
"""
Serialize an Xmrs object to a Eds representation
Args:
ms: an iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize (unless the *single* option is `True`)
single (bool): if `True`, treat *ms* as a single
:class:`~delphin.mrs.xmrs.Xmrs` object instead of as an
iterator
properties (bool): if `False`, suppress variable properties
pretty_print (bool): if `True`, add newlines and indentation
show_status (bool): if `True`, annotate disconnected graphs and
nodes
Returns:
an :class:`Eds` string representation of a corpus of Xmrs
"""
if not pretty_print and kwargs.get('indent'):
pretty_print = True
if single:
ms = [ms]
return serialize(
ms,
properties=properties,
pretty_print=pretty_print,
show_status=show_status,
predicate_modifiers=predicate_modifiers,
**kwargs
) | python | def dumps(ms, single=False,
properties=False, pretty_print=True,
show_status=False, predicate_modifiers=False, **kwargs):
"""
Serialize an Xmrs object to a Eds representation
Args:
ms: an iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize (unless the *single* option is `True`)
single (bool): if `True`, treat *ms* as a single
:class:`~delphin.mrs.xmrs.Xmrs` object instead of as an
iterator
properties (bool): if `False`, suppress variable properties
pretty_print (bool): if `True`, add newlines and indentation
show_status (bool): if `True`, annotate disconnected graphs and
nodes
Returns:
an :class:`Eds` string representation of a corpus of Xmrs
"""
if not pretty_print and kwargs.get('indent'):
pretty_print = True
if single:
ms = [ms]
return serialize(
ms,
properties=properties,
pretty_print=pretty_print,
show_status=show_status,
predicate_modifiers=predicate_modifiers,
**kwargs
) | Serialize an Xmrs object to a Eds representation
Args:
ms: an iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize (unless the *single* option is `True`)
single (bool): if `True`, treat *ms* as a single
:class:`~delphin.mrs.xmrs.Xmrs` object instead of as an
iterator
properties (bool): if `False`, suppress variable properties
pretty_print (bool): if `True`, add newlines and indentation
show_status (bool): if `True`, annotate disconnected graphs and
nodes
Returns:
an :class:`Eds` string representation of a corpus of Xmrs | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L438-L468 |
delph-in/pydelphin | delphin/mrs/eds.py | Eds.from_xmrs | def from_xmrs(cls, xmrs, predicate_modifiers=False, **kwargs):
"""
Instantiate an Eds from an Xmrs (lossy conversion).
Args:
xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): Xmrs instance to
convert from
predicate_modifiers (function, bool): function that is
called as `func(xmrs, deps)` after finding the basic
dependencies (`deps`), returning a mapping of
predicate-modifier dependencies; the form of `deps` and
the returned mapping are `{head: [(role, dependent)]}`;
if *predicate_modifiers* is `True`, the function is
created using :func:`non_argument_modifiers` as:
`non_argument_modifiers(role="ARG1", connecting=True);
if *predicate_modifiers* is `False`, only the basic
dependencies are returned
"""
eps = xmrs.eps()
deps = _find_basic_dependencies(xmrs, eps)
# if requested, find additional dependencies not captured already
if predicate_modifiers is True:
func = non_argument_modifiers(role='ARG1', only_connecting=True)
addl_deps = func(xmrs, deps)
elif predicate_modifiers is False or predicate_modifiers is None:
addl_deps = {}
elif hasattr(predicate_modifiers, '__call__'):
addl_deps = predicate_modifiers(xmrs, deps)
else:
raise TypeError('a boolean or callable is required')
for nid, deplist in addl_deps.items():
deps.setdefault(nid, []).extend(deplist)
ids = _unique_ids(eps, deps)
root = _find_root(xmrs)
if root is not None:
root = ids[root]
nodes = [Node(ids[n.nodeid], *n[1:]) for n in make_nodes(xmrs)]
edges = [(ids[a], rarg, ids[b]) for a, deplist in deps.items()
for rarg, b in deplist]
return cls(top=root, nodes=nodes, edges=edges) | python | def from_xmrs(cls, xmrs, predicate_modifiers=False, **kwargs):
"""
Instantiate an Eds from an Xmrs (lossy conversion).
Args:
xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): Xmrs instance to
convert from
predicate_modifiers (function, bool): function that is
called as `func(xmrs, deps)` after finding the basic
dependencies (`deps`), returning a mapping of
predicate-modifier dependencies; the form of `deps` and
the returned mapping are `{head: [(role, dependent)]}`;
if *predicate_modifiers* is `True`, the function is
created using :func:`non_argument_modifiers` as:
`non_argument_modifiers(role="ARG1", connecting=True);
if *predicate_modifiers* is `False`, only the basic
dependencies are returned
"""
eps = xmrs.eps()
deps = _find_basic_dependencies(xmrs, eps)
# if requested, find additional dependencies not captured already
if predicate_modifiers is True:
func = non_argument_modifiers(role='ARG1', only_connecting=True)
addl_deps = func(xmrs, deps)
elif predicate_modifiers is False or predicate_modifiers is None:
addl_deps = {}
elif hasattr(predicate_modifiers, '__call__'):
addl_deps = predicate_modifiers(xmrs, deps)
else:
raise TypeError('a boolean or callable is required')
for nid, deplist in addl_deps.items():
deps.setdefault(nid, []).extend(deplist)
ids = _unique_ids(eps, deps)
root = _find_root(xmrs)
if root is not None:
root = ids[root]
nodes = [Node(ids[n.nodeid], *n[1:]) for n in make_nodes(xmrs)]
edges = [(ids[a], rarg, ids[b]) for a, deplist in deps.items()
for rarg, b in deplist]
return cls(top=root, nodes=nodes, edges=edges) | Instantiate an Eds from an Xmrs (lossy conversion).
Args:
xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): Xmrs instance to
convert from
predicate_modifiers (function, bool): function that is
called as `func(xmrs, deps)` after finding the basic
dependencies (`deps`), returning a mapping of
predicate-modifier dependencies; the form of `deps` and
the returned mapping are `{head: [(role, dependent)]}`;
if *predicate_modifiers* is `True`, the function is
created using :func:`non_argument_modifiers` as:
`non_argument_modifiers(role="ARG1", connecting=True);
if *predicate_modifiers* is `False`, only the basic
dependencies are returned | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L67-L110 |
delph-in/pydelphin | delphin/mrs/eds.py | Eds.nodes | def nodes(self):
"""Return the list of nodes."""
getnode = self._nodes.__getitem__
return [getnode(nid) for nid in self._nodeids] | python | def nodes(self):
"""Return the list of nodes."""
getnode = self._nodes.__getitem__
return [getnode(nid) for nid in self._nodeids] | Return the list of nodes. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L129-L132 |
delph-in/pydelphin | delphin/mrs/eds.py | Eds.to_dict | def to_dict(self, properties=True):
"""
Encode the Eds as a dictionary suitable for JSON serialization.
"""
nodes = {}
for node in self.nodes():
nd = {
'label': node.pred.short_form(),
'edges': self.edges(node.nodeid)
}
if node.lnk is not None:
nd['lnk'] = {'from': node.cfrom, 'to': node.cto}
if properties:
if node.cvarsort is not None:
nd['type'] = node.cvarsort
props = node.properties
if props:
nd['properties'] = props
if node.carg is not None:
nd['carg'] = node.carg
nodes[node.nodeid] = nd
return {'top': self.top, 'nodes': nodes} | python | def to_dict(self, properties=True):
"""
Encode the Eds as a dictionary suitable for JSON serialization.
"""
nodes = {}
for node in self.nodes():
nd = {
'label': node.pred.short_form(),
'edges': self.edges(node.nodeid)
}
if node.lnk is not None:
nd['lnk'] = {'from': node.cfrom, 'to': node.cto}
if properties:
if node.cvarsort is not None:
nd['type'] = node.cvarsort
props = node.properties
if props:
nd['properties'] = props
if node.carg is not None:
nd['carg'] = node.carg
nodes[node.nodeid] = nd
return {'top': self.top, 'nodes': nodes} | Encode the Eds as a dictionary suitable for JSON serialization. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L138-L159 |
delph-in/pydelphin | delphin/mrs/eds.py | Eds.from_dict | def from_dict(cls, d):
"""
Decode a dictionary, as from :meth:`to_dict`, into an Eds object.
"""
makepred, charspan = Pred.surface_or_abstract, Lnk.charspan
top = d.get('top')
nodes, edges = [], []
for nid, node in d.get('nodes', {}).items():
props = node.get('properties', {})
if 'type' in node:
props[CVARSORT] = node['type']
if not props:
props = None
lnk = None
if 'lnk' in node:
lnk = charspan(node['lnk']['from'], node['lnk']['to'])
nodes.append(
Node(
nodeid=nid,
pred=makepred(node['label']),
sortinfo=props,
lnk=lnk,
carg=node.get('carg')
)
)
edges.extend(
(nid, rargname, tgtnid)
for rargname, tgtnid in node.get('edges', {}).items()
)
nodes.sort(key=lambda n: (n.cfrom, -n.cto))
return cls(top, nodes=nodes, edges=edges) | python | def from_dict(cls, d):
"""
Decode a dictionary, as from :meth:`to_dict`, into an Eds object.
"""
makepred, charspan = Pred.surface_or_abstract, Lnk.charspan
top = d.get('top')
nodes, edges = [], []
for nid, node in d.get('nodes', {}).items():
props = node.get('properties', {})
if 'type' in node:
props[CVARSORT] = node['type']
if not props:
props = None
lnk = None
if 'lnk' in node:
lnk = charspan(node['lnk']['from'], node['lnk']['to'])
nodes.append(
Node(
nodeid=nid,
pred=makepred(node['label']),
sortinfo=props,
lnk=lnk,
carg=node.get('carg')
)
)
edges.extend(
(nid, rargname, tgtnid)
for rargname, tgtnid in node.get('edges', {}).items()
)
nodes.sort(key=lambda n: (n.cfrom, -n.cto))
return cls(top, nodes=nodes, edges=edges) | Decode a dictionary, as from :meth:`to_dict`, into an Eds object. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L162-L192 |
delph-in/pydelphin | delphin/mrs/eds.py | Eds.to_triples | def to_triples(self, short_pred=True, properties=True):
"""
Encode the Eds as triples suitable for PENMAN serialization.
"""
node_triples, edge_triples = [], []
# sort nodeids just so top var is first
nodes = sorted(self.nodes(), key=lambda n: n.nodeid != self.top)
for node in nodes:
nid = node.nodeid
pred = node.pred.short_form() if short_pred else node.pred.string
node_triples.append((nid, 'predicate', pred))
if node.lnk:
node_triples.append((nid, 'lnk', '"{}"'.format(str(node.lnk))))
if node.carg:
node_triples.append((nid, 'carg', '"{}"'.format(node.carg)))
if properties:
if node.cvarsort is not None:
node_triples.append((nid, 'type', node.cvarsort))
props = node.properties
node_triples.extend((nid, p, v) for p, v in props.items())
edge_triples.extend(
(nid, rargname, tgt)
for rargname, tgt in sorted(
self.edges(nid).items(),
key=lambda x: rargname_sortkey(x[0])
)
)
return node_triples + edge_triples | python | def to_triples(self, short_pred=True, properties=True):
"""
Encode the Eds as triples suitable for PENMAN serialization.
"""
node_triples, edge_triples = [], []
# sort nodeids just so top var is first
nodes = sorted(self.nodes(), key=lambda n: n.nodeid != self.top)
for node in nodes:
nid = node.nodeid
pred = node.pred.short_form() if short_pred else node.pred.string
node_triples.append((nid, 'predicate', pred))
if node.lnk:
node_triples.append((nid, 'lnk', '"{}"'.format(str(node.lnk))))
if node.carg:
node_triples.append((nid, 'carg', '"{}"'.format(node.carg)))
if properties:
if node.cvarsort is not None:
node_triples.append((nid, 'type', node.cvarsort))
props = node.properties
node_triples.extend((nid, p, v) for p, v in props.items())
edge_triples.extend(
(nid, rargname, tgt)
for rargname, tgt in sorted(
self.edges(nid).items(),
key=lambda x: rargname_sortkey(x[0])
)
)
return node_triples + edge_triples | Encode the Eds as triples suitable for PENMAN serialization. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L194-L221 |
delph-in/pydelphin | delphin/mrs/eds.py | Eds.from_triples | def from_triples(cls, triples):
"""
Decode triples, as from :meth:`to_triples`, into an Eds object.
"""
nids, nd, edges = [], {}, []
for src, rel, tgt in triples:
if src not in nd:
nids.append(src)
nd[src] = {'pred': None, 'lnk': None, 'carg': None, 'si': []}
if rel == 'predicate':
nd[src]['pred'] = Pred.surface_or_abstract(tgt)
elif rel == 'lnk':
cfrom, cto = tgt.strip('"<>').split(':')
nd[src]['lnk'] = Lnk.charspan(int(cfrom), int(cto))
elif rel == 'carg':
if (tgt[0], tgt[-1]) == ('"', '"'):
tgt = tgt[1:-1]
nd[src]['carg'] = tgt
elif rel == 'type':
nd[src]['si'].append((CVARSORT, tgt))
elif rel.islower():
nd[src]['si'].append((rel, tgt))
else:
edges.append((src, rel, tgt))
nodes = [
Node(
nodeid=nid,
pred=nd[nid]['pred'],
sortinfo=nd[nid]['si'],
lnk=nd[nid]['lnk'],
carg=nd[nid]['carg']
) for nid in nids
]
top = nids[0] if nids else None
return cls(top=top, nodes=nodes, edges=edges) | python | def from_triples(cls, triples):
"""
Decode triples, as from :meth:`to_triples`, into an Eds object.
"""
nids, nd, edges = [], {}, []
for src, rel, tgt in triples:
if src not in nd:
nids.append(src)
nd[src] = {'pred': None, 'lnk': None, 'carg': None, 'si': []}
if rel == 'predicate':
nd[src]['pred'] = Pred.surface_or_abstract(tgt)
elif rel == 'lnk':
cfrom, cto = tgt.strip('"<>').split(':')
nd[src]['lnk'] = Lnk.charspan(int(cfrom), int(cto))
elif rel == 'carg':
if (tgt[0], tgt[-1]) == ('"', '"'):
tgt = tgt[1:-1]
nd[src]['carg'] = tgt
elif rel == 'type':
nd[src]['si'].append((CVARSORT, tgt))
elif rel.islower():
nd[src]['si'].append((rel, tgt))
else:
edges.append((src, rel, tgt))
nodes = [
Node(
nodeid=nid,
pred=nd[nid]['pred'],
sortinfo=nd[nid]['si'],
lnk=nd[nid]['lnk'],
carg=nd[nid]['carg']
) for nid in nids
]
top = nids[0] if nids else None
return cls(top=top, nodes=nodes, edges=edges) | Decode triples, as from :meth:`to_triples`, into an Eds object. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L224-L258 |
delph-in/pydelphin | delphin/util.py | LookaheadIterator.next | def next(self, skip=None):
"""
Remove the next datum from the buffer and return it.
"""
buffer = self._buffer
popleft = buffer.popleft
if skip is not None:
while True:
try:
if not skip(buffer[0]):
break
popleft()
except IndexError:
self._buffer_fill()
try:
datum = popleft()
except IndexError:
self._buffer_fill()
datum = popleft()
return datum | python | def next(self, skip=None):
"""
Remove the next datum from the buffer and return it.
"""
buffer = self._buffer
popleft = buffer.popleft
if skip is not None:
while True:
try:
if not skip(buffer[0]):
break
popleft()
except IndexError:
self._buffer_fill()
try:
datum = popleft()
except IndexError:
self._buffer_fill()
datum = popleft()
return datum | Remove the next datum from the buffer and return it. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/util.py#L266-L285 |
delph-in/pydelphin | delphin/util.py | LookaheadIterator.peek | def peek(self, n=0, skip=None, drop=False):
"""
Return the *n*th datum from the buffer.
"""
buffer = self._buffer
popleft = buffer.popleft
datum = None
if skip is not None:
stack = []
stackpush = stack.append
while n >= 0:
try:
datum = popleft()
except IndexError:
self._buffer_fill()
datum = popleft()
if not skip(datum):
n -= 1
stackpush(datum)
elif not drop:
stackpush(datum)
buffer.extendleft(reversed(stack))
else:
self._buffer_fill(n + 1)
datum = buffer[n]
return datum | python | def peek(self, n=0, skip=None, drop=False):
"""
Return the *n*th datum from the buffer.
"""
buffer = self._buffer
popleft = buffer.popleft
datum = None
if skip is not None:
stack = []
stackpush = stack.append
while n >= 0:
try:
datum = popleft()
except IndexError:
self._buffer_fill()
datum = popleft()
if not skip(datum):
n -= 1
stackpush(datum)
elif not drop:
stackpush(datum)
buffer.extendleft(reversed(stack))
else:
self._buffer_fill(n + 1)
datum = buffer[n]
return datum | Return the *n*th datum from the buffer. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/util.py#L287-L312 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultPhoto.to_array | def to_array(self):
"""
Serializes this InlineQueryResultPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultPhoto, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['photo_url'] = u(self.photo_url) # py2: type unicode, py3: type str
array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str
if self.photo_width is not None:
array['photo_width'] = int(self.photo_width) # type int
if self.photo_height is not None:
array['photo_height'] = int(self.photo_height) # type int
if self.title is not None:
array['title'] = u(self.title) # 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 InlineQueryResultPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultPhoto, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['photo_url'] = u(self.photo_url) # py2: type unicode, py3: type str
array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str
if self.photo_width is not None:
array['photo_width'] = int(self.photo_width) # type int
if self.photo_height is not None:
array['photo_height'] = int(self.photo_height) # type int
if self.title is not None:
array['title'] = u(self.title) # 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 InlineQueryResultPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L374-L412 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultMpeg4Gif.to_array | def to_array(self):
"""
Serializes this InlineQueryResultMpeg4Gif to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultMpeg4Gif, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['mpeg4_url'] = u(self.mpeg4_url) # py2: type unicode, py3: type str
array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str
if self.mpeg4_width is not None:
array['mpeg4_width'] = int(self.mpeg4_width) # type int
if self.mpeg4_height is not None:
array['mpeg4_height'] = int(self.mpeg4_height) # type int
if self.mpeg4_duration is not None:
array['mpeg4_duration'] = int(self.mpeg4_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 InlineQueryResultMpeg4Gif to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultMpeg4Gif, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['mpeg4_url'] = u(self.mpeg4_url) # py2: type unicode, py3: type str
array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str
if self.mpeg4_width is not None:
array['mpeg4_width'] = int(self.mpeg4_width) # type int
if self.mpeg4_height is not None:
array['mpeg4_height'] = int(self.mpeg4_height) # type int
if self.mpeg4_duration is not None:
array['mpeg4_duration'] = int(self.mpeg4_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 InlineQueryResultMpeg4Gif to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L853-L890 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultVideo.to_array | def to_array(self):
"""
Serializes this InlineQueryResultVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultVideo, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['video_url'] = u(self.video_url) # py2: type unicode, py3: type str
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
array['thumb_url'] = u(self.thumb_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.video_width is not None:
array['video_width'] = int(self.video_width) # type int
if self.video_height is not None:
array['video_height'] = int(self.video_height) # type int
if self.video_duration is not None:
array['video_duration'] = int(self.video_duration) # type int
if self.description is not None:
array['description'] = u(self.description) # 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 InlineQueryResultVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultVideo, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['video_url'] = u(self.video_url) # py2: type unicode, py3: type str
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
array['thumb_url'] = u(self.thumb_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.video_width is not None:
array['video_width'] = int(self.video_width) # type int
if self.video_height is not None:
array['video_height'] = int(self.video_height) # type int
if self.video_duration is not None:
array['video_duration'] = int(self.video_duration) # type int
if self.description is not None:
array['description'] = u(self.description) # 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 InlineQueryResultVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L1114-L1155 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultVoice.to_array | def to_array(self):
"""
Serializes this InlineQueryResultVoice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultVoice, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['voice_url'] = u(self.voice_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.voice_duration is not None:
array['voice_duration'] = int(self.voice_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 InlineQueryResultVoice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultVoice, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['voice_url'] = u(self.voice_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.voice_duration is not None:
array['voice_duration'] = int(self.voice_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 InlineQueryResultVoice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L1551-L1581 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultDocument.to_array | def to_array(self):
"""
Serializes this InlineQueryResultDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultDocument, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['document_url'] = u(self.document_url) # py2: type unicode, py3: type str
array['mime_type'] = u(self.mime_type) # 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.description is not None:
array['description'] = u(self.description) # 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 InlineQueryResultDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultDocument, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['document_url'] = u(self.document_url) # py2: type unicode, py3: type str
array['mime_type'] = u(self.mime_type) # 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.description is not None:
array['description'] = u(self.description) # 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 InlineQueryResultDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L1791-L1831 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultVenue.to_array | def to_array(self):
"""
Serializes this InlineQueryResultVenue to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultVenue, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
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
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 InlineQueryResultVenue to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultVenue, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
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
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 InlineQueryResultVenue to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L2270-L2307 |
luckydonald/pytgbot | code_generation/output/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()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
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()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
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/code_generation/output/pytgbot/api_types/sendable/inline.py#L2668-L2685 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultCachedPhoto.to_array | def to_array(self):
"""
Serializes this InlineQueryResultCachedPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultCachedPhoto, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['photo_file_id'] = u(self.photo_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.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 InlineQueryResultCachedPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultCachedPhoto, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['photo_file_id'] = u(self.photo_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.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 InlineQueryResultCachedPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L2851-L2883 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultCachedMpeg4Gif.to_array | def to_array(self):
"""
Serializes this InlineQueryResultCachedMpeg4Gif to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultCachedMpeg4Gif, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['mpeg4_file_id'] = u(self.mpeg4_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 InlineQueryResultCachedMpeg4Gif to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultCachedMpeg4Gif, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['mpeg4_file_id'] = u(self.mpeg4_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 InlineQueryResultCachedMpeg4Gif to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L3237-L3266 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultCachedSticker.to_array | def to_array(self):
"""
Serializes this InlineQueryResultCachedSticker to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultCachedSticker, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['sticker_file_id'] = u(self.sticker_file_id) # 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 InlineQueryResultCachedSticker to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultCachedSticker, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['sticker_file_id'] = u(self.sticker_file_id) # 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 InlineQueryResultCachedSticker to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L3403-L3423 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultCachedVideo.to_array | def to_array(self):
"""
Serializes this InlineQueryResultCachedVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultCachedVideo, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['video_file_id'] = u(self.video_file_id) # py2: type unicode, py3: type str
array['title'] = u(self.title) # 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 InlineQueryResultCachedVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultCachedVideo, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['video_file_id'] = u(self.video_file_id) # py2: type unicode, py3: type str
array['title'] = u(self.title) # 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 InlineQueryResultCachedVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L3796-L3827 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/inline.py | InlineQueryResultCachedAudio.to_array | def to_array(self):
"""
Serializes this InlineQueryResultCachedAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultCachedAudio, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['audio_file_id'] = u(self.audio_file_id) # 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 InlineQueryResultCachedAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQueryResultCachedAudio, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['audio_file_id'] = u(self.audio_file_id) # 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 InlineQueryResultCachedAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/inline.py#L4175-L4201 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | MessageEntity.to_array | def to_array(self):
"""
Serializes this MessageEntity to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(MessageEntity, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['offset'] = int(self.offset) # type int
array['length'] = int(self.length) # type int
if self.url is not None:
array['url'] = u(self.url) # py2: type unicode, py3: type str
if self.user is not None:
array['user'] = self.user.to_array() # type User
return array | python | def to_array(self):
"""
Serializes this MessageEntity to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(MessageEntity, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['offset'] = int(self.offset) # type int
array['length'] = int(self.length) # type int
if self.url is not None:
array['url'] = u(self.url) # py2: type unicode, py3: type str
if self.user is not None:
array['user'] = self.user.to_array() # type User
return array | Serializes this MessageEntity 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/media.py#L92-L110 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | PhotoSize.to_array | def to_array(self):
"""
Serializes this PhotoSize to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PhotoSize, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['width'] = int(self.width) # type int
array['height'] = int(self.height) # type int
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | python | def to_array(self):
"""
Serializes this PhotoSize to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PhotoSize, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['width'] = int(self.width) # type int
array['height'] = int(self.height) # type int
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | Serializes this PhotoSize 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/media.py#L235-L249 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Audio.to_array | def to_array(self):
"""
Serializes this Audio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Audio, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['duration'] = int(self.duration) # type int
if self.performer is not None:
array['performer'] = u(self.performer) # 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.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
return array | python | def to_array(self):
"""
Serializes this Audio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Audio, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['duration'] = int(self.duration) # type int
if self.performer is not None:
array['performer'] = u(self.performer) # 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.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
return array | Serializes this Audio 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/media.py#L400-L425 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Audio.from_array | def from_array(array):
"""
Deserialize a new Audio from a given dictionary.
:return: new Audio instance.
:rtype: Audio
"""
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 PhotoSize
data = {}
data['file_id'] = u(array.get('file_id'))
data['duration'] = int(array.get('duration'))
data['performer'] = u(array.get('performer')) if array.get('performer') is not None else None
data['title'] = u(array.get('title')) if array.get('title') is not None else None
data['mime_type'] = u(array.get('mime_type')) if array.get('mime_type') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['_raw'] = array
return Audio(**data) | python | def from_array(array):
"""
Deserialize a new Audio from a given dictionary.
:return: new Audio instance.
:rtype: Audio
"""
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 PhotoSize
data = {}
data['file_id'] = u(array.get('file_id'))
data['duration'] = int(array.get('duration'))
data['performer'] = u(array.get('performer')) if array.get('performer') is not None else None
data['title'] = u(array.get('title')) if array.get('title') is not None else None
data['mime_type'] = u(array.get('mime_type')) if array.get('mime_type') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['_raw'] = array
return Audio(**data) | Deserialize a new Audio from a given dictionary.
:return: new Audio instance.
:rtype: Audio | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/media.py#L429-L452 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Document.to_array | def to_array(self):
"""
Serializes this Document to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Document, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.file_name is not None:
array['file_name'] = u(self.file_name) # py2: type unicode, py3: type str
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | python | def to_array(self):
"""
Serializes this Document to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Document, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.file_name is not None:
array['file_name'] = u(self.file_name) # py2: type unicode, py3: type str
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | Serializes this Document 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/media.py#L563-L584 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Animation.to_array | def to_array(self):
"""
Serializes this Animation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Animation, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['width'] = int(self.width) # type int
array['height'] = int(self.height) # type int
array['duration'] = int(self.duration) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.file_name is not None:
array['file_name'] = u(self.file_name) # py2: type unicode, py3: type str
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | python | def to_array(self):
"""
Serializes this Animation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Animation, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['width'] = int(self.width) # type int
array['height'] = int(self.height) # type int
array['duration'] = int(self.duration) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.file_name is not None:
array['file_name'] = u(self.file_name) # py2: type unicode, py3: type str
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | Serializes this Animation 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/media.py#L924-L948 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Voice.to_array | def to_array(self):
"""
Serializes this Voice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Voice, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['duration'] = int(self.duration) # type int
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | python | def to_array(self):
"""
Serializes this Voice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Voice, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['duration'] = int(self.duration) # type int
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | Serializes this Voice 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/media.py#L1076-L1092 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | VideoNote.to_array | def to_array(self):
"""
Serializes this VideoNote to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(VideoNote, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['length'] = int(self.length) # type int
array['duration'] = int(self.duration) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | python | def to_array(self):
"""
Serializes this VideoNote to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(VideoNote, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['length'] = int(self.length) # type int
array['duration'] = int(self.duration) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | Serializes this VideoNote 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/media.py#L1225-L1242 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Contact.to_array | def to_array(self):
"""
Serializes this Contact to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Contact, 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.user_id is not None:
array['user_id'] = int(self.user_id) # type int
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 Contact to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Contact, 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.user_id is not None:
array['user_id'] = int(self.user_id) # type int
if self.vcard is not None:
array['vcard'] = u(self.vcard) # py2: type unicode, py3: type str
return array | Serializes this Contact 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/media.py#L1376-L1396 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Location.to_array | def to_array(self):
"""
Serializes this Location to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Location, self).to_array()
array['longitude'] = float(self.longitude) # type float
array['latitude'] = float(self.latitude) # type float
return array | python | def to_array(self):
"""
Serializes this Location to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Location, self).to_array()
array['longitude'] = float(self.longitude) # type float
array['latitude'] = float(self.latitude) # type float
return array | Serializes this Location 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/media.py#L1501-L1511 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Location.from_array | def from_array(array):
"""
Deserialize a new Location from a given dictionary.
:return: new Location instance.
:rtype: Location
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['longitude'] = float(array.get('longitude'))
data['latitude'] = float(array.get('latitude'))
data['_raw'] = array
return Location(**data) | python | def from_array(array):
"""
Deserialize a new Location from a given dictionary.
:return: new Location instance.
:rtype: Location
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['longitude'] = float(array.get('longitude'))
data['latitude'] = float(array.get('latitude'))
data['_raw'] = array
return Location(**data) | Deserialize a new Location from a given dictionary.
:return: new Location instance.
:rtype: Location | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/media.py#L1515-L1531 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Venue.to_array | def to_array(self):
"""
Serializes this Venue to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Venue, self).to_array()
array['location'] = self.location.to_array() # type Location
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 Venue to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Venue, self).to_array()
array['location'] = self.location.to_array() # type Location
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 Venue 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/media.py#L1642-L1662 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Venue.from_array | def from_array(array):
"""
Deserialize a new Venue from a given dictionary.
:return: new Venue instance.
:rtype: Venue
"""
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 Location
data = {}
data['location'] = Location.from_array(array.get('location'))
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
data['_raw'] = array
return Venue(**data) | python | def from_array(array):
"""
Deserialize a new Venue from a given dictionary.
:return: new Venue instance.
:rtype: Venue
"""
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 Location
data = {}
data['location'] = Location.from_array(array.get('location'))
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
data['_raw'] = array
return Venue(**data) | Deserialize a new Venue from a given dictionary.
:return: new Venue instance.
:rtype: Venue | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/media.py#L1666-L1687 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | UserProfilePhotos.to_array | def to_array(self):
"""
Serializes this UserProfilePhotos to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(UserProfilePhotos, self).to_array()
array['total_count'] = int(self.total_count) # type int
array['photos'] = self._as_array(self.photos) # type list of list of PhotoSize
return array | python | def to_array(self):
"""
Serializes this UserProfilePhotos to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(UserProfilePhotos, self).to_array()
array['total_count'] = int(self.total_count) # type int
array['photos'] = self._as_array(self.photos) # type list of list of PhotoSize
return array | Serializes this UserProfilePhotos 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/media.py#L1771-L1782 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | UserProfilePhotos.from_array | def from_array(array):
"""
Deserialize a new UserProfilePhotos from a given dictionary.
:return: new UserProfilePhotos instance.
:rtype: UserProfilePhotos
"""
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 PhotoSize
data = {}
data['total_count'] = int(array.get('total_count'))
data['photos'] = PhotoSize.from_array_list(array.get('photos'), list_level=2)
data['_raw'] = array
return UserProfilePhotos(**data) | python | def from_array(array):
"""
Deserialize a new UserProfilePhotos from a given dictionary.
:return: new UserProfilePhotos instance.
:rtype: UserProfilePhotos
"""
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 PhotoSize
data = {}
data['total_count'] = int(array.get('total_count'))
data['photos'] = PhotoSize.from_array_list(array.get('photos'), list_level=2)
data['_raw'] = array
return UserProfilePhotos(**data) | Deserialize a new UserProfilePhotos from a given dictionary.
:return: new UserProfilePhotos instance.
:rtype: UserProfilePhotos | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/media.py#L1786-L1804 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | File.to_array | def to_array(self):
"""
Serializes this File to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(File, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
if self.file_path is not None:
array['file_path'] = u(self.file_path) # py2: type unicode, py3: type str
return array | python | def to_array(self):
"""
Serializes this File to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(File, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
if self.file_path is not None:
array['file_path'] = u(self.file_path) # py2: type unicode, py3: type str
return array | Serializes this File 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/media.py#L1899-L1914 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | ChatPhoto.to_array | def to_array(self):
"""
Serializes this ChatPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ChatPhoto, self).to_array()
array['small_file_id'] = u(self.small_file_id) # py2: type unicode, py3: type str
array['big_file_id'] = u(self.big_file_id) # py2: type unicode, py3: type str
return array | python | def to_array(self):
"""
Serializes this ChatPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ChatPhoto, self).to_array()
array['small_file_id'] = u(self.small_file_id) # py2: type unicode, py3: type str
array['big_file_id'] = u(self.big_file_id) # py2: type unicode, py3: type str
return array | Serializes this ChatPhoto 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/media.py#L2017-L2029 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Sticker.to_array | def to_array(self):
"""
Serializes this Sticker to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Sticker, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['width'] = int(self.width) # type int
array['height'] = int(self.height) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.emoji is not None:
array['emoji'] = u(self.emoji) # py2: type unicode, py3: type str
if self.set_name is not None:
array['set_name'] = u(self.set_name) # py2: type unicode, py3: type str
if self.mask_position is not None:
array['mask_position'] = self.mask_position.to_array() # type MaskPosition
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | python | def to_array(self):
"""
Serializes this Sticker to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Sticker, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['width'] = int(self.width) # type int
array['height'] = int(self.height) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.emoji is not None:
array['emoji'] = u(self.emoji) # py2: type unicode, py3: type str
if self.set_name is not None:
array['set_name'] = u(self.set_name) # py2: type unicode, py3: type str
if self.mask_position is not None:
array['mask_position'] = self.mask_position.to_array() # type MaskPosition
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array | Serializes this Sticker 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/media.py#L2188-L2214 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Sticker.from_array | def from_array(array):
"""
Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker
"""
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 PhotoSize
from pytgbot.api_types.receivable.stickers import MaskPosition
data = {}
data['file_id'] = u(array.get('file_id'))
data['width'] = int(array.get('width'))
data['height'] = int(array.get('height'))
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['emoji'] = u(array.get('emoji')) if array.get('emoji') is not None else None
data['set_name'] = u(array.get('set_name')) if array.get('set_name') is not None else None
data['mask_position'] = MaskPosition.from_array(array.get('mask_position')) if array.get('mask_position') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['_raw'] = array
return Sticker(**data) | python | def from_array(array):
"""
Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker
"""
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 PhotoSize
from pytgbot.api_types.receivable.stickers import MaskPosition
data = {}
data['file_id'] = u(array.get('file_id'))
data['width'] = int(array.get('width'))
data['height'] = int(array.get('height'))
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['emoji'] = u(array.get('emoji')) if array.get('emoji') is not None else None
data['set_name'] = u(array.get('set_name')) if array.get('set_name') is not None else None
data['mask_position'] = MaskPosition.from_array(array.get('mask_position')) if array.get('mask_position') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['_raw'] = array
return Sticker(**data) | Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/media.py#L2218-L2243 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Game.to_array | def to_array(self):
"""
Serializes this Game to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Game, self).to_array()
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['description'] = u(self.description) # py2: type unicode, py3: type str
array['photo'] = self._as_array(self.photo) # type list of PhotoSize
if self.text is not None:
array['text'] = u(self.text) # py2: type unicode, py3: type str
if self.text_entities is not None:
array['text_entities'] = self._as_array(self.text_entities) # type list of MessageEntity
if self.animation is not None:
array['animation'] = self.animation.to_array() # type Animation
return array | python | def to_array(self):
"""
Serializes this Game to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Game, self).to_array()
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['description'] = u(self.description) # py2: type unicode, py3: type str
array['photo'] = self._as_array(self.photo) # type list of PhotoSize
if self.text is not None:
array['text'] = u(self.text) # py2: type unicode, py3: type str
if self.text_entities is not None:
array['text_entities'] = self._as_array(self.text_entities) # type list of MessageEntity
if self.animation is not None:
array['animation'] = self.animation.to_array() # type Animation
return array | Serializes this Game 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/media.py#L2365-L2388 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/media.py | Game.from_array | def from_array(array):
"""
Deserialize a new Game from a given dictionary.
:return: new Game instance.
:rtype: Game
"""
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 Animation
from pytgbot.api_types.receivable.media import MessageEntity
from pytgbot.api_types.receivable.media import PhotoSize
data = {}
data['title'] = u(array.get('title'))
data['description'] = u(array.get('description'))
data['photo'] = PhotoSize.from_array_list(array.get('photo'), list_level=1)
data['text'] = u(array.get('text')) if array.get('text') is not None else None
data['text_entities'] = MessageEntity.from_array_list(array.get('text_entities'), list_level=1) if array.get('text_entities') is not None else None
data['animation'] = Animation.from_array(array.get('animation')) if array.get('animation') is not None else None
data['_raw'] = array
return Game(**data) | python | def from_array(array):
"""
Deserialize a new Game from a given dictionary.
:return: new Game instance.
:rtype: Game
"""
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 Animation
from pytgbot.api_types.receivable.media import MessageEntity
from pytgbot.api_types.receivable.media import PhotoSize
data = {}
data['title'] = u(array.get('title'))
data['description'] = u(array.get('description'))
data['photo'] = PhotoSize.from_array_list(array.get('photo'), list_level=1)
data['text'] = u(array.get('text')) if array.get('text') is not None else None
data['text_entities'] = MessageEntity.from_array_list(array.get('text_entities'), list_level=1) if array.get('text_entities') is not None else None
data['animation'] = Animation.from_array(array.get('animation')) if array.get('animation') is not None else None
data['_raw'] = array
return Game(**data) | Deserialize a new Game from a given dictionary.
:return: new Game instance.
:rtype: Game | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/media.py#L2392-L2416 |
luckydonald/pytgbot | pytgbot/api_types/receivable/media.py | DownloadableMedia.from_array | def from_array(array):
"""
Subclass for all :class:`Media` which has a :py:attr:`file_id` and optionally a :py:attr:`file_size`
:param array: a array to parse
:type array: dict
:return: a dict with file_id and file_size extracted from the array
:rtype: dict
"""
data = super(DownloadableMedia).from_array(array)
data["file_id"] = array.get("file_id")
data["file_size"] = array.get("file_size") # can be None
return data | python | def from_array(array):
"""
Subclass for all :class:`Media` which has a :py:attr:`file_id` and optionally a :py:attr:`file_size`
:param array: a array to parse
:type array: dict
:return: a dict with file_id and file_size extracted from the array
:rtype: dict
"""
data = super(DownloadableMedia).from_array(array)
data["file_id"] = array.get("file_id")
data["file_size"] = array.get("file_size") # can be None
return data | Subclass for all :class:`Media` which has a :py:attr:`file_id` and optionally a :py:attr:`file_size`
:param array: a array to parse
:type array: dict
:return: a dict with file_id and file_size extracted from the array
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/media.py#L165-L176 |
luckydonald/pytgbot | pytgbot/api_types/receivable/media.py | Sticker.from_array | def from_array(array):
"""
Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from .stickers import MaskPosition
data = {}
data['file_id'] = u(array.get('file_id'))
data['width'] = int(array.get('width'))
data['height'] = int(array.get('height'))
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['emoji'] = u(array.get('emoji')) if array.get('emoji') is not None else None
data['set_name'] = u(array.get('set_name')) if array.get('set_name') is not None else None
data['mask_position'] = MaskPosition.from_array(array.get('mask_position')) if array.get(
'mask_position') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['_raw'] = array
return Sticker(**data) | python | def from_array(array):
"""
Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from .stickers import MaskPosition
data = {}
data['file_id'] = u(array.get('file_id'))
data['width'] = int(array.get('width'))
data['height'] = int(array.get('height'))
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['emoji'] = u(array.get('emoji')) if array.get('emoji') is not None else None
data['set_name'] = u(array.get('set_name')) if array.get('set_name') is not None else None
data['mask_position'] = MaskPosition.from_array(array.get('mask_position')) if array.get(
'mask_position') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['_raw'] = array
return Sticker(**data) | Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/media.py#L965-L989 |
luckydonald/pytgbot | pytgbot/api_types/receivable/media.py | VideoNote.from_array | def from_array(array):
"""
Deserialize a new VideoNote from a given dictionary.
:return: new VideoNote instance.
:rtype: VideoNote
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['file_id'] = u(array.get('file_id'))
data['length'] = int(array.get('length'))
data['duration'] = int(array.get('duration'))
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['_raw'] = array
return VideoNote(**data) | python | def from_array(array):
"""
Deserialize a new VideoNote from a given dictionary.
:return: new VideoNote instance.
:rtype: VideoNote
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['file_id'] = u(array.get('file_id'))
data['length'] = int(array.get('length'))
data['duration'] = int(array.get('duration'))
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['_raw'] = array
return VideoNote(**data) | Deserialize a new VideoNote from a given dictionary.
:return: new VideoNote instance.
:rtype: VideoNote | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/media.py#L1428-L1447 |
luckydonald/pytgbot | pytgbot/api_types/receivable/media.py | Venue.from_array | def from_array(array):
"""
Deserialize a new Venue from a given dictionary.
:return: new Venue instance.
:rtype: Venue
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['location'] = Location.from_array(array.get('location'))
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
data['_raw'] = array
return Venue(**data) | python | def from_array(array):
"""
Deserialize a new Venue from a given dictionary.
:return: new Venue instance.
:rtype: Venue
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['location'] = Location.from_array(array.get('location'))
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
data['_raw'] = array
return Venue(**data) | Deserialize a new Venue from a given dictionary.
:return: new Venue instance.
:rtype: Venue | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/media.py#L1837-L1856 |
luckydonald/pytgbot | pytgbot/api_types/receivable/media.py | UserProfilePhotos.from_array | def from_array(array):
"""
Deserialize a new UserProfilePhotos from a given dictionary.
:return: new UserProfilePhotos instance.
:rtype: UserProfilePhotos
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['total_count'] = int(array.get('total_count'))
data['photos'] = PhotoSize.from_array_list(array.get('photos'), list_level=2)
data['_raw'] = array
return UserProfilePhotos(**data) | python | def from_array(array):
"""
Deserialize a new UserProfilePhotos from a given dictionary.
:return: new UserProfilePhotos instance.
:rtype: UserProfilePhotos
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['total_count'] = int(array.get('total_count'))
data['photos'] = PhotoSize.from_array_list(array.get('photos'), list_level=2)
data['_raw'] = array
return UserProfilePhotos(**data) | Deserialize a new UserProfilePhotos from a given dictionary.
:return: new UserProfilePhotos instance.
:rtype: UserProfilePhotos | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/media.py#L1953-L1969 |
luckydonald/pytgbot | pytgbot/api_types/receivable/media.py | Game.from_array | def from_array(array):
"""
Deserialize a new Game from a given dictionary.
:return: new Game instance.
:rtype: Game
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['title'] = u(array.get('title'))
data['description'] = u(array.get('description'))
data['photo'] = PhotoSize.from_array_list(array.get('photo'), list_level=1)
data['text'] = u(array.get('text')) if array.get('text') is not None else None
data['text_entities'] = MessageEntity.from_array_list(array.get('text_entities'), list_level=1) if array.get('text_entities') is not None else None
data['animation'] = Animation.from_array(array.get('animation')) if array.get('animation') is not None else None
data['_raw'] = array
return Game(**data) | python | def from_array(array):
"""
Deserialize a new Game from a given dictionary.
:return: new Game instance.
:rtype: Game
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['title'] = u(array.get('title'))
data['description'] = u(array.get('description'))
data['photo'] = PhotoSize.from_array_list(array.get('photo'), list_level=1)
data['text'] = u(array.get('text')) if array.get('text') is not None else None
data['text_entities'] = MessageEntity.from_array_list(array.get('text_entities'), list_level=1) if array.get('text_entities') is not None else None
data['animation'] = Animation.from_array(array.get('animation')) if array.get('animation') is not None else None
data['_raw'] = array
return Game(**data) | Deserialize a new Game from a given dictionary.
:return: new Game instance.
:rtype: Game | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/media.py#L2371-L2391 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | ReplyKeyboardMarkup.to_array | def to_array(self):
"""
Serializes this ReplyKeyboardMarkup to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ReplyKeyboardMarkup, self).to_array()
array['keyboard'] = self._as_array(self.keyboard) # type list of list of KeyboardButton
if self.resize_keyboard is not None:
array['resize_keyboard'] = bool(self.resize_keyboard) # type bool
if self.one_time_keyboard is not None:
array['one_time_keyboard'] = bool(self.one_time_keyboard) # type bool
if self.selective is not None:
array['selective'] = bool(self.selective) # type bool
return array | python | def to_array(self):
"""
Serializes this ReplyKeyboardMarkup to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ReplyKeyboardMarkup, self).to_array()
array['keyboard'] = self._as_array(self.keyboard) # type list of list of KeyboardButton
if self.resize_keyboard is not None:
array['resize_keyboard'] = bool(self.resize_keyboard) # type bool
if self.one_time_keyboard is not None:
array['one_time_keyboard'] = bool(self.one_time_keyboard) # type bool
if self.selective is not None:
array['selective'] = bool(self.selective) # type bool
return array | Serializes this ReplyKeyboardMarkup to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L74-L90 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | ReplyKeyboardMarkup.from_array | def from_array(array):
"""
Deserialize a new ReplyKeyboardMarkup from a given dictionary.
:return: new ReplyKeyboardMarkup instance.
:rtype: ReplyKeyboardMarkup
"""
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 KeyboardButton
data = {}
data['keyboard'] = KeyboardButton.from_array_list(array.get('keyboard'), list_level=2)
data['resize_keyboard'] = bool(array.get('resize_keyboard')) if array.get('resize_keyboard') is not None else None
data['one_time_keyboard'] = bool(array.get('one_time_keyboard')) if array.get('one_time_keyboard') is not None else None
data['selective'] = bool(array.get('selective')) if array.get('selective') is not None else None
instance = ReplyKeyboardMarkup(**data)
instance._raw = array
return instance | python | def from_array(array):
"""
Deserialize a new ReplyKeyboardMarkup from a given dictionary.
:return: new ReplyKeyboardMarkup instance.
:rtype: ReplyKeyboardMarkup
"""
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 KeyboardButton
data = {}
data['keyboard'] = KeyboardButton.from_array_list(array.get('keyboard'), list_level=2)
data['resize_keyboard'] = bool(array.get('resize_keyboard')) if array.get('resize_keyboard') is not None else None
data['one_time_keyboard'] = bool(array.get('one_time_keyboard')) if array.get('one_time_keyboard') is not None else None
data['selective'] = bool(array.get('selective')) if array.get('selective') is not None else None
instance = ReplyKeyboardMarkup(**data)
instance._raw = array
return instance | Deserialize a new ReplyKeyboardMarkup from a given dictionary.
:return: new ReplyKeyboardMarkup instance.
:rtype: ReplyKeyboardMarkup | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L94-L116 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | KeyboardButton.to_array | def to_array(self):
"""
Serializes this KeyboardButton to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(KeyboardButton, self).to_array()
array['text'] = u(self.text) # py2: type unicode, py3: type str
if self.request_contact is not None:
array['request_contact'] = bool(self.request_contact) # type bool
if self.request_location is not None:
array['request_location'] = bool(self.request_location) # type bool
return array | python | def to_array(self):
"""
Serializes this KeyboardButton to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(KeyboardButton, self).to_array()
array['text'] = u(self.text) # py2: type unicode, py3: type str
if self.request_contact is not None:
array['request_contact'] = bool(self.request_contact) # type bool
if self.request_location is not None:
array['request_location'] = bool(self.request_location) # type bool
return array | Serializes this KeyboardButton to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L201-L215 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | KeyboardButton.from_array | def from_array(array):
"""
Deserialize a new KeyboardButton from a given dictionary.
:return: new KeyboardButton instance.
:rtype: KeyboardButton
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['text'] = u(array.get('text'))
data['request_contact'] = bool(array.get('request_contact')) if array.get('request_contact') is not None else None
data['request_location'] = bool(array.get('request_location')) if array.get('request_location') is not None else None
instance = KeyboardButton(**data)
instance._raw = array
return instance | python | def from_array(array):
"""
Deserialize a new KeyboardButton from a given dictionary.
:return: new KeyboardButton instance.
:rtype: KeyboardButton
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['text'] = u(array.get('text'))
data['request_contact'] = bool(array.get('request_contact')) if array.get('request_contact') is not None else None
data['request_location'] = bool(array.get('request_location')) if array.get('request_location') is not None else None
instance = KeyboardButton(**data)
instance._raw = array
return instance | Deserialize a new KeyboardButton from a given dictionary.
:return: new KeyboardButton instance.
:rtype: KeyboardButton | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L219-L238 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | ReplyKeyboardRemove.to_array | def to_array(self):
"""
Serializes this ReplyKeyboardRemove to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ReplyKeyboardRemove, self).to_array()
array['remove_keyboard'] = bool(self.remove_keyboard) # type bool
if self.selective is not None:
array['selective'] = bool(self.selective) # type bool
return array | python | def to_array(self):
"""
Serializes this ReplyKeyboardRemove to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ReplyKeyboardRemove, self).to_array()
array['remove_keyboard'] = bool(self.remove_keyboard) # type bool
if self.selective is not None:
array['selective'] = bool(self.selective) # type bool
return array | Serializes this ReplyKeyboardRemove to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L312-L323 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | InlineKeyboardMarkup.to_array | def to_array(self):
"""
Serializes this InlineKeyboardMarkup to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineKeyboardMarkup, self).to_array()
array['inline_keyboard'] = self._as_array(self.inline_keyboard) # type list of list of InlineKeyboardButton
return array | python | def to_array(self):
"""
Serializes this InlineKeyboardMarkup to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineKeyboardMarkup, self).to_array()
array['inline_keyboard'] = self._as_array(self.inline_keyboard) # type list of list of InlineKeyboardButton
return array | Serializes this InlineKeyboardMarkup to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L414-L424 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | InlineKeyboardMarkup.from_array | def from_array(array):
"""
Deserialize a new InlineKeyboardMarkup from a given dictionary.
:return: new InlineKeyboardMarkup instance.
:rtype: InlineKeyboardMarkup
"""
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 InlineKeyboardButton
data = {}
data['inline_keyboard'] = InlineKeyboardButton.from_array_list(array.get('inline_keyboard'), list_level=2)
instance = InlineKeyboardMarkup(**data)
instance._raw = array
return instance | python | def from_array(array):
"""
Deserialize a new InlineKeyboardMarkup from a given dictionary.
:return: new InlineKeyboardMarkup instance.
:rtype: InlineKeyboardMarkup
"""
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 InlineKeyboardButton
data = {}
data['inline_keyboard'] = InlineKeyboardButton.from_array_list(array.get('inline_keyboard'), list_level=2)
instance = InlineKeyboardMarkup(**data)
instance._raw = array
return instance | Deserialize a new InlineKeyboardMarkup from a given dictionary.
:return: new InlineKeyboardMarkup instance.
:rtype: InlineKeyboardMarkup | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L428-L447 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | InlineKeyboardButton.to_array | def to_array(self):
"""
Serializes this InlineKeyboardButton to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineKeyboardButton, self).to_array()
array['text'] = u(self.text) # py2: type unicode, py3: type str
if self.url is not None:
array['url'] = u(self.url) # py2: type unicode, py3: type str
if self.callback_data is not None:
array['callback_data'] = u(self.callback_data) # py2: type unicode, py3: type str
if self.switch_inline_query is not None:
array['switch_inline_query'] = u(self.switch_inline_query) # py2: type unicode, py3: type str
if self.switch_inline_query_current_chat is not None:
array['switch_inline_query_current_chat'] = u(self.switch_inline_query_current_chat) # py2: type unicode, py3: type str
if self.callback_game is not None:
array['callback_game'] = self.callback_game.to_array() # type CallbackGame
if self.pay is not None:
array['pay'] = bool(self.pay) # type bool
return array | python | def to_array(self):
"""
Serializes this InlineKeyboardButton to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineKeyboardButton, self).to_array()
array['text'] = u(self.text) # py2: type unicode, py3: type str
if self.url is not None:
array['url'] = u(self.url) # py2: type unicode, py3: type str
if self.callback_data is not None:
array['callback_data'] = u(self.callback_data) # py2: type unicode, py3: type str
if self.switch_inline_query is not None:
array['switch_inline_query'] = u(self.switch_inline_query) # py2: type unicode, py3: type str
if self.switch_inline_query_current_chat is not None:
array['switch_inline_query_current_chat'] = u(self.switch_inline_query_current_chat) # py2: type unicode, py3: type str
if self.callback_game is not None:
array['callback_game'] = self.callback_game.to_array() # type CallbackGame
if self.pay is not None:
array['pay'] = bool(self.pay) # type bool
return array | Serializes this InlineKeyboardButton to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L568-L595 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | InlineKeyboardButton.from_array | def from_array(array):
"""
Deserialize a new InlineKeyboardButton from a given dictionary.
:return: new InlineKeyboardButton instance.
:rtype: InlineKeyboardButton
"""
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.updates import CallbackGame
data = {}
data['text'] = u(array.get('text'))
data['url'] = u(array.get('url')) if array.get('url') is not None else None
data['callback_data'] = u(array.get('callback_data')) if array.get('callback_data') is not None else None
data['switch_inline_query'] = u(array.get('switch_inline_query')) if array.get('switch_inline_query') is not None else None
data['switch_inline_query_current_chat'] = u(array.get('switch_inline_query_current_chat')) if array.get('switch_inline_query_current_chat') is not None else None
data['callback_game'] = CallbackGame.from_array(array.get('callback_game')) if array.get('callback_game') is not None else None
data['pay'] = bool(array.get('pay')) if array.get('pay') is not None else None
instance = InlineKeyboardButton(**data)
instance._raw = array
return instance | python | def from_array(array):
"""
Deserialize a new InlineKeyboardButton from a given dictionary.
:return: new InlineKeyboardButton instance.
:rtype: InlineKeyboardButton
"""
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.updates import CallbackGame
data = {}
data['text'] = u(array.get('text'))
data['url'] = u(array.get('url')) if array.get('url') is not None else None
data['callback_data'] = u(array.get('callback_data')) if array.get('callback_data') is not None else None
data['switch_inline_query'] = u(array.get('switch_inline_query')) if array.get('switch_inline_query') is not None else None
data['switch_inline_query_current_chat'] = u(array.get('switch_inline_query_current_chat')) if array.get('switch_inline_query_current_chat') is not None else None
data['callback_game'] = CallbackGame.from_array(array.get('callback_game')) if array.get('callback_game') is not None else None
data['pay'] = bool(array.get('pay')) if array.get('pay') is not None else None
instance = InlineKeyboardButton(**data)
instance._raw = array
return instance | Deserialize a new InlineKeyboardButton from a given dictionary.
:return: new InlineKeyboardButton instance.
:rtype: InlineKeyboardButton | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L599-L624 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | ForceReply.to_array | def to_array(self):
"""
Serializes this ForceReply to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ForceReply, self).to_array()
array['force_reply'] = bool(self.force_reply) # type bool
if self.selective is not None:
array['selective'] = bool(self.selective) # type bool
return array | python | def to_array(self):
"""
Serializes this ForceReply to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ForceReply, self).to_array()
array['force_reply'] = bool(self.force_reply) # type bool
if self.selective is not None:
array['selective'] = bool(self.selective) # type bool
return array | Serializes this ForceReply to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L706-L717 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/sendable/reply_markup.py | ForceReply.from_array | def from_array(array):
"""
Deserialize a new ForceReply from a given dictionary.
:return: new ForceReply instance.
:rtype: ForceReply
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['force_reply'] = bool(array.get('force_reply'))
data['selective'] = bool(array.get('selective')) if array.get('selective') is not None else None
instance = ForceReply(**data)
instance._raw = array
return instance | python | def from_array(array):
"""
Deserialize a new ForceReply from a given dictionary.
:return: new ForceReply instance.
:rtype: ForceReply
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['force_reply'] = bool(array.get('force_reply'))
data['selective'] = bool(array.get('selective')) if array.get('selective') is not None else None
instance = ForceReply(**data)
instance._raw = array
return instance | Deserialize a new ForceReply from a given dictionary.
:return: new ForceReply instance.
:rtype: ForceReply | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/reply_markup.py#L721-L739 |
luckydonald/pytgbot | pytgbot/api_types/sendable/passport.py | PassportElementErrorDataField.to_array | def to_array(self):
"""
Serializes this PassportElementErrorDataField to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PassportElementErrorDataField, self).to_array()
array['source'] = u(self.source) # py2: type unicode, py3: type str
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['field_name'] = u(self.field_name) # py2: type unicode, py3: type str
array['data_hash'] = u(self.data_hash) # py2: type unicode, py3: type str
array['message'] = u(self.message) # py2: type unicode, py3: type str
return array | python | def to_array(self):
"""
Serializes this PassportElementErrorDataField to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PassportElementErrorDataField, self).to_array()
array['source'] = u(self.source) # py2: type unicode, py3: type str
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['field_name'] = u(self.field_name) # py2: type unicode, py3: type str
array['data_hash'] = u(self.data_hash) # py2: type unicode, py3: type str
array['message'] = u(self.message) # py2: type unicode, py3: type str
return array | Serializes this PassportElementErrorDataField to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/passport.py#L91-L104 |
luckydonald/pytgbot | pytgbot/api_types/sendable/passport.py | PassportElementErrorReverseSide.to_array | def to_array(self):
"""
Serializes this PassportElementErrorReverseSide to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PassportElementErrorReverseSide, self).to_array()
array['source'] = u(self.source) # py2: type unicode, py3: type str
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['file_hash'] = u(self.file_hash) # py2: type unicode, py3: type str
array['message'] = u(self.message) # py2: type unicode, py3: type str
return array | python | def to_array(self):
"""
Serializes this PassportElementErrorReverseSide to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PassportElementErrorReverseSide, self).to_array()
array['source'] = u(self.source) # py2: type unicode, py3: type str
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['file_hash'] = u(self.file_hash) # py2: type unicode, py3: type str
array['message'] = u(self.message) # py2: type unicode, py3: type str
return array | Serializes this PassportElementErrorReverseSide to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/passport.py#L351-L363 |
luckydonald/pytgbot | pytgbot/api_types/sendable/passport.py | PassportElementErrorFiles.to_array | def to_array(self):
"""
Serializes this PassportElementErrorFiles to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PassportElementErrorFiles, self).to_array()
array['source'] = u(self.source) # py2: type unicode, py3: type str
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['file_hashes'] = self._as_array(self.file_hashes) # type list of str
array['message'] = u(self.message) # py2: type unicode, py3: type str
return array | python | def to_array(self):
"""
Serializes this PassportElementErrorFiles to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PassportElementErrorFiles, self).to_array()
array['source'] = u(self.source) # py2: type unicode, py3: type str
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['file_hashes'] = self._as_array(self.file_hashes) # type list of str
array['message'] = u(self.message) # py2: type unicode, py3: type str
return array | Serializes this PassportElementErrorFiles to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/passport.py#L738-L750 |
luckydonald/pytgbot | pytgbot/api_types/sendable/passport.py | PassportElementErrorFiles.from_array | def from_array(array):
"""
Deserialize a new PassportElementErrorFiles from a given dictionary.
:return: new PassportElementErrorFiles instance.
:rtype: PassportElementErrorFiles
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['source'] = u(array.get('source'))
data['type'] = u(array.get('type'))
data['file_hashes'] = PassportElementErrorFiles._builtin_from_array_list(required_type=unicode_type, value=array.get('file_hashes'), list_level=1)
data['message'] = u(array.get('message'))
instance = PassportElementErrorFiles(**data)
instance._raw = array
return instance | python | def from_array(array):
"""
Deserialize a new PassportElementErrorFiles from a given dictionary.
:return: new PassportElementErrorFiles instance.
:rtype: PassportElementErrorFiles
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['source'] = u(array.get('source'))
data['type'] = u(array.get('type'))
data['file_hashes'] = PassportElementErrorFiles._builtin_from_array_list(required_type=unicode_type, value=array.get('file_hashes'), list_level=1)
data['message'] = u(array.get('message'))
instance = PassportElementErrorFiles(**data)
instance._raw = array
return instance | Deserialize a new PassportElementErrorFiles from a given dictionary.
:return: new PassportElementErrorFiles instance.
:rtype: PassportElementErrorFiles | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/passport.py#L754-L774 |
luckydonald/pytgbot | pytgbot/api_types/sendable/passport.py | PassportElementErrorUnspecified.to_array | def to_array(self):
"""
Serializes this PassportElementErrorUnspecified to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PassportElementErrorUnspecified, self).to_array()
array['source'] = u(self.source) # py2: type unicode, py3: type str
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['element_hash'] = u(self.element_hash) # py2: type unicode, py3: type str
array['message'] = u(self.message) # py2: type unicode, py3: type str
return array | python | def to_array(self):
"""
Serializes this PassportElementErrorUnspecified to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PassportElementErrorUnspecified, self).to_array()
array['source'] = u(self.source) # py2: type unicode, py3: type str
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['element_hash'] = u(self.element_hash) # py2: type unicode, py3: type str
array['message'] = u(self.message) # py2: type unicode, py3: type str
return array | Serializes this PassportElementErrorUnspecified to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/passport.py#L1130-L1146 |
luckydonald/pytgbot | pytgbot/api_types/sendable/passport.py | PassportElementErrorUnspecified.from_array | def from_array(array):
"""
Deserialize a new PassportElementErrorUnspecified from a given dictionary.
:return: new PassportElementErrorUnspecified instance.
:rtype: PassportElementErrorUnspecified
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['source'] = u(array.get('source'))
data['type'] = u(array.get('type'))
data['element_hash'] = u(array.get('element_hash'))
data['message'] = u(array.get('message'))
instance = PassportElementErrorUnspecified(**data)
instance._raw = array
return instance | python | def from_array(array):
"""
Deserialize a new PassportElementErrorUnspecified from a given dictionary.
:return: new PassportElementErrorUnspecified instance.
:rtype: PassportElementErrorUnspecified
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['source'] = u(array.get('source'))
data['type'] = u(array.get('type'))
data['element_hash'] = u(array.get('element_hash'))
data['message'] = u(array.get('message'))
instance = PassportElementErrorUnspecified(**data)
instance._raw = array
return instance | Deserialize a new PassportElementErrorUnspecified from a given dictionary.
:return: new PassportElementErrorUnspecified instance.
:rtype: PassportElementErrorUnspecified | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/passport.py#L1150-L1170 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.