nwo
stringlengths 10
28
| sha
stringlengths 40
40
| path
stringlengths 11
97
| identifier
stringlengths 1
64
| parameters
stringlengths 2
2.24k
| return_statement
stringlengths 0
2.17k
| docstring
stringlengths 0
5.45k
| docstring_summary
stringlengths 0
3.83k
| func_begin
int64 1
13.4k
| func_end
int64 2
13.4k
| function
stringlengths 28
56.4k
| url
stringlengths 106
209
| project
int64 1
48
| executed_lines
list | executed_lines_pc
float64 0
153
| missing_lines
list | missing_lines_pc
float64 0
100
| covered
bool 2
classes | filecoverage
float64 2.53
100
| function_lines
int64 2
1.46k
| mccabe
int64 1
253
| coverage
float64 0
100
| docstring_lines
int64 0
112
| function_nodoc
stringlengths 9
56.4k
| id
int64 0
29.8k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
NestedFacet.add_filter
|
(self, filter_values)
| 253 | 256 |
def add_filter(self, filter_values):
inner_q = self._inner.add_filter(filter_values)
if inner_q:
return Nested(path=self._path, query=inner_q)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L253-L256
| 37 |
[
0
] | 25 |
[
1,
2,
3
] | 75 | false | 69.154229 | 4 | 2 | 25 | 0 |
def add_filter(self, filter_values):
inner_q = self._inner.add_filter(filter_values)
if inner_q:
return Nested(path=self._path, query=inner_q)
| 23,016 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedResponse.query_string
|
(self)
|
return self._faceted_search._query
| 261 | 262 |
def query_string(self):
return self._faceted_search._query
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L261-L262
| 37 |
[
0
] | 50 |
[
1
] | 50 | false | 69.154229 | 2 | 1 | 50 | 0 |
def query_string(self):
return self._faceted_search._query
| 23,017 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedResponse.facets
|
(self)
|
return self._facets
| 265 | 273 |
def facets(self):
if not hasattr(self, "_facets"):
super(AttrDict, self).__setattr__("_facets", AttrDict({}))
for name, facet in self._faceted_search.facets.items():
self._facets[name] = facet.get_values(
getattr(getattr(self.aggregations, "_filter_" + name), name),
self._faceted_search.filter_values.get(name, ()),
)
return self._facets
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L265-L273
| 37 |
[
0
] | 11.111111 |
[
1,
2,
3,
4,
8
] | 55.555556 | false | 69.154229 | 9 | 3 | 44.444444 | 0 |
def facets(self):
if not hasattr(self, "_facets"):
super(AttrDict, self).__setattr__("_facets", AttrDict({}))
for name, facet in self._faceted_search.facets.items():
self._facets[name] = facet.get_values(
getattr(getattr(self.aggregations, "_filter_" + name), name),
self._faceted_search.filter_values.get(name, ()),
)
return self._facets
| 23,018 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.__init__
|
(self, query=None, filters={}, sort=())
|
:arg query: the text to search for
:arg filters: facet values to filter
:arg sort: sort information to be passed to :class:`~elasticsearch_dsl.Search`
|
:arg query: the text to search for
:arg filters: facet values to filter
:arg sort: sort information to be passed to :class:`~elasticsearch_dsl.Search`
| 324 | 337 |
def __init__(self, query=None, filters={}, sort=()):
"""
:arg query: the text to search for
:arg filters: facet values to filter
:arg sort: sort information to be passed to :class:`~elasticsearch_dsl.Search`
"""
self._query = query
self._filters = {}
self._sort = sort
self.filter_values = {}
for name, value in filters.items():
self.add_filter(name, value)
self._s = self.build_search()
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L324-L337
| 37 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13
] | 100 |
[] | 0 | true | 69.154229 | 14 | 2 | 100 | 3 |
def __init__(self, query=None, filters={}, sort=()):
self._query = query
self._filters = {}
self._sort = sort
self.filter_values = {}
for name, value in filters.items():
self.add_filter(name, value)
self._s = self.build_search()
| 23,019 |
|
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.count
|
(self)
|
return self._s.count()
| 339 | 340 |
def count(self):
return self._s.count()
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L339-L340
| 37 |
[
0
] | 50 |
[
1
] | 50 | false | 69.154229 | 2 | 1 | 50 | 0 |
def count(self):
return self._s.count()
| 23,020 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.__getitem__
|
(self, k)
|
return self
| 342 | 344 |
def __getitem__(self, k):
self._s = self._s[k]
return self
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L342-L344
| 37 |
[
0
] | 33.333333 |
[
1,
2
] | 66.666667 | false | 69.154229 | 3 | 1 | 33.333333 | 0 |
def __getitem__(self, k):
self._s = self._s[k]
return self
| 23,021 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.__iter__
|
(self)
|
return iter(self._s)
| 346 | 347 |
def __iter__(self):
return iter(self._s)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L346-L347
| 37 |
[
0
] | 50 |
[
1
] | 50 | false | 69.154229 | 2 | 1 | 50 | 0 |
def __iter__(self):
return iter(self._s)
| 23,022 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.add_filter
|
(self, name, filter_values)
|
Add a filter for a facet.
|
Add a filter for a facet.
| 349 | 369 |
def add_filter(self, name, filter_values):
"""
Add a filter for a facet.
"""
# normalize the value into a list
if not isinstance(filter_values, (tuple, list)):
if filter_values is None:
return
filter_values = [
filter_values,
]
# remember the filter values for use in FacetedResponse
self.filter_values[name] = filter_values
# get the filter from the facet
f = self.facets[name].add_filter(filter_values)
if f is None:
return
self._filters[name] = f
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L349-L369
| 37 |
[
0,
1,
2,
3,
4,
5,
6,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
19,
20
] | 90.47619 |
[
7,
18
] | 9.52381 | false | 69.154229 | 21 | 4 | 90.47619 | 1 |
def add_filter(self, name, filter_values):
# normalize the value into a list
if not isinstance(filter_values, (tuple, list)):
if filter_values is None:
return
filter_values = [
filter_values,
]
# remember the filter values for use in FacetedResponse
self.filter_values[name] = filter_values
# get the filter from the facet
f = self.facets[name].add_filter(filter_values)
if f is None:
return
self._filters[name] = f
| 23,023 |
|
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.search
|
(self)
|
return s.response_class(FacetedResponse)
|
Returns the base Search object to which the facets are added.
You can customize the query by overriding this method and returning a
modified search object.
|
Returns the base Search object to which the facets are added.
| 371 | 379 |
def search(self):
"""
Returns the base Search object to which the facets are added.
You can customize the query by overriding this method and returning a
modified search object.
"""
s = Search(doc_type=self.doc_types, index=self.index, using=self.using)
return s.response_class(FacetedResponse)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L371-L379
| 37 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 100 |
[] | 0 | true | 69.154229 | 9 | 1 | 100 | 4 |
def search(self):
s = Search(doc_type=self.doc_types, index=self.index, using=self.using)
return s.response_class(FacetedResponse)
| 23,024 |
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.query
|
(self, search, query)
|
return search
|
Add query part to ``search``.
Override this if you wish to customize the query used.
|
Add query part to ``search``.
| 381 | 392 |
def query(self, search, query):
"""
Add query part to ``search``.
Override this if you wish to customize the query used.
"""
if query:
if self.fields:
return search.query("multi_match", fields=self.fields, query=query)
else:
return search.query("multi_match", query=query)
return search
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L381-L392
| 37 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 83.333333 |
[
10,
11
] | 16.666667 | false | 69.154229 | 12 | 3 | 83.333333 | 3 |
def query(self, search, query):
if query:
if self.fields:
return search.query("multi_match", fields=self.fields, query=query)
else:
return search.query("multi_match", query=query)
return search
| 23,025 |
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.aggregate
|
(self, search)
|
Add aggregations representing the facets selected, including potential
filters.
|
Add aggregations representing the facets selected, including potential
filters.
| 394 | 408 |
def aggregate(self, search):
"""
Add aggregations representing the facets selected, including potential
filters.
"""
for f, facet in self.facets.items():
agg = facet.get_aggregation()
agg_filter = MatchAll()
for field, filter in self._filters.items():
if f == field:
continue
agg_filter &= filter
search.aggs.bucket("_filter_" + f, "filter", filter=agg_filter).bucket(
f, agg
)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L394-L408
| 37 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
] | 100 |
[] | 0 | true | 69.154229 | 15 | 4 | 100 | 2 |
def aggregate(self, search):
for f, facet in self.facets.items():
agg = facet.get_aggregation()
agg_filter = MatchAll()
for field, filter in self._filters.items():
if f == field:
continue
agg_filter &= filter
search.aggs.bucket("_filter_" + f, "filter", filter=agg_filter).bucket(
f, agg
)
| 23,026 |
|
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.filter
|
(self, search)
|
return search.post_filter(post_filter)
|
Add a ``post_filter`` to the search request narrowing the results based
on the facet filters.
|
Add a ``post_filter`` to the search request narrowing the results based
on the facet filters.
| 410 | 421 |
def filter(self, search):
"""
Add a ``post_filter`` to the search request narrowing the results based
on the facet filters.
"""
if not self._filters:
return search
post_filter = MatchAll()
for f in self._filters.values():
post_filter &= f
return search.post_filter(post_filter)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L410-L421
| 37 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 100 |
[] | 0 | true | 69.154229 | 12 | 3 | 100 | 2 |
def filter(self, search):
if not self._filters:
return search
post_filter = MatchAll()
for f in self._filters.values():
post_filter &= f
return search.post_filter(post_filter)
| 23,027 |
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.highlight
|
(self, search)
|
return search.highlight(
*(f if "^" not in f else f.split("^", 1)[0] for f in self.fields)
)
|
Add highlighting for all the fields
|
Add highlighting for all the fields
| 423 | 429 |
def highlight(self, search):
"""
Add highlighting for all the fields
"""
return search.highlight(
*(f if "^" not in f else f.split("^", 1)[0] for f in self.fields)
)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L423-L429
| 37 |
[
0,
1,
2,
3,
4,
5,
6
] | 100 |
[] | 0 | true | 69.154229 | 7 | 1 | 100 | 1 |
def highlight(self, search):
return search.highlight(
*(f if "^" not in f else f.split("^", 1)[0] for f in self.fields)
)
| 23,028 |
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.sort
|
(self, search)
|
return search
|
Add sorting information to the request.
|
Add sorting information to the request.
| 431 | 437 |
def sort(self, search):
"""
Add sorting information to the request.
"""
if self._sort:
search = search.sort(*self._sort)
return search
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L431-L437
| 37 |
[
0,
1,
2,
3,
4,
5,
6
] | 100 |
[] | 0 | true | 69.154229 | 7 | 2 | 100 | 1 |
def sort(self, search):
if self._sort:
search = search.sort(*self._sort)
return search
| 23,029 |
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.build_search
|
(self)
|
return s
|
Construct the ``Search`` object.
|
Construct the ``Search`` object.
| 439 | 450 |
def build_search(self):
"""
Construct the ``Search`` object.
"""
s = self.search()
s = self.query(s, self._query)
s = self.filter(s)
if self.fields:
s = self.highlight(s)
s = self.sort(s)
self.aggregate(s)
return s
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L439-L450
| 37 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 100 |
[] | 0 | true | 69.154229 | 12 | 2 | 100 | 1 |
def build_search(self):
s = self.search()
s = self.query(s, self._query)
s = self.filter(s)
if self.fields:
s = self.highlight(s)
s = self.sort(s)
self.aggregate(s)
return s
| 23,030 |
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/faceted_search.py
|
FacetedSearch.execute
|
(self)
|
return r
|
Execute the search and return the response.
|
Execute the search and return the response.
| 452 | 458 |
def execute(self):
"""
Execute the search and return the response.
"""
r = self._s.execute()
r._faceted_search = self
return r
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/faceted_search.py#L452-L458
| 37 |
[
0,
1,
2,
3
] | 57.142857 |
[
4,
5,
6
] | 42.857143 | false | 69.154229 | 7 | 1 | 57.142857 | 1 |
def execute(self):
r = self._s.execute()
r._faceted_search = self
return r
| 23,031 |
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/hit.py
|
Hit.__init__
|
(self, document)
| 22 | 31 |
def __init__(self, document):
data = {}
if "_source" in document:
data = document["_source"]
if "fields" in document:
data.update(document["fields"])
super().__init__(data)
# assign meta as attribute and not as key in self._d_
super(AttrDict, self).__setattr__("meta", HitMeta(document))
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/hit.py#L22-L31
| 37 |
[
0,
1,
2,
3,
4,
6,
7,
8,
9
] | 90 |
[
5
] | 10 | false | 94.736842 | 10 | 3 | 90 | 0 |
def __init__(self, document):
data = {}
if "_source" in document:
data = document["_source"]
if "fields" in document:
data.update(document["fields"])
super().__init__(data)
# assign meta as attribute and not as key in self._d_
super(AttrDict, self).__setattr__("meta", HitMeta(document))
| 23,032 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/hit.py
|
Hit.__getstate__
|
(self)
|
return super().__getstate__() + (self.meta,)
| 33 | 35 |
def __getstate__(self):
# add self.meta since it is not in self.__dict__
return super().__getstate__() + (self.meta,)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/hit.py#L33-L35
| 37 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 94.736842 | 3 | 1 | 100 | 0 |
def __getstate__(self):
# add self.meta since it is not in self.__dict__
return super().__getstate__() + (self.meta,)
| 23,033 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/hit.py
|
Hit.__setstate__
|
(self, state)
| 37 | 39 |
def __setstate__(self, state):
super(AttrDict, self).__setattr__("meta", state[-1])
super().__setstate__(state[:-1])
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/hit.py#L37-L39
| 37 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 94.736842 | 3 | 1 | 100 | 0 |
def __setstate__(self, state):
super(AttrDict, self).__setattr__("meta", state[-1])
super().__setstate__(state[:-1])
| 23,034 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/hit.py
|
Hit.__dir__
|
(self)
|
return super().__dir__() + ["meta"]
| 41 | 43 |
def __dir__(self):
# be sure to expose meta in dir(self)
return super().__dir__() + ["meta"]
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/hit.py#L41-L43
| 37 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 94.736842 | 3 | 1 | 100 | 0 |
def __dir__(self):
# be sure to expose meta in dir(self)
return super().__dir__() + ["meta"]
| 23,035 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/hit.py
|
Hit.__repr__
|
(self)
|
return "<Hit({}): {}>".format(
"/".join(
getattr(self.meta, key) for key in ("index", "id") if key in self.meta
),
super().__repr__(),
)
| 45 | 51 |
def __repr__(self):
return "<Hit({}): {}>".format(
"/".join(
getattr(self.meta, key) for key in ("index", "id") if key in self.meta
),
super().__repr__(),
)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/hit.py#L45-L51
| 37 |
[
0,
1
] | 28.571429 |
[] | 0 | false | 94.736842 | 7 | 1 | 100 | 0 |
def __repr__(self):
return "<Hit({}): {}>".format(
"/".join(
getattr(self.meta, key) for key in ("index", "id") if key in self.meta
),
super().__repr__(),
)
| 23,036 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.__init__
|
(self, search, response, doc_class=None)
| 25 | 28 |
def __init__(self, search, response, doc_class=None):
super(AttrDict, self).__setattr__("_search", search)
super(AttrDict, self).__setattr__("_doc_class", doc_class)
super().__init__(response)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L25-L28
| 37 |
[
0,
1,
2,
3
] | 100 |
[] | 0 | true | 100 | 4 | 1 | 100 | 0 |
def __init__(self, search, response, doc_class=None):
super(AttrDict, self).__setattr__("_search", search)
super(AttrDict, self).__setattr__("_doc_class", doc_class)
super().__init__(response)
| 23,037 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.__iter__
|
(self)
|
return iter(self.hits)
| 30 | 31 |
def __iter__(self):
return iter(self.hits)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L30-L31
| 37 |
[
0,
1
] | 100 |
[] | 0 | true | 100 | 2 | 1 | 100 | 0 |
def __iter__(self):
return iter(self.hits)
| 23,038 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.__getitem__
|
(self, key)
|
return super().__getitem__(key)
| 33 | 37 |
def __getitem__(self, key):
if isinstance(key, (slice, int)):
# for slicing etc
return self.hits[key]
return super().__getitem__(key)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L33-L37
| 37 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 100 | 5 | 2 | 100 | 0 |
def __getitem__(self, key):
if isinstance(key, (slice, int)):
# for slicing etc
return self.hits[key]
return super().__getitem__(key)
| 23,039 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.__nonzero__
|
(self)
|
return bool(self.hits)
| 39 | 40 |
def __nonzero__(self):
return bool(self.hits)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L39-L40
| 37 |
[
0,
1
] | 100 |
[] | 0 | true | 100 | 2 | 1 | 100 | 0 |
def __nonzero__(self):
return bool(self.hits)
| 23,040 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.__repr__
|
(self)
|
return "<Response: %r>" % (self.hits or self.aggregations)
| 44 | 45 |
def __repr__(self):
return "<Response: %r>" % (self.hits or self.aggregations)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L44-L45
| 37 |
[
0,
1
] | 100 |
[] | 0 | true | 100 | 2 | 2 | 100 | 0 |
def __repr__(self):
return "<Response: %r>" % (self.hits or self.aggregations)
| 23,041 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.__len__
|
(self)
|
return len(self.hits)
| 47 | 48 |
def __len__(self):
return len(self.hits)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L47-L48
| 37 |
[
0,
1
] | 100 |
[] | 0 | true | 100 | 2 | 1 | 100 | 0 |
def __len__(self):
return len(self.hits)
| 23,042 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.__getstate__
|
(self)
|
return self._d_, self._search, self._doc_class
| 50 | 51 |
def __getstate__(self):
return self._d_, self._search, self._doc_class
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L50-L51
| 37 |
[
0,
1
] | 100 |
[] | 0 | true | 100 | 2 | 1 | 100 | 0 |
def __getstate__(self):
return self._d_, self._search, self._doc_class
| 23,043 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.__setstate__
|
(self, state)
| 53 | 56 |
def __setstate__(self, state):
super(AttrDict, self).__setattr__("_d_", state[0])
super(AttrDict, self).__setattr__("_search", state[1])
super(AttrDict, self).__setattr__("_doc_class", state[2])
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L53-L56
| 37 |
[
0,
1,
2,
3
] | 100 |
[] | 0 | true | 100 | 4 | 1 | 100 | 0 |
def __setstate__(self, state):
super(AttrDict, self).__setattr__("_d_", state[0])
super(AttrDict, self).__setattr__("_search", state[1])
super(AttrDict, self).__setattr__("_doc_class", state[2])
| 23,044 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.success
|
(self)
|
return self._shards.total == self._shards.successful and not self.timed_out
| 58 | 59 |
def success(self):
return self._shards.total == self._shards.successful and not self.timed_out
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L58-L59
| 37 |
[
0,
1
] | 100 |
[] | 0 | true | 100 | 2 | 2 | 100 | 0 |
def success(self):
return self._shards.total == self._shards.successful and not self.timed_out
| 23,045 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.hits
|
(self)
|
return self._hits
| 62 | 76 |
def hits(self):
if not hasattr(self, "_hits"):
h = self._d_["hits"]
try:
hits = AttrList(map(self._search._get_result, h["hits"]))
except AttributeError as e:
# avoid raising AttributeError since it will be hidden by the property
raise TypeError("Could not parse hits.", e)
# avoid assigning _hits into self._d_
super(AttrDict, self).__setattr__("_hits", hits)
for k in h:
setattr(self._hits, k, _wrap(h[k]))
return self._hits
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L62-L76
| 37 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
] | 100 |
[] | 0 | true | 100 | 15 | 4 | 100 | 0 |
def hits(self):
if not hasattr(self, "_hits"):
h = self._d_["hits"]
try:
hits = AttrList(map(self._search._get_result, h["hits"]))
except AttributeError as e:
# avoid raising AttributeError since it will be hidden by the property
raise TypeError("Could not parse hits.", e)
# avoid assigning _hits into self._d_
super(AttrDict, self).__setattr__("_hits", hits)
for k in h:
setattr(self._hits, k, _wrap(h[k]))
return self._hits
| 23,046 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.aggregations
|
(self)
|
return self.aggs
| 79 | 80 |
def aggregations(self):
return self.aggs
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L79-L80
| 37 |
[
0,
1
] | 100 |
[] | 0 | true | 100 | 2 | 1 | 100 | 0 |
def aggregations(self):
return self.aggs
| 23,047 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
Response.aggs
|
(self)
|
return self._aggs
| 83 | 91 |
def aggs(self):
if not hasattr(self, "_aggs"):
aggs = AggResponse(
self._search.aggs, self._search, self._d_.get("aggregations", {})
)
# avoid assigning _aggs into self._d_
super(AttrDict, self).__setattr__("_aggs", aggs)
return self._aggs
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L83-L91
| 37 |
[
0,
1,
2,
6,
7,
8
] | 66.666667 |
[] | 0 | false | 100 | 9 | 2 | 100 | 0 |
def aggs(self):
if not hasattr(self, "_aggs"):
aggs = AggResponse(
self._search.aggs, self._search, self._d_.get("aggregations", {})
)
# avoid assigning _aggs into self._d_
super(AttrDict, self).__setattr__("_aggs", aggs)
return self._aggs
| 23,048 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
AggResponse.__init__
|
(self, aggs, search, data)
| 95 | 97 |
def __init__(self, aggs, search, data):
super(AttrDict, self).__setattr__("_meta", {"search": search, "aggs": aggs})
super().__init__(data)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L95-L97
| 37 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 100 | 3 | 1 | 100 | 0 |
def __init__(self, aggs, search, data):
super(AttrDict, self).__setattr__("_meta", {"search": search, "aggs": aggs})
super().__init__(data)
| 23,049 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
AggResponse.__getitem__
|
(self, attr_name)
|
return super().__getitem__(attr_name)
| 99 | 104 |
def __getitem__(self, attr_name):
if attr_name in self._meta["aggs"]:
# don't do self._meta['aggs'][attr_name] to avoid copying
agg = self._meta["aggs"].aggs[attr_name]
return agg.result(self._meta["search"], self._d_[attr_name])
return super().__getitem__(attr_name)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L99-L104
| 37 |
[
0,
1,
2,
3,
4,
5
] | 100 |
[] | 0 | true | 100 | 6 | 2 | 100 | 0 |
def __getitem__(self, attr_name):
if attr_name in self._meta["aggs"]:
# don't do self._meta['aggs'][attr_name] to avoid copying
agg = self._meta["aggs"].aggs[attr_name]
return agg.result(self._meta["search"], self._d_[attr_name])
return super().__getitem__(attr_name)
| 23,050 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
AggResponse.__iter__
|
(self)
| 106 | 108 |
def __iter__(self):
for name in self._meta["aggs"]:
yield self[name]
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L106-L108
| 37 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 100 | 3 | 2 | 100 | 0 |
def __iter__(self):
for name in self._meta["aggs"]:
yield self[name]
| 23,051 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
UpdateByQueryResponse.__init__
|
(self, search, response, doc_class=None)
| 112 | 115 |
def __init__(self, search, response, doc_class=None):
super(AttrDict, self).__setattr__("_search", search)
super(AttrDict, self).__setattr__("_doc_class", doc_class)
super().__init__(response)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L112-L115
| 37 |
[
0,
1,
2,
3
] | 100 |
[] | 0 | true | 100 | 4 | 1 | 100 | 0 |
def __init__(self, search, response, doc_class=None):
super(AttrDict, self).__setattr__("_search", search)
super(AttrDict, self).__setattr__("_doc_class", doc_class)
super().__init__(response)
| 23,052 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/__init__.py
|
UpdateByQueryResponse.success
|
(self)
|
return not self.timed_out and not self.failures
| 117 | 118 |
def success(self):
return not self.timed_out and not self.failures
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/__init__.py#L117-L118
| 37 |
[
0,
1
] | 100 |
[] | 0 | true | 100 | 2 | 2 | 100 | 0 |
def success(self):
return not self.timed_out and not self.failures
| 23,053 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/aggs.py
|
Bucket.__init__
|
(self, aggs, search, data, field=None)
| 23 | 24 |
def __init__(self, aggs, search, data, field=None):
super().__init__(aggs, search, data)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/aggs.py#L23-L24
| 37 |
[
0,
1
] | 100 |
[] | 0 | true | 87.5 | 2 | 1 | 100 | 0 |
def __init__(self, aggs, search, data, field=None):
super().__init__(aggs, search, data)
| 23,054 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/aggs.py
|
FieldBucket.__init__
|
(self, aggs, search, data, field=None)
| 28 | 31 |
def __init__(self, aggs, search, data, field=None):
if field:
data["key"] = field.deserialize(data["key"])
super().__init__(aggs, search, data, field)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/aggs.py#L28-L31
| 37 |
[
0,
1,
2,
3
] | 100 |
[] | 0 | true | 87.5 | 4 | 2 | 100 | 0 |
def __init__(self, aggs, search, data, field=None):
if field:
data["key"] = field.deserialize(data["key"])
super().__init__(aggs, search, data, field)
| 23,055 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/aggs.py
|
BucketData._wrap_bucket
|
(self, data)
|
return self._bucket_class(
self._meta["aggs"],
self._meta["search"],
data,
field=self._meta.get("field"),
)
| 37 | 43 |
def _wrap_bucket(self, data):
return self._bucket_class(
self._meta["aggs"],
self._meta["search"],
data,
field=self._meta.get("field"),
)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/aggs.py#L37-L43
| 37 |
[
0,
1
] | 28.571429 |
[] | 0 | false | 87.5 | 7 | 1 | 100 | 0 |
def _wrap_bucket(self, data):
return self._bucket_class(
self._meta["aggs"],
self._meta["search"],
data,
field=self._meta.get("field"),
)
| 23,056 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/aggs.py
|
BucketData.__iter__
|
(self)
|
return iter(self.buckets)
| 45 | 46 |
def __iter__(self):
return iter(self.buckets)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/aggs.py#L45-L46
| 37 |
[
0,
1
] | 100 |
[] | 0 | true | 87.5 | 2 | 1 | 100 | 0 |
def __iter__(self):
return iter(self.buckets)
| 23,057 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/aggs.py
|
BucketData.__len__
|
(self)
|
return len(self.buckets)
| 48 | 49 |
def __len__(self):
return len(self.buckets)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/aggs.py#L48-L49
| 37 |
[
0
] | 50 |
[
1
] | 50 | false | 87.5 | 2 | 1 | 50 | 0 |
def __len__(self):
return len(self.buckets)
| 23,058 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/aggs.py
|
BucketData.__getitem__
|
(self, key)
|
return super().__getitem__(key)
| 51 | 54 |
def __getitem__(self, key):
if isinstance(key, (int, slice)):
return self.buckets[key]
return super().__getitem__(key)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/aggs.py#L51-L54
| 37 |
[
0,
1,
3
] | 75 |
[
2
] | 25 | false | 87.5 | 4 | 2 | 75 | 0 |
def __getitem__(self, key):
if isinstance(key, (int, slice)):
return self.buckets[key]
return super().__getitem__(key)
| 23,059 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/aggs.py
|
BucketData.buckets
|
(self)
|
return self._buckets
| 57 | 68 |
def buckets(self):
if not hasattr(self, "_buckets"):
field = getattr(self._meta["aggs"], "field", None)
if field:
self._meta["field"] = self._meta["search"]._resolve_field(field)
bs = self._d_["buckets"]
if isinstance(bs, list):
bs = AttrList(bs, obj_wrapper=self._wrap_bucket)
else:
bs = AttrDict({k: self._wrap_bucket(bs[k]) for k in bs})
super(AttrDict, self).__setattr__("_buckets", bs)
return self._buckets
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/aggs.py#L57-L68
| 37 |
[
0,
1,
2,
3,
4,
5,
6,
7,
10,
11
] | 83.333333 |
[
9
] | 8.333333 | false | 87.5 | 12 | 4 | 91.666667 | 0 |
def buckets(self):
if not hasattr(self, "_buckets"):
field = getattr(self._meta["aggs"], "field", None)
if field:
self._meta["field"] = self._meta["search"]._resolve_field(field)
bs = self._d_["buckets"]
if isinstance(bs, list):
bs = AttrList(bs, obj_wrapper=self._wrap_bucket)
else:
bs = AttrDict({k: self._wrap_bucket(bs[k]) for k in bs})
super(AttrDict, self).__setattr__("_buckets", bs)
return self._buckets
| 23,060 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
elasticsearch_dsl/response/aggs.py
|
TopHitsData.__init__
|
(self, agg, search, data)
| 76 | 80 |
def __init__(self, agg, search, data):
super(AttrDict, self).__setattr__(
"meta", AttrDict({"agg": agg, "search": search})
)
super().__init__(search, data)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/elasticsearch_dsl/response/aggs.py#L76-L80
| 37 |
[
0
] | 20 |
[
1,
4
] | 40 | false | 87.5 | 5 | 1 | 60 | 0 |
def __init__(self, agg, search, data):
super(AttrDict, self).__setattr__(
"meta", AttrDict({"agg": agg, "search": search})
)
super().__init__(search, data)
| 23,061 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/percolate.py
|
setup
|
()
| 79 | 89 |
def setup():
# create the percolator index if it doesn't exist
if not PercolatorDoc._index.exists():
PercolatorDoc.init()
# register a percolation query looking for documents about python
PercolatorDoc(
_id="python",
tags=["programming", "development", "python"],
query=Q("match", content="python"),
).save(refresh=True)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/percolate.py#L79-L89
| 37 |
[
0,
1
] | 18.181818 |
[
2,
3,
6
] | 27.272727 | false | 58.62069 | 11 | 2 | 72.727273 | 0 |
def setup():
# create the percolator index if it doesn't exist
if not PercolatorDoc._index.exists():
PercolatorDoc.init()
# register a percolation query looking for documents about python
PercolatorDoc(
_id="python",
tags=["programming", "development", "python"],
query=Q("match", content="python"),
).save(refresh=True)
| 23,062 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/percolate.py
|
BlogPost.add_tags
|
(self)
| 40 | 52 |
def add_tags(self):
# run a percolation to automatically tag the blog post.
s = Search(index="test-percolator")
s = s.query(
"percolate", field="query", index=self._get_index(), document=self.to_dict()
)
# collect all the tags from matched percolators
for percolator in s:
self.tags.extend(percolator.tags)
# make sure tags are unique
self.tags = list(set(self.tags))
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/percolate.py#L40-L52
| 37 |
[
0,
1
] | 15.384615 |
[
2,
3,
8,
9,
12
] | 38.461538 | false | 58.62069 | 13 | 2 | 61.538462 | 0 |
def add_tags(self):
# run a percolation to automatically tag the blog post.
s = Search(index="test-percolator")
s = s.query(
"percolate", field="query", index=self._get_index(), document=self.to_dict()
)
# collect all the tags from matched percolators
for percolator in s:
self.tags.extend(percolator.tags)
# make sure tags are unique
self.tags = list(set(self.tags))
| 23,063 |
|||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/percolate.py
|
BlogPost.save
|
(self, **kwargs)
|
return super().save(**kwargs)
| 54 | 56 |
def save(self, **kwargs):
self.add_tags()
return super().save(**kwargs)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/percolate.py#L54-L56
| 37 |
[
0
] | 33.333333 |
[
1,
2
] | 66.666667 | false | 58.62069 | 3 | 1 | 33.333333 | 0 |
def save(self, **kwargs):
self.add_tags()
return super().save(**kwargs)
| 23,064 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/composite_agg.py
|
scan_aggs
|
(search, source_aggs, inner_aggs={}, size=10)
|
Helper function used to iterate over all possible bucket combinations of
``source_aggs``, returning results of ``inner_aggs`` for each. Uses the
``composite`` aggregation under the hood to perform this.
|
Helper function used to iterate over all possible bucket combinations of
``source_aggs``, returning results of ``inner_aggs`` for each. Uses the
``composite`` aggregation under the hood to perform this.
| 22 | 43 |
def scan_aggs(search, source_aggs, inner_aggs={}, size=10):
"""
Helper function used to iterate over all possible bucket combinations of
``source_aggs``, returning results of ``inner_aggs`` for each. Uses the
``composite`` aggregation under the hood to perform this.
"""
def run_search(**kwargs):
s = search[:0]
s.aggs.bucket("comp", "composite", sources=source_aggs, size=size, **kwargs)
for agg_name, agg in inner_aggs.items():
s.aggs["comp"][agg_name] = agg
return s.execute()
response = run_search()
while response.aggregations.comp.buckets:
yield from response.aggregations.comp.buckets
if "after_key" in response.aggregations.comp:
after = response.aggregations.comp.after_key
else:
after = response.aggregations.comp.buckets[-1].key
response = run_search(after=after)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/composite_agg.py#L22-L43
| 37 |
[
0,
1,
2,
3,
4,
5,
6
] | 31.818182 |
[
7,
8,
9,
10,
11,
12,
14,
15,
16,
17,
18,
20,
21
] | 59.090909 | false | 15.789474 | 22 | 5 | 40.909091 | 3 |
def scan_aggs(search, source_aggs, inner_aggs={}, size=10):
def run_search(**kwargs):
s = search[:0]
s.aggs.bucket("comp", "composite", sources=source_aggs, size=size, **kwargs)
for agg_name, agg in inner_aggs.items():
s.aggs["comp"][agg_name] = agg
return s.execute()
response = run_search()
while response.aggregations.comp.buckets:
yield from response.aggregations.comp.buckets
if "after_key" in response.aggregations.comp:
after = response.aggregations.comp.after_key
else:
after = response.aggregations.comp.buckets[-1].key
response = run_search(after=after)
| 23,065 |
|
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/completion.py
|
Person.clean
|
(self)
|
Automatically construct the suggestion input and weight by taking all
possible permutation of Person's name as ``input`` and taking their
popularity as ``weight``.
|
Automatically construct the suggestion input and weight by taking all
possible permutation of Person's name as ``input`` and taking their
popularity as ``weight``.
| 58 | 67 |
def clean(self):
"""
Automatically construct the suggestion input and weight by taking all
possible permutation of Person's name as ``input`` and taking their
popularity as ``weight``.
"""
self.suggest = {
"input": [" ".join(p) for p in permutations(self.name.split())],
"weight": self.popularity,
}
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/completion.py#L58-L67
| 37 |
[
0,
1,
2,
3,
4,
5
] | 60 |
[
6
] | 10 | false | 52 | 10 | 2 | 90 | 3 |
def clean(self):
self.suggest = {
"input": [" ".join(p) for p in permutations(self.name.split())],
"weight": self.popularity,
}
| 23,066 |
|
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
setup
|
()
|
Create an IndexTemplate and save it into elasticsearch.
|
Create an IndexTemplate and save it into elasticsearch.
| 205 | 208 |
def setup():
"""Create an IndexTemplate and save it into elasticsearch."""
index_template = Post._index.as_template("base")
index_template.save()
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L205-L208
| 37 |
[
0,
1
] | 50 |
[
2,
3
] | 50 | false | 54.545455 | 4 | 1 | 50 | 1 |
def setup():
index_template = Post._index.as_template("base")
index_template.save()
| 23,067 |
|
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Post._matches
|
(cls, hit)
|
return False
| 93 | 96 |
def _matches(cls, hit):
# Post is an abstract class, make sure it never gets used for
# deserialization
return False
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L93-L96
| 37 |
[
0,
1,
2
] | 75 |
[
3
] | 25 | false | 54.545455 | 4 | 1 | 75 | 0 |
def _matches(cls, hit):
# Post is an abstract class, make sure it never gets used for
# deserialization
return False
| 23,068 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Post.add_comment
|
(self, user, content, created=None, commit=True)
|
return c
| 105 | 110 |
def add_comment(self, user, content, created=None, commit=True):
c = Comment(author=user, content=content, created=created or datetime.now())
self.comments.append(c)
if commit:
self.save()
return c
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L105-L110
| 37 |
[
0
] | 16.666667 |
[
1,
2,
3,
4,
5
] | 83.333333 | false | 54.545455 | 6 | 3 | 16.666667 | 0 |
def add_comment(self, user, content, created=None, commit=True):
c = Comment(author=user, content=content, created=created or datetime.now())
self.comments.append(c)
if commit:
self.save()
return c
| 23,069 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Post.save
|
(self, **kwargs)
|
return super().save(**kwargs)
| 112 | 116 |
def save(self, **kwargs):
# if there is no date, use now
if self.created is None:
self.created = datetime.now()
return super().save(**kwargs)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L112-L116
| 37 |
[
0,
1
] | 40 |
[
2,
3,
4
] | 60 | false | 54.545455 | 5 | 2 | 40 | 0 |
def save(self, **kwargs):
# if there is no date, use now
if self.created is None:
self.created = datetime.now()
return super().save(**kwargs)
| 23,070 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Question._matches
|
(cls, hit)
|
return hit["_source"]["question_answer"] == "question"
|
Use Question class for parent documents
|
Use Question class for parent documents
| 125 | 127 |
def _matches(cls, hit):
"""Use Question class for parent documents"""
return hit["_source"]["question_answer"] == "question"
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L125-L127
| 37 |
[
0,
1
] | 66.666667 |
[
2
] | 33.333333 | false | 54.545455 | 3 | 1 | 66.666667 | 1 |
def _matches(cls, hit):
return hit["_source"]["question_answer"] == "question"
| 23,071 |
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Question.search
|
(cls, **kwargs)
|
return cls._index.search(**kwargs).filter("term", question_answer="question")
| 130 | 131 |
def search(cls, **kwargs):
return cls._index.search(**kwargs).filter("term", question_answer="question")
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L130-L131
| 37 |
[
0
] | 50 |
[
1
] | 50 | false | 54.545455 | 2 | 1 | 50 | 0 |
def search(cls, **kwargs):
return cls._index.search(**kwargs).filter("term", question_answer="question")
| 23,072 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Question.add_answer
|
(self, user, body, created=None, accepted=False, commit=True)
|
return answer
| 133 | 149 |
def add_answer(self, user, body, created=None, accepted=False, commit=True):
answer = Answer(
# required make sure the answer is stored in the same shard
_routing=self.meta.id,
# since we don't have explicit index, ensure same index as self
_index=self.meta.index,
# set up the parent/child mapping
question_answer={"name": "answer", "parent": self.meta.id},
# pass in the field values
author=user,
created=created,
body=body,
accepted=accepted,
)
if commit:
answer.save()
return answer
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L133-L149
| 37 |
[
0
] | 5.882353 |
[
1,
14,
15,
16
] | 23.529412 | false | 54.545455 | 17 | 2 | 76.470588 | 0 |
def add_answer(self, user, body, created=None, accepted=False, commit=True):
answer = Answer(
# required make sure the answer is stored in the same shard
_routing=self.meta.id,
# since we don't have explicit index, ensure same index as self
_index=self.meta.index,
# set up the parent/child mapping
question_answer={"name": "answer", "parent": self.meta.id},
# pass in the field values
author=user,
created=created,
body=body,
accepted=accepted,
)
if commit:
answer.save()
return answer
| 23,073 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Question.search_answers
|
(self)
|
return s
| 151 | 158 |
def search_answers(self):
# search only our index
s = Answer.search()
# filter for answers belonging to us
s = s.filter("parent_id", type="answer", id=self.meta.id)
# add routing to only go to specific shard
s = s.params(routing=self.meta.id)
return s
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L151-L158
| 37 |
[
0,
1
] | 25 |
[
2,
4,
6,
7
] | 50 | false | 54.545455 | 8 | 1 | 50 | 0 |
def search_answers(self):
# search only our index
s = Answer.search()
# filter for answers belonging to us
s = s.filter("parent_id", type="answer", id=self.meta.id)
# add routing to only go to specific shard
s = s.params(routing=self.meta.id)
return s
| 23,074 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Question.get_answers
|
(self)
|
return list(self.search_answers())
|
Get answers either from inner_hits already present or by searching
elasticsearch.
|
Get answers either from inner_hits already present or by searching
elasticsearch.
| 160 | 167 |
def get_answers(self):
"""
Get answers either from inner_hits already present or by searching
elasticsearch.
"""
if "inner_hits" in self.meta and "answer" in self.meta.inner_hits:
return self.meta.inner_hits.answer.hits
return list(self.search_answers())
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L160-L167
| 37 |
[
0,
1,
2,
3,
4
] | 62.5 |
[
5,
6,
7
] | 37.5 | false | 54.545455 | 8 | 3 | 62.5 | 2 |
def get_answers(self):
if "inner_hits" in self.meta and "answer" in self.meta.inner_hits:
return self.meta.inner_hits.answer.hits
return list(self.search_answers())
| 23,075 |
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Question.save
|
(self, **kwargs)
|
return super().save(**kwargs)
| 169 | 171 |
def save(self, **kwargs):
self.question_answer = "question"
return super().save(**kwargs)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L169-L171
| 37 |
[
0
] | 33.333333 |
[
1,
2
] | 66.666667 | false | 54.545455 | 3 | 1 | 33.333333 | 0 |
def save(self, **kwargs):
self.question_answer = "question"
return super().save(**kwargs)
| 23,076 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Answer._matches
|
(cls, hit)
|
return (
isinstance(hit["_source"]["question_answer"], dict)
and hit["_source"]["question_answer"].get("name") == "answer"
)
|
Use Answer class for child documents with child name 'answer
|
Use Answer class for child documents with child name 'answer
| 178 | 183 |
def _matches(cls, hit):
"""Use Answer class for child documents with child name 'answer'"""
return (
isinstance(hit["_source"]["question_answer"], dict)
and hit["_source"]["question_answer"].get("name") == "answer"
)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L178-L183
| 37 |
[
0,
1
] | 33.333333 |
[
2
] | 16.666667 | false | 54.545455 | 6 | 2 | 83.333333 | 1 |
def _matches(cls, hit):
return (
isinstance(hit["_source"]["question_answer"], dict)
and hit["_source"]["question_answer"].get("name") == "answer"
)
| 23,077 |
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Answer.search
|
(cls, **kwargs)
|
return cls._index.search(**kwargs).exclude("term", question_answer="question")
| 186 | 187 |
def search(cls, **kwargs):
return cls._index.search(**kwargs).exclude("term", question_answer="question")
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L186-L187
| 37 |
[
0
] | 50 |
[
1
] | 50 | false | 54.545455 | 2 | 1 | 50 | 0 |
def search(cls, **kwargs):
return cls._index.search(**kwargs).exclude("term", question_answer="question")
| 23,078 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Answer.question
|
(self)
|
return self.meta.question
| 190 | 197 |
def question(self):
# cache question in self.meta
# any attributes set on self would be interpretted as fields
if "question" not in self.meta:
self.meta.question = Question.get(
id=self.question_answer.parent, index=self.meta.index
)
return self.meta.question
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L190-L197
| 37 |
[
0,
1,
2
] | 37.5 |
[
3,
4,
7
] | 37.5 | false | 54.545455 | 8 | 2 | 62.5 | 0 |
def question(self):
# cache question in self.meta
# any attributes set on self would be interpretted as fields
if "question" not in self.meta:
self.meta.question = Question.get(
id=self.question_answer.parent, index=self.meta.index
)
return self.meta.question
| 23,079 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/parent_child.py
|
Answer.save
|
(self, **kwargs)
|
return super().save(**kwargs)
| 199 | 202 |
def save(self, **kwargs):
# set routing to parents id automatically
self.meta.routing = self.question_answer.parent
return super().save(**kwargs)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/parent_child.py#L199-L202
| 37 |
[
0,
1
] | 50 |
[
2,
3
] | 50 | false | 54.545455 | 4 | 1 | 50 | 0 |
def save(self, **kwargs):
# set routing to parents id automatically
self.meta.routing = self.question_answer.parent
return super().save(**kwargs)
| 23,080 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/alias_migration.py
|
setup
|
()
|
Create the index template in elasticsearch specifying the mappings and any
settings to be used. This can be run at any time, ideally at every new code
deploy.
|
Create the index template in elasticsearch specifying the mappings and any
settings to be used. This can be run at any time, ideally at every new code
deploy.
| 70 | 84 |
def setup():
"""
Create the index template in elasticsearch specifying the mappings and any
settings to be used. This can be run at any time, ideally at every new code
deploy.
"""
# create an index template
index_template = BlogPost._index.as_template(ALIAS, PATTERN)
# upload the template into elasticsearch
# potentially overriding the one already there
index_template.save()
# create the first index if it doesn't exist
if not BlogPost._index.exists():
migrate(move_data=False)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/alias_migration.py#L70-L84
| 37 |
[
0,
1,
2,
3,
4,
5,
6
] | 46.666667 |
[
7,
10,
13,
14
] | 26.666667 | false | 51.282051 | 15 | 2 | 73.333333 | 3 |
def setup():
# create an index template
index_template = BlogPost._index.as_template(ALIAS, PATTERN)
# upload the template into elasticsearch
# potentially overriding the one already there
index_template.save()
# create the first index if it doesn't exist
if not BlogPost._index.exists():
migrate(move_data=False)
| 23,081 |
|
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/alias_migration.py
|
migrate
|
(move_data=True, update_alias=True)
|
Upgrade function that creates a new index for the data. Optionally it also can
(and by default will) reindex previous copy of the data into the new index
(specify ``move_data=False`` to skip this step) and update the alias to
point to the latest index (set ``update_alias=False`` to skip).
Note that while this function is running the application can still perform
any and all searches without any loss of functionality. It should, however,
not perform any writes at this time as those might be lost.
|
Upgrade function that creates a new index for the data. Optionally it also can
(and by default will) reindex previous copy of the data into the new index
(specify ``move_data=False`` to skip this step) and update the alias to
point to the latest index (set ``update_alias=False`` to skip).
| 87 | 125 |
def migrate(move_data=True, update_alias=True):
"""
Upgrade function that creates a new index for the data. Optionally it also can
(and by default will) reindex previous copy of the data into the new index
(specify ``move_data=False`` to skip this step) and update the alias to
point to the latest index (set ``update_alias=False`` to skip).
Note that while this function is running the application can still perform
any and all searches without any loss of functionality. It should, however,
not perform any writes at this time as those might be lost.
"""
# construct a new index name by appending current timestamp
next_index = PATTERN.replace("*", datetime.now().strftime("%Y%m%d%H%M%S%f"))
# get the low level connection
es = connections.get_connection()
# create new index, it will use the settings from the template
es.indices.create(index=next_index)
if move_data:
# move data from current alias to the new index
es.reindex(
body={"source": {"index": ALIAS}, "dest": {"index": next_index}},
request_timeout=3600,
)
# refresh the index to make the changes visible
es.indices.refresh(index=next_index)
if update_alias:
# repoint the alias to point to the newly created index
es.indices.update_aliases(
body={
"actions": [
{"remove": {"alias": ALIAS, "index": PATTERN}},
{"add": {"alias": ALIAS, "index": next_index}},
]
}
)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/alias_migration.py#L87-L125
| 37 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 30.769231 |
[
12,
15,
18,
20,
22,
27,
29,
31
] | 20.512821 | false | 51.282051 | 39 | 3 | 79.487179 | 8 |
def migrate(move_data=True, update_alias=True):
# construct a new index name by appending current timestamp
next_index = PATTERN.replace("*", datetime.now().strftime("%Y%m%d%H%M%S%f"))
# get the low level connection
es = connections.get_connection()
# create new index, it will use the settings from the template
es.indices.create(index=next_index)
if move_data:
# move data from current alias to the new index
es.reindex(
body={"source": {"index": ALIAS}, "dest": {"index": next_index}},
request_timeout=3600,
)
# refresh the index to make the changes visible
es.indices.refresh(index=next_index)
if update_alias:
# repoint the alias to point to the newly created index
es.indices.update_aliases(
body={
"actions": [
{"remove": {"alias": ALIAS, "index": PATTERN}},
{"add": {"alias": ALIAS, "index": next_index}},
]
}
)
| 23,082 |
|
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/alias_migration.py
|
BlogPost.is_published
|
(self)
|
return self.published and datetime.now() > self.published
| 53 | 54 |
def is_published(self):
return self.published and datetime.now() > self.published
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/alias_migration.py#L53-L54
| 37 |
[
0
] | 50 |
[
1
] | 50 | false | 51.282051 | 2 | 2 | 50 | 0 |
def is_published(self):
return self.published and datetime.now() > self.published
| 23,083 |
||
elastic/elasticsearch-dsl-py
|
5874ff6bd5a7a77086539159f041eb979b5235cc
|
examples/alias_migration.py
|
BlogPost._matches
|
(cls, hit)
|
return fnmatch(hit["_index"], PATTERN)
| 57 | 60 |
def _matches(cls, hit):
# override _matches to match indices in a pattern instead of just ALIAS
# hit is the raw dict as returned by elasticsearch
return fnmatch(hit["_index"], PATTERN)
|
https://github.com/elastic/elasticsearch-dsl-py/blob/5874ff6bd5a7a77086539159f041eb979b5235cc/project37/examples/alias_migration.py#L57-L60
| 37 |
[
0,
1,
2
] | 75 |
[
3
] | 25 | false | 51.282051 | 4 | 1 | 75 | 0 |
def _matches(cls, hit):
# override _matches to match indices in a pattern instead of just ALIAS
# hit is the raw dict as returned by elasticsearch
return fnmatch(hit["_index"], PATTERN)
| 23,084 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/pagerange.py
|
parse_filename_page_ranges
|
(
args: List[Union[str, PageRange, None]]
)
|
return pairs
|
Given a list of filenames and page ranges, return a list of (filename, page_range) pairs.
Args:
args: A list where the first element is a filename. The other elements are
filenames, page-range expressions, slice objects, or PageRange objects.
A filename not followed by a page range indicates all pages of the file.
Returns:
A list of (filename, page_range) pairs.
|
Given a list of filenames and page ranges, return a list of (filename, page_range) pairs.
| 156 | 189 |
def parse_filename_page_ranges(
args: List[Union[str, PageRange, None]]
) -> List[Tuple[str, PageRange]]:
"""
Given a list of filenames and page ranges, return a list of (filename, page_range) pairs.
Args:
args: A list where the first element is a filename. The other elements are
filenames, page-range expressions, slice objects, or PageRange objects.
A filename not followed by a page range indicates all pages of the file.
Returns:
A list of (filename, page_range) pairs.
"""
pairs: List[Tuple[str, PageRange]] = []
pdf_filename = None
did_page_range = False
for arg in args + [None]:
if PageRange.valid(arg):
if not pdf_filename:
raise ValueError(
"The first argument must be a filename, not a page range."
)
pairs.append((pdf_filename, PageRange(arg)))
did_page_range = True
else:
# New filename or end of list--do all of the previous file?
if pdf_filename and not did_page_range:
pairs.append((pdf_filename, PAGE_RANGE_ALL))
pdf_filename = arg
did_page_range = False
return pairs
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/pagerange.py#L156-L189
| 39 |
[
0,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33
] | 64.705882 |
[] | 0 | false | 100 | 34 | 6 | 100 | 9 |
def parse_filename_page_ranges(
args: List[Union[str, PageRange, None]]
) -> List[Tuple[str, PageRange]]:
pairs: List[Tuple[str, PageRange]] = []
pdf_filename = None
did_page_range = False
for arg in args + [None]:
if PageRange.valid(arg):
if not pdf_filename:
raise ValueError(
"The first argument must be a filename, not a page range."
)
pairs.append((pdf_filename, PageRange(arg)))
did_page_range = True
else:
# New filename or end of list--do all of the previous file?
if pdf_filename and not did_page_range:
pairs.append((pdf_filename, PAGE_RANGE_ALL))
pdf_filename = arg
did_page_range = False
return pairs
| 24,023 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/pagerange.py
|
PageRange.__init__
|
(self, arg: Union[slice, "PageRange", str])
|
Initialize with either a slice -- giving the equivalent page range,
or a PageRange object -- making a copy,
or a string like
"int", "[int]:[int]" or "[int]:[int]:[int]",
where the brackets indicate optional ints.
Remember, page indices start with zero.
Page range expression examples:
: all pages. -1 last page.
22 just the 23rd page. :-1 all but the last page.
0:3 the first three pages. -2 second-to-last page.
:3 the first three pages. -2: last two pages.
5: from the sixth page onward. -3:-1 third & second to last.
The third, "stride" or "step" number is also recognized.
::2 0 2 4 ... to the end. 3:0:-1 3 2 1 but not 0.
1:10:2 1 3 5 7 9 2::-1 2 1 0.
::-1 all pages in reverse order.
Note the difference between this notation and arguments to slice():
slice(3) means the first three pages;
PageRange("3") means the range of only the fourth page.
However PageRange(slice(3)) means the first three pages.
|
Initialize with either a slice -- giving the equivalent page range,
or a PageRange object -- making a copy,
or a string like
"int", "[int]:[int]" or "[int]:[int]:[int]",
where the brackets indicate optional ints.
Remember, page indices start with zero.
Page range expression examples:
: all pages. -1 last page.
22 just the 23rd page. :-1 all but the last page.
0:3 the first three pages. -2 second-to-last page.
:3 the first three pages. -2: last two pages.
5: from the sixth page onward. -3:-1 third & second to last.
The third, "stride" or "step" number is also recognized.
::2 0 2 4 ... to the end. 3:0:-1 3 2 1 but not 0.
1:10:2 1 3 5 7 9 2::-1 2 1 0.
::-1 all pages in reverse order.
Note the difference between this notation and arguments to slice():
slice(3) means the first three pages;
PageRange("3") means the range of only the fourth page.
However PageRange(slice(3)) means the first three pages.
| 37 | 77 |
def __init__(self, arg: Union[slice, "PageRange", str]) -> None:
"""
Initialize with either a slice -- giving the equivalent page range,
or a PageRange object -- making a copy,
or a string like
"int", "[int]:[int]" or "[int]:[int]:[int]",
where the brackets indicate optional ints.
Remember, page indices start with zero.
Page range expression examples:
: all pages. -1 last page.
22 just the 23rd page. :-1 all but the last page.
0:3 the first three pages. -2 second-to-last page.
:3 the first three pages. -2: last two pages.
5: from the sixth page onward. -3:-1 third & second to last.
The third, "stride" or "step" number is also recognized.
::2 0 2 4 ... to the end. 3:0:-1 3 2 1 but not 0.
1:10:2 1 3 5 7 9 2::-1 2 1 0.
::-1 all pages in reverse order.
Note the difference between this notation and arguments to slice():
slice(3) means the first three pages;
PageRange("3") means the range of only the fourth page.
However PageRange(slice(3)) means the first three pages.
"""
if isinstance(arg, slice):
self._slice = arg
return
if isinstance(arg, PageRange):
self._slice = arg.to_slice()
return
m = isinstance(arg, str) and re.match(PAGE_RANGE_RE, arg)
if not m:
raise ParseError(arg)
elif m.group(2):
# Special case: just an int means a range of one page.
start = int(m.group(2))
stop = start + 1 if start != -1 else None
self._slice = slice(start, stop)
else:
self._slice = slice(*[int(g) if g else None for g in m.group(4, 6, 8)])
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/pagerange.py#L37-L77
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40
] | 100 |
[] | 0 | true | 100 | 41 | 7 | 100 | 20 |
def __init__(self, arg: Union[slice, "PageRange", str]) -> None:
if isinstance(arg, slice):
self._slice = arg
return
if isinstance(arg, PageRange):
self._slice = arg.to_slice()
return
m = isinstance(arg, str) and re.match(PAGE_RANGE_RE, arg)
if not m:
raise ParseError(arg)
elif m.group(2):
# Special case: just an int means a range of one page.
start = int(m.group(2))
stop = start + 1 if start != -1 else None
self._slice = slice(start, stop)
else:
self._slice = slice(*[int(g) if g else None for g in m.group(4, 6, 8)])
| 24,024 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/pagerange.py
|
PageRange.valid
|
(input: Any)
|
return isinstance(input, (slice, PageRange)) or (
isinstance(input, str) and bool(re.match(PAGE_RANGE_RE, input))
)
|
True if input is a valid initializer for a PageRange.
Args:
input: A possible PageRange string or a PageRange object.
Returns:
True, if the ``input`` is a valid PageRange.
|
True if input is a valid initializer for a PageRange.
| 80 | 92 |
def valid(input: Any) -> bool:
"""
True if input is a valid initializer for a PageRange.
Args:
input: A possible PageRange string or a PageRange object.
Returns:
True, if the ``input`` is a valid PageRange.
"""
return isinstance(input, (slice, PageRange)) or (
isinstance(input, str) and bool(re.match(PAGE_RANGE_RE, input))
)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/pagerange.py#L80-L92
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12
] | 100 |
[] | 0 | true | 100 | 13 | 3 | 100 | 7 |
def valid(input: Any) -> bool:
return isinstance(input, (slice, PageRange)) or (
isinstance(input, str) and bool(re.match(PAGE_RANGE_RE, input))
)
| 24,025 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/pagerange.py
|
PageRange.to_slice
|
(self)
|
return self._slice
|
Return the slice equivalent of this page range.
|
Return the slice equivalent of this page range.
| 94 | 96 |
def to_slice(self) -> slice:
"""Return the slice equivalent of this page range."""
return self._slice
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/pagerange.py#L94-L96
| 39 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 100 | 3 | 1 | 100 | 1 |
def to_slice(self) -> slice:
return self._slice
| 24,026 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/pagerange.py
|
PageRange.__str__
|
(self)
|
return ":".join("" if i is None else str(i) for i in indices)
|
A string like "1:2:3".
|
A string like "1:2:3".
| 98 | 109 |
def __str__(self) -> str:
"""A string like "1:2:3"."""
s = self._slice
indices: Union[Tuple[int, int], Tuple[int, int, int]]
if s.step is None:
if s.start is not None and s.stop == s.start + 1:
return str(s.start)
indices = s.start, s.stop
else:
indices = s.start, s.stop, s.step
return ":".join("" if i is None else str(i) for i in indices)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/pagerange.py#L98-L109
| 39 |
[] | 0 |
[] | 0 | false | 100 | 12 | 4 | 100 | 1 |
def __str__(self) -> str:
s = self._slice
indices: Union[Tuple[int, int], Tuple[int, int, int]]
if s.step is None:
if s.start is not None and s.stop == s.start + 1:
return str(s.start)
indices = s.start, s.stop
else:
indices = s.start, s.stop, s.step
return ":".join("" if i is None else str(i) for i in indices)
| 24,027 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/pagerange.py
|
PageRange.__repr__
|
(self)
|
return "PageRange(" + repr(str(self)) + ")"
|
A string like "PageRange('1:2:3')".
|
A string like "PageRange('1:2:3')".
| 111 | 113 |
def __repr__(self) -> str:
"""A string like "PageRange('1:2:3')"."""
return "PageRange(" + repr(str(self)) + ")"
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/pagerange.py#L111-L113
| 39 |
[] | 0 |
[] | 0 | false | 100 | 3 | 1 | 100 | 1 |
def __repr__(self) -> str:
return "PageRange(" + repr(str(self)) + ")"
| 24,028 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/pagerange.py
|
PageRange.indices
|
(self, n: int)
|
return self._slice.indices(n)
|
Assuming a sequence of length n, calculate the start and stop
indices, and the stride length of the PageRange.
See help(slice.indices).
Args:
n: the length of the list of pages to choose from.
Returns:
Arguments for range()
|
Assuming a sequence of length n, calculate the start and stop
indices, and the stride length of the PageRange.
| 115 | 128 |
def indices(self, n: int) -> Tuple[int, int, int]:
"""
Assuming a sequence of length n, calculate the start and stop
indices, and the stride length of the PageRange.
See help(slice.indices).
Args:
n: the length of the list of pages to choose from.
Returns:
Arguments for range()
"""
return self._slice.indices(n)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/pagerange.py#L115-L128
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13
] | 100 |
[] | 0 | true | 100 | 14 | 1 | 100 | 10 |
def indices(self, n: int) -> Tuple[int, int, int]:
return self._slice.indices(n)
| 24,029 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/pagerange.py
|
PageRange.__eq__
|
(self, other: Any)
|
return self._slice == other._slice
| 130 | 133 |
def __eq__(self, other: Any) -> bool:
if not isinstance(other, PageRange):
return False
return self._slice == other._slice
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/pagerange.py#L130-L133
| 39 |
[
0,
1,
2,
3
] | 100 |
[] | 0 | true | 100 | 4 | 2 | 100 | 0 |
def __eq__(self, other: Any) -> bool:
if not isinstance(other, PageRange):
return False
return self._slice == other._slice
| 24,030 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/pagerange.py
|
PageRange.__add__
|
(self, other: "PageRange")
|
return PageRange(slice(a[0], max(a[1], b[1])))
| 135 | 150 |
def __add__(self, other: "PageRange") -> "PageRange":
if not isinstance(other, PageRange):
raise TypeError(f"Can't add PageRange and {type(other)}")
if self._slice.step is not None or other._slice.step is not None:
raise ValueError("Can't add PageRange with stride")
a = self._slice.start, self._slice.stop
b = other._slice.start, other._slice.stop
if a[0] > b[0]:
a, b = b, a
# Now a[0] is the smallest
if b[0] > a[1]:
# There is a gap between a and b.
raise ValueError("Can't add PageRanges with gap")
return PageRange(slice(a[0], max(a[1], b[1])))
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/pagerange.py#L135-L150
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
] | 100 |
[] | 0 | true | 100 | 16 | 6 | 100 | 0 |
def __add__(self, other: "PageRange") -> "PageRange":
if not isinstance(other, PageRange):
raise TypeError(f"Can't add PageRange and {type(other)}")
if self._slice.step is not None or other._slice.step is not None:
raise ValueError("Can't add PageRange with stride")
a = self._slice.start, self._slice.stop
b = other._slice.start, other._slice.stop
if a[0] > b[0]:
a, b = b, a
# Now a[0] is the smallest
if b[0] > a[1]:
# There is a gap between a and b.
raise ValueError("Can't add PageRanges with gap")
return PageRange(slice(a[0], max(a[1], b[1])))
| 24,031 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_cmap.py
|
build_char_map
|
(
font_name: str, space_width: float, obj: DictionaryObject
)
|
return (
font_type,
float(sp_width / 2),
encoding,
# https://github.com/python/mypy/issues/4374
map_dict,
ft,
)
|
Determine information about a font.
This function returns a tuple consisting of:
font sub-type, space_width/2, encoding, map character-map, font-dictionary.
The font-dictionary itself is suitable for the curious.
|
Determine information about a font.
| 13 | 68 |
def build_char_map(
font_name: str, space_width: float, obj: DictionaryObject
) -> Tuple[
str, float, Union[str, Dict[int, str]], Dict, DictionaryObject
]: # font_type,space_width /2, encoding, cmap
"""Determine information about a font.
This function returns a tuple consisting of:
font sub-type, space_width/2, encoding, map character-map, font-dictionary.
The font-dictionary itself is suitable for the curious."""
ft: DictionaryObject = obj["/Resources"]["/Font"][font_name] # type: ignore
font_type: str = cast(str, ft["/Subtype"])
space_code = 32
encoding, space_code = parse_encoding(ft, space_code)
map_dict, space_code, int_entry = parse_to_unicode(ft, space_code)
# encoding can be either a string for decode (on 1,2 or a variable number of bytes) of a char table (for 1 byte only for me)
# if empty string, it means it is than encoding field is not present and we have to select the good encoding from cmap input data
if encoding == "":
if -1 not in map_dict or map_dict[-1] == 1:
# I have not been able to find any rule for no /Encoding nor /ToUnicode
# One example shows /Symbol,bold I consider 8 bits encoding default
encoding = "charmap"
else:
encoding = "utf-16-be"
# apply rule from PDF ref 1.7 §5.9.1, 1st bullet : if cmap not empty encoding should be discarded (here transformed into identity for those characters)
# if encoding is an str it is expected to be a identity translation
elif isinstance(encoding, dict):
for x in int_entry:
if x <= 255:
encoding[x] = chr(x)
try:
# override space_width with new params
space_width = _default_fonts_space_width[cast(str, ft["/BaseFont"])]
except Exception:
pass
# I conside the space_code is available on one byte
if isinstance(space_code, str):
try: # one byte
sp = space_code.encode("charmap")[0]
except Exception:
sp = space_code.encode("utf-16-be")
sp = sp[0] + 256 * sp[1]
else:
sp = space_code
sp_width = compute_space_width(ft, sp, space_width)
return (
font_type,
float(sp_width / 2),
encoding,
# https://github.com/python/mypy/issues/4374
map_dict,
ft,
)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_cmap.py#L13-L68
| 39 |
[
0,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
45,
46,
47,
48
] | 64.285714 |
[
25
] | 1.785714 | false | 95.988539 | 56 | 10 | 98.214286 | 5 |
def build_char_map(
font_name: str, space_width: float, obj: DictionaryObject
) -> Tuple[
str, float, Union[str, Dict[int, str]], Dict, DictionaryObject
]: # font_type,space_width /2, encoding, cmap
ft: DictionaryObject = obj["/Resources"]["/Font"][font_name] # type: ignore
font_type: str = cast(str, ft["/Subtype"])
space_code = 32
encoding, space_code = parse_encoding(ft, space_code)
map_dict, space_code, int_entry = parse_to_unicode(ft, space_code)
# encoding can be either a string for decode (on 1,2 or a variable number of bytes) of a char table (for 1 byte only for me)
# if empty string, it means it is than encoding field is not present and we have to select the good encoding from cmap input data
if encoding == "":
if -1 not in map_dict or map_dict[-1] == 1:
# I have not been able to find any rule for no /Encoding nor /ToUnicode
# One example shows /Symbol,bold I consider 8 bits encoding default
encoding = "charmap"
else:
encoding = "utf-16-be"
# apply rule from PDF ref 1.7 §5.9.1, 1st bullet : if cmap not empty encoding should be discarded (here transformed into identity for those characters)
# if encoding is an str it is expected to be a identity translation
elif isinstance(encoding, dict):
for x in int_entry:
if x <= 255:
encoding[x] = chr(x)
try:
# override space_width with new params
space_width = _default_fonts_space_width[cast(str, ft["/BaseFont"])]
except Exception:
pass
# I conside the space_code is available on one byte
if isinstance(space_code, str):
try: # one byte
sp = space_code.encode("charmap")[0]
except Exception:
sp = space_code.encode("utf-16-be")
sp = sp[0] + 256 * sp[1]
else:
sp = space_code
sp_width = compute_space_width(ft, sp, space_width)
return (
font_type,
float(sp_width / 2),
encoding,
# https://github.com/python/mypy/issues/4374
map_dict,
ft,
)
| 24,032 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_cmap.py
|
parse_encoding
|
(
ft: DictionaryObject, space_code: int
)
|
return encoding, space_code
| 113 | 174 |
def parse_encoding(
ft: DictionaryObject, space_code: int
) -> Tuple[Union[str, Dict[int, str]], int]:
encoding: Union[str, List[str], Dict[int, str]] = []
if "/Encoding" not in ft:
try:
if "/BaseFont" in ft and cast(str, ft["/BaseFont"]) in charset_encoding:
encoding = dict(
zip(range(256), charset_encoding[cast(str, ft["/BaseFont"])])
)
else:
encoding = "charmap"
return encoding, _default_fonts_space_width[cast(str, ft["/BaseFont"])]
except Exception:
if cast(str, ft["/Subtype"]) == "/Type1":
return "charmap", space_code
else:
return "", space_code
enc: Union(str, DictionaryObject) = ft["/Encoding"].get_object() # type: ignore
if isinstance(enc, str):
try:
# allready done : enc = NameObject.unnumber(enc.encode()).decode() # for #xx decoding
if enc in charset_encoding:
encoding = charset_encoding[enc].copy()
elif enc in _predefined_cmap:
encoding = _predefined_cmap[enc]
else:
raise Exception("not found")
except Exception:
warnings.warn(
f"Advanced encoding {enc} not implemented yet",
PdfReadWarning,
)
encoding = enc
elif isinstance(enc, DictionaryObject) and "/BaseEncoding" in enc:
try:
encoding = charset_encoding[cast(str, enc["/BaseEncoding"])].copy()
except Exception:
warnings.warn(
f"Advanced encoding {encoding} not implemented yet",
PdfReadWarning,
)
encoding = charset_encoding["/StandardCoding"].copy()
else:
encoding = charset_encoding["/StandardCoding"].copy()
if "/Differences" in enc:
x: int = 0
o: Union[int, str]
for o in cast(DictionaryObject, cast(DictionaryObject, enc)["/Differences"]):
if isinstance(o, int):
x = o
else: # isinstance(o,str):
try:
encoding[x] = adobe_glyphs[o] # type: ignore
except Exception:
encoding[x] = o # type: ignore
if o == " ":
space_code = x
x += 1
if isinstance(encoding, list):
encoding = dict(zip(range(256), encoding))
return encoding, space_code
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_cmap.py#L113-L174
| 39 |
[
0,
3,
4,
5,
6,
7,
11,
12,
13,
14,
15,
17,
18,
19,
20,
21,
22,
23,
24,
25,
27,
28,
29,
33,
34,
35,
36,
44,
45,
46,
48,
49,
50,
52,
53,
54,
55,
56,
58,
59,
60,
61
] | 67.741935 |
[
37,
38,
42,
57
] | 6.451613 | false | 95.988539 | 62 | 19 | 93.548387 | 0 |
def parse_encoding(
ft: DictionaryObject, space_code: int
) -> Tuple[Union[str, Dict[int, str]], int]:
encoding: Union[str, List[str], Dict[int, str]] = []
if "/Encoding" not in ft:
try:
if "/BaseFont" in ft and cast(str, ft["/BaseFont"]) in charset_encoding:
encoding = dict(
zip(range(256), charset_encoding[cast(str, ft["/BaseFont"])])
)
else:
encoding = "charmap"
return encoding, _default_fonts_space_width[cast(str, ft["/BaseFont"])]
except Exception:
if cast(str, ft["/Subtype"]) == "/Type1":
return "charmap", space_code
else:
return "", space_code
enc: Union(str, DictionaryObject) = ft["/Encoding"].get_object() # type: ignore
if isinstance(enc, str):
try:
# allready done : enc = NameObject.unnumber(enc.encode()).decode() # for #xx decoding
if enc in charset_encoding:
encoding = charset_encoding[enc].copy()
elif enc in _predefined_cmap:
encoding = _predefined_cmap[enc]
else:
raise Exception("not found")
except Exception:
warnings.warn(
f"Advanced encoding {enc} not implemented yet",
PdfReadWarning,
)
encoding = enc
elif isinstance(enc, DictionaryObject) and "/BaseEncoding" in enc:
try:
encoding = charset_encoding[cast(str, enc["/BaseEncoding"])].copy()
except Exception:
warnings.warn(
f"Advanced encoding {encoding} not implemented yet",
PdfReadWarning,
)
encoding = charset_encoding["/StandardCoding"].copy()
else:
encoding = charset_encoding["/StandardCoding"].copy()
if "/Differences" in enc:
x: int = 0
o: Union[int, str]
for o in cast(DictionaryObject, cast(DictionaryObject, enc)["/Differences"]):
if isinstance(o, int):
x = o
else: # isinstance(o,str):
try:
encoding[x] = adobe_glyphs[o] # type: ignore
except Exception:
encoding[x] = o # type: ignore
if o == " ":
space_code = x
x += 1
if isinstance(encoding, list):
encoding = dict(zip(range(256), encoding))
return encoding, space_code
| 24,033 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_cmap.py
|
parse_to_unicode
|
(
ft: DictionaryObject, space_code: int
)
|
return map_dict, space_code, int_entry
| 177 | 208 |
def parse_to_unicode(
ft: DictionaryObject, space_code: int
) -> Tuple[Dict[Any, Any], int, List[int]]:
# will store all translation code
# and map_dict[-1] we will have the number of bytes to convert
map_dict: Dict[Any, Any] = {}
# will provide the list of cmap keys as int to correct encoding
int_entry: List[int] = []
if "/ToUnicode" not in ft:
return {}, space_code, []
process_rg: bool = False
process_char: bool = False
multiline_rg: Union[
None, Tuple[int, int]
] = None # tuple = (current_char, remaining size) ; cf #1285 for example of file
cm = prepare_cm(ft)
for line in cm.split(b"\n"):
process_rg, process_char, multiline_rg = process_cm_line(
line.strip(b" "),
process_rg,
process_char,
multiline_rg,
map_dict,
int_entry,
)
for a, value in map_dict.items():
if value == " ":
space_code = a
return map_dict, space_code, int_entry
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_cmap.py#L177-L208
| 39 |
[
0,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
17,
18,
19,
27,
28,
29,
30,
31
] | 62.5 |
[] | 0 | false | 95.988539 | 32 | 5 | 100 | 0 |
def parse_to_unicode(
ft: DictionaryObject, space_code: int
) -> Tuple[Dict[Any, Any], int, List[int]]:
# will store all translation code
# and map_dict[-1] we will have the number of bytes to convert
map_dict: Dict[Any, Any] = {}
# will provide the list of cmap keys as int to correct encoding
int_entry: List[int] = []
if "/ToUnicode" not in ft:
return {}, space_code, []
process_rg: bool = False
process_char: bool = False
multiline_rg: Union[
None, Tuple[int, int]
] = None # tuple = (current_char, remaining size) ; cf #1285 for example of file
cm = prepare_cm(ft)
for line in cm.split(b"\n"):
process_rg, process_char, multiline_rg = process_cm_line(
line.strip(b" "),
process_rg,
process_char,
multiline_rg,
map_dict,
int_entry,
)
for a, value in map_dict.items():
if value == " ":
space_code = a
return map_dict, space_code, int_entry
| 24,034 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_cmap.py
|
prepare_cm
|
(ft: DictionaryObject)
|
return cm
| 211 | 247 |
def prepare_cm(ft: DictionaryObject) -> bytes:
tu = ft["/ToUnicode"]
cm: bytes
if isinstance(tu, StreamObject):
cm = cast(DecodedStreamObject, ft["/ToUnicode"]).get_data()
elif isinstance(tu, str) and tu.startswith("/Identity"):
cm = b"beginbfrange\n<0000> <0001> <0000>\nendbfrange" # the full range 0000-FFFF will be processed
if isinstance(cm, str):
cm = cm.encode()
# we need to prepare cm before due to missing return line in pdf printed to pdf from word
cm = (
cm.strip()
.replace(b"beginbfchar", b"\nbeginbfchar\n")
.replace(b"endbfchar", b"\nendbfchar\n")
.replace(b"beginbfrange", b"\nbeginbfrange\n")
.replace(b"endbfrange", b"\nendbfrange\n")
.replace(b"<<", b"\n{\n") # text between << and >> not used but
.replace(b">>", b"\n}\n") # some solution to find it back
)
ll = cm.split(b"<")
for i in range(len(ll)):
j = ll[i].find(b">")
if j >= 0:
if j == 0:
# string is empty: stash a placeholder here (see below)
# see https://github.com/py-pdf/pypdf/issues/1111
content = b"."
else:
content = ll[i][:j].replace(b" ", b"")
ll[i] = content + b" " + ll[i][j + 1 :]
cm = (
(b" ".join(ll))
.replace(b"[", b" [ ")
.replace(b"]", b" ]\n ")
.replace(b"\r", b"\n")
)
return cm
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_cmap.py#L211-L247
| 39 |
[
0,
1,
3,
4,
5,
6,
7,
8,
9,
10,
19,
20,
21,
22,
23,
24,
25,
28,
29,
30,
36
] | 56.756757 |
[
26
] | 2.702703 | false | 95.988539 | 37 | 8 | 97.297297 | 0 |
def prepare_cm(ft: DictionaryObject) -> bytes:
tu = ft["/ToUnicode"]
cm: bytes
if isinstance(tu, StreamObject):
cm = cast(DecodedStreamObject, ft["/ToUnicode"]).get_data()
elif isinstance(tu, str) and tu.startswith("/Identity"):
cm = b"beginbfrange\n<0000> <0001> <0000>\nendbfrange" # the full range 0000-FFFF will be processed
if isinstance(cm, str):
cm = cm.encode()
# we need to prepare cm before due to missing return line in pdf printed to pdf from word
cm = (
cm.strip()
.replace(b"beginbfchar", b"\nbeginbfchar\n")
.replace(b"endbfchar", b"\nendbfchar\n")
.replace(b"beginbfrange", b"\nbeginbfrange\n")
.replace(b"endbfrange", b"\nendbfrange\n")
.replace(b"<<", b"\n{\n") # text between << and >> not used but
.replace(b">>", b"\n}\n") # some solution to find it back
)
ll = cm.split(b"<")
for i in range(len(ll)):
j = ll[i].find(b">")
if j >= 0:
if j == 0:
# string is empty: stash a placeholder here (see below)
# see https://github.com/py-pdf/pypdf/issues/1111
content = b"."
else:
content = ll[i][:j].replace(b" ", b"")
ll[i] = content + b" " + ll[i][j + 1 :]
cm = (
(b" ".join(ll))
.replace(b"[", b" [ ")
.replace(b"]", b" ]\n ")
.replace(b"\r", b"\n")
)
return cm
| 24,035 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_cmap.py
|
process_cm_line
|
(
line: bytes,
process_rg: bool,
process_char: bool,
multiline_rg: Union[None, Tuple[int, int]],
map_dict: Dict[Any, Any],
int_entry: List[int],
)
|
return process_rg, process_char, multiline_rg
| 250 | 272 |
def process_cm_line(
line: bytes,
process_rg: bool,
process_char: bool,
multiline_rg: Union[None, Tuple[int, int]],
map_dict: Dict[Any, Any],
int_entry: List[int],
) -> Tuple[bool, bool, Union[None, Tuple[int, int]]]:
if line in (b"", b" ") or line[0] == 37: # 37 = %
return process_rg, process_char, multiline_rg
if b"beginbfrange" in line:
process_rg = True
elif b"endbfrange" in line:
process_rg = False
elif b"beginbfchar" in line:
process_char = True
elif b"endbfchar" in line:
process_char = False
elif process_rg:
multiline_rg = parse_bfrange(line, map_dict, int_entry, multiline_rg)
elif process_char:
parse_bfchar(line, map_dict, int_entry)
return process_rg, process_char, multiline_rg
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_cmap.py#L250-L272
| 39 |
[
0,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22
] | 69.565217 |
[] | 0 | false | 95.988539 | 23 | 9 | 100 | 0 |
def process_cm_line(
line: bytes,
process_rg: bool,
process_char: bool,
multiline_rg: Union[None, Tuple[int, int]],
map_dict: Dict[Any, Any],
int_entry: List[int],
) -> Tuple[bool, bool, Union[None, Tuple[int, int]]]:
if line in (b"", b" ") or line[0] == 37: # 37 = %
return process_rg, process_char, multiline_rg
if b"beginbfrange" in line:
process_rg = True
elif b"endbfrange" in line:
process_rg = False
elif b"beginbfchar" in line:
process_char = True
elif b"endbfchar" in line:
process_char = False
elif process_rg:
multiline_rg = parse_bfrange(line, map_dict, int_entry, multiline_rg)
elif process_char:
parse_bfchar(line, map_dict, int_entry)
return process_rg, process_char, multiline_rg
| 24,036 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_cmap.py
|
parse_bfrange
|
(
line: bytes,
map_dict: Dict[Any, Any],
int_entry: List[int],
multiline_rg: Union[None, Tuple[int, int]],
)
|
return None if closure_found else (a, b)
| 275 | 331 |
def parse_bfrange(
line: bytes,
map_dict: Dict[Any, Any],
int_entry: List[int],
multiline_rg: Union[None, Tuple[int, int]],
) -> Union[None, Tuple[int, int]]:
lst = [x for x in line.split(b" ") if x]
closure_found = False
nbi = max(len(lst[0]), len(lst[1]))
map_dict[-1] = ceil(nbi / 2)
fmt = b"%%0%dX" % (map_dict[-1] * 2)
if multiline_rg is not None:
a = multiline_rg[0] # a, b not in the current line
b = multiline_rg[1]
for sq in lst[1:]:
if sq == b"]":
closure_found = True
break
map_dict[
unhexlify(fmt % a).decode(
"charmap" if map_dict[-1] == 1 else "utf-16-be",
"surrogatepass",
)
] = unhexlify(sq).decode("utf-16-be", "surrogatepass")
int_entry.append(a)
a += 1
else:
a = int(lst[0], 16)
b = int(lst[1], 16)
if lst[2] == b"[":
for sq in lst[3:]:
if sq == b"]":
closure_found = True
break
map_dict[
unhexlify(fmt % a).decode(
"charmap" if map_dict[-1] == 1 else "utf-16-be",
"surrogatepass",
)
] = unhexlify(sq).decode("utf-16-be", "surrogatepass")
int_entry.append(a)
a += 1
else: # case without list
c = int(lst[2], 16)
fmt2 = b"%%0%dX" % max(4, len(lst[2]))
closure_found = True
while a <= b:
map_dict[
unhexlify(fmt % a).decode(
"charmap" if map_dict[-1] == 1 else "utf-16-be",
"surrogatepass",
)
] = unhexlify(fmt2 % c).decode("utf-16-be", "surrogatepass")
int_entry.append(a)
a += 1
c += 1
return None if closure_found else (a, b)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_cmap.py#L275-L331
| 39 |
[
0,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
24,
25,
27,
28,
29,
30,
31,
32,
33,
34,
40,
41,
43,
44,
45,
46,
47,
53,
54,
55,
56
] | 61.403509 |
[] | 0 | false | 95.988539 | 57 | 9 | 100 | 0 |
def parse_bfrange(
line: bytes,
map_dict: Dict[Any, Any],
int_entry: List[int],
multiline_rg: Union[None, Tuple[int, int]],
) -> Union[None, Tuple[int, int]]:
lst = [x for x in line.split(b" ") if x]
closure_found = False
nbi = max(len(lst[0]), len(lst[1]))
map_dict[-1] = ceil(nbi / 2)
fmt = b"%%0%dX" % (map_dict[-1] * 2)
if multiline_rg is not None:
a = multiline_rg[0] # a, b not in the current line
b = multiline_rg[1]
for sq in lst[1:]:
if sq == b"]":
closure_found = True
break
map_dict[
unhexlify(fmt % a).decode(
"charmap" if map_dict[-1] == 1 else "utf-16-be",
"surrogatepass",
)
] = unhexlify(sq).decode("utf-16-be", "surrogatepass")
int_entry.append(a)
a += 1
else:
a = int(lst[0], 16)
b = int(lst[1], 16)
if lst[2] == b"[":
for sq in lst[3:]:
if sq == b"]":
closure_found = True
break
map_dict[
unhexlify(fmt % a).decode(
"charmap" if map_dict[-1] == 1 else "utf-16-be",
"surrogatepass",
)
] = unhexlify(sq).decode("utf-16-be", "surrogatepass")
int_entry.append(a)
a += 1
else: # case without list
c = int(lst[2], 16)
fmt2 = b"%%0%dX" % max(4, len(lst[2]))
closure_found = True
while a <= b:
map_dict[
unhexlify(fmt % a).decode(
"charmap" if map_dict[-1] == 1 else "utf-16-be",
"surrogatepass",
)
] = unhexlify(fmt2 % c).decode("utf-16-be", "surrogatepass")
int_entry.append(a)
a += 1
c += 1
return None if closure_found else (a, b)
| 24,037 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_cmap.py
|
parse_bfchar
|
(l: bytes, map_dict: Dict[Any, Any], int_entry: List[int])
| 334 | 350 |
def parse_bfchar(l: bytes, map_dict: Dict[Any, Any], int_entry: List[int]) -> None:
lst = [x for x in l.split(b" ") if x]
map_dict[-1] = len(lst[0]) // 2
while len(lst) > 1:
map_to = ""
# placeholder (see above) means empty string
if lst[1] != b".":
map_to = unhexlify(lst[1]).decode(
"charmap" if len(lst[1]) < 4 else "utf-16-be", "surrogatepass"
) # join is here as some cases where the code was split
map_dict[
unhexlify(lst[0]).decode(
"charmap" if map_dict[-1] == 1 else "utf-16-be", "surrogatepass"
)
] = map_to
int_entry.append(int(lst[0], 16))
lst = lst[2:]
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_cmap.py#L334-L350
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
10,
15,
16
] | 64.705882 |
[] | 0 | false | 95.988539 | 17 | 4 | 100 | 0 |
def parse_bfchar(l: bytes, map_dict: Dict[Any, Any], int_entry: List[int]) -> None:
lst = [x for x in l.split(b" ") if x]
map_dict[-1] = len(lst[0]) // 2
while len(lst) > 1:
map_to = ""
# placeholder (see above) means empty string
if lst[1] != b".":
map_to = unhexlify(lst[1]).decode(
"charmap" if len(lst[1]) < 4 else "utf-16-be", "surrogatepass"
) # join is here as some cases where the code was split
map_dict[
unhexlify(lst[0]).decode(
"charmap" if map_dict[-1] == 1 else "utf-16-be", "surrogatepass"
)
] = map_to
int_entry.append(int(lst[0], 16))
lst = lst[2:]
| 24,038 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_cmap.py
|
compute_space_width
|
(
ft: DictionaryObject, space_code: int, space_width: float
)
|
return sp_width
| 353 | 418 |
def compute_space_width(
ft: DictionaryObject, space_code: int, space_width: float
) -> float:
sp_width: float = space_width * 2.0 # default value
w = []
w1 = {}
st: int = 0
if "/DescendantFonts" in ft: # ft["/Subtype"].startswith("/CIDFontType"):
ft1 = ft["/DescendantFonts"][0].get_object() # type: ignore
try:
w1[-1] = cast(float, ft1["/DW"])
except Exception:
w1[-1] = 1000.0
if "/W" in ft1:
w = list(ft1["/W"])
else:
w = []
while len(w) > 0:
st = w[0]
second = w[1]
if isinstance(second, int):
for x in range(st, second):
w1[x] = w[2]
w = w[3:]
elif isinstance(second, list):
for y in second:
w1[st] = y
st += 1
w = w[2:]
else:
logger_warning(
"unknown widths : \n" + (ft1["/W"]).__repr__(),
__name__,
)
break
try:
sp_width = w1[space_code]
except Exception:
sp_width = (
w1[-1] / 2.0
) # if using default we consider space will be only half size
elif "/Widths" in ft:
w = list(ft["/Widths"]) # type: ignore
try:
st = cast(int, ft["/FirstChar"])
en: int = cast(int, ft["/LastChar"])
if st > space_code or en < space_code:
raise Exception("Not in range")
if w[space_code - st] == 0:
raise Exception("null width")
sp_width = w[space_code - st]
except Exception:
if "/FontDescriptor" in ft and "/MissingWidth" in cast(
DictionaryObject, ft["/FontDescriptor"]
):
sp_width = ft["/FontDescriptor"]["/MissingWidth"] # type: ignore
else:
# will consider width of char as avg(width)/2
m = 0
cpt = 0
for x in w:
if x > 0:
m += x
cpt += 1
sp_width = m / max(1, cpt) / 2
return sp_width
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_cmap.py#L353-L418
| 39 |
[
0,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
35,
36,
37,
38,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
55,
57,
58,
59,
60,
61,
62,
63,
64,
65
] | 78.787879 |
[
30,
34
] | 3.030303 | false | 95.988539 | 66 | 19 | 96.969697 | 0 |
def compute_space_width(
ft: DictionaryObject, space_code: int, space_width: float
) -> float:
sp_width: float = space_width * 2.0 # default value
w = []
w1 = {}
st: int = 0
if "/DescendantFonts" in ft: # ft["/Subtype"].startswith("/CIDFontType"):
ft1 = ft["/DescendantFonts"][0].get_object() # type: ignore
try:
w1[-1] = cast(float, ft1["/DW"])
except Exception:
w1[-1] = 1000.0
if "/W" in ft1:
w = list(ft1["/W"])
else:
w = []
while len(w) > 0:
st = w[0]
second = w[1]
if isinstance(second, int):
for x in range(st, second):
w1[x] = w[2]
w = w[3:]
elif isinstance(second, list):
for y in second:
w1[st] = y
st += 1
w = w[2:]
else:
logger_warning(
"unknown widths : \n" + (ft1["/W"]).__repr__(),
__name__,
)
break
try:
sp_width = w1[space_code]
except Exception:
sp_width = (
w1[-1] / 2.0
) # if using default we consider space will be only half size
elif "/Widths" in ft:
w = list(ft["/Widths"]) # type: ignore
try:
st = cast(int, ft["/FirstChar"])
en: int = cast(int, ft["/LastChar"])
if st > space_code or en < space_code:
raise Exception("Not in range")
if w[space_code - st] == 0:
raise Exception("null width")
sp_width = w[space_code - st]
except Exception:
if "/FontDescriptor" in ft and "/MissingWidth" in cast(
DictionaryObject, ft["/FontDescriptor"]
):
sp_width = ft["/FontDescriptor"]["/MissingWidth"] # type: ignore
else:
# will consider width of char as avg(width)/2
m = 0
cpt = 0
for x in w:
if x > 0:
m += x
cpt += 1
sp_width = m / max(1, cpt) / 2
return sp_width
| 24,039 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
set_custom_rtl
|
(
_min: Union[str, int, None] = None,
_max: Union[str, int, None] = None,
specials: Union[str, List[int], None] = None,
)
|
return CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS
|
Change the Right-To-Left and special characters custom parameters.
Args:
_min: The new minimum value for the range of custom characters that
will be written right to left.
If set to `None`, the value will not be changed.
If set to an integer or string, it will be converted to its ASCII code.
The default value is -1, which sets no additional range to be converted.
_max: The new maximum value for the range of custom characters that will be written right to left.
If set to `None`, the value will not be changed.
If set to an integer or string, it will be converted to its ASCII code.
The default value is -1, which sets no additional range to be converted.
specials: The new list of special characters to be inserted in the current insertion order.
If set to `None`, the current value will not be changed.
If set to a string, it will be converted to a list of ASCII codes.
The default value is an empty list.
Returns:
A tuple containing the new values for `CUSTOM_RTL_MIN`, `CUSTOM_RTL_MAX`, and `CUSTOM_RTL_SPECIAL_CHARS`.
|
Change the Right-To-Left and special characters custom parameters.
| 84 | 123 |
def set_custom_rtl(
_min: Union[str, int, None] = None,
_max: Union[str, int, None] = None,
specials: Union[str, List[int], None] = None,
) -> Tuple[int, int, List[int]]:
"""
Change the Right-To-Left and special characters custom parameters.
Args:
_min: The new minimum value for the range of custom characters that
will be written right to left.
If set to `None`, the value will not be changed.
If set to an integer or string, it will be converted to its ASCII code.
The default value is -1, which sets no additional range to be converted.
_max: The new maximum value for the range of custom characters that will be written right to left.
If set to `None`, the value will not be changed.
If set to an integer or string, it will be converted to its ASCII code.
The default value is -1, which sets no additional range to be converted.
specials: The new list of special characters to be inserted in the current insertion order.
If set to `None`, the current value will not be changed.
If set to a string, it will be converted to a list of ASCII codes.
The default value is an empty list.
Returns:
A tuple containing the new values for `CUSTOM_RTL_MIN`, `CUSTOM_RTL_MAX`, and `CUSTOM_RTL_SPECIAL_CHARS`.
"""
global CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS
if isinstance(_min, int):
CUSTOM_RTL_MIN = _min
elif isinstance(_min, str):
CUSTOM_RTL_MIN = ord(_min)
if isinstance(_max, int):
CUSTOM_RTL_MAX = _max
elif isinstance(_max, str):
CUSTOM_RTL_MAX = ord(_max)
if isinstance(specials, str):
CUSTOM_RTL_SPECIAL_CHARS = [ord(x) for x in specials]
elif isinstance(specials, list):
CUSTOM_RTL_SPECIAL_CHARS = specials
return CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L84-L123
| 39 |
[
0,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39
] | 35 |
[] | 0 | false | 91.202346 | 40 | 8 | 100 | 19 |
def set_custom_rtl(
_min: Union[str, int, None] = None,
_max: Union[str, int, None] = None,
specials: Union[str, List[int], None] = None,
) -> Tuple[int, int, List[int]]:
global CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS
if isinstance(_min, int):
CUSTOM_RTL_MIN = _min
elif isinstance(_min, str):
CUSTOM_RTL_MIN = ord(_min)
if isinstance(_max, int):
CUSTOM_RTL_MAX = _max
elif isinstance(_max, str):
CUSTOM_RTL_MAX = ord(_max)
if isinstance(specials, str):
CUSTOM_RTL_SPECIAL_CHARS = [ord(x) for x in specials]
elif isinstance(specials, list):
CUSTOM_RTL_SPECIAL_CHARS = specials
return CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS
| 24,040 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
_get_rectangle
|
(self: Any, name: str, defaults: Iterable[str])
|
return retval
| 126 | 139 |
def _get_rectangle(self: Any, name: str, defaults: Iterable[str]) -> RectangleObject:
retval: Union[None, RectangleObject, IndirectObject] = self.get(name)
if isinstance(retval, RectangleObject):
return retval
if retval is None:
for d in defaults:
retval = self.get(d)
if retval is not None:
break
if isinstance(retval, IndirectObject):
retval = self.pdf.get_object(retval)
retval = RectangleObject(retval) # type: ignore
_set_rectangle(self, name, retval)
return retval
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L126-L139
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13
] | 100 |
[] | 0 | true | 91.202346 | 14 | 6 | 100 | 0 |
def _get_rectangle(self: Any, name: str, defaults: Iterable[str]) -> RectangleObject:
retval: Union[None, RectangleObject, IndirectObject] = self.get(name)
if isinstance(retval, RectangleObject):
return retval
if retval is None:
for d in defaults:
retval = self.get(d)
if retval is not None:
break
if isinstance(retval, IndirectObject):
retval = self.pdf.get_object(retval)
retval = RectangleObject(retval) # type: ignore
_set_rectangle(self, name, retval)
return retval
| 24,041 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
getRectangle
|
(
self: Any, name: str, defaults: Iterable[str]
)
|
return _get_rectangle(self, name, defaults)
| 142 | 146 |
def getRectangle(
self: Any, name: str, defaults: Iterable[str]
) -> RectangleObject: # deprecated
deprecation_no_replacement("getRectangle", "3.0.0")
return _get_rectangle(self, name, defaults)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L142-L146
| 39 |
[] | 0 |
[] | 0 | false | 91.202346 | 5 | 1 | 100 | 0 |
def getRectangle(
self: Any, name: str, defaults: Iterable[str]
) -> RectangleObject: # deprecated
deprecation_no_replacement("getRectangle", "3.0.0")
return _get_rectangle(self, name, defaults)
| 24,042 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
_set_rectangle
|
(self: Any, name: str, value: Union[RectangleObject, float])
| 149 | 151 |
def _set_rectangle(self: Any, name: str, value: Union[RectangleObject, float]) -> None:
name = NameObject(name)
self[name] = value
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L149-L151
| 39 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 91.202346 | 3 | 1 | 100 | 0 |
def _set_rectangle(self: Any, name: str, value: Union[RectangleObject, float]) -> None:
name = NameObject(name)
self[name] = value
| 24,043 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
setRectangle
|
(
self: Any, name: str, value: Union[RectangleObject, float]
)
| 154 | 158 |
def setRectangle(
self: Any, name: str, value: Union[RectangleObject, float]
) -> None: # deprecated
deprecation_no_replacement("setRectangle", "3.0.0")
_set_rectangle(self, name, value)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L154-L158
| 39 |
[] | 0 |
[] | 0 | false | 91.202346 | 5 | 1 | 100 | 0 |
def setRectangle(
self: Any, name: str, value: Union[RectangleObject, float]
) -> None: # deprecated
deprecation_no_replacement("setRectangle", "3.0.0")
_set_rectangle(self, name, value)
| 24,044 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
_delete_rectangle
|
(self: Any, name: str)
| 161 | 162 |
def _delete_rectangle(self: Any, name: str) -> None:
del self[name]
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L161-L162
| 39 |
[
0,
1
] | 100 |
[] | 0 | true | 91.202346 | 2 | 1 | 100 | 0 |
def _delete_rectangle(self: Any, name: str) -> None:
del self[name]
| 24,045 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
deleteRectangle
|
(self: Any, name: str)
| 165 | 167 |
def deleteRectangle(self: Any, name: str) -> None: # deprecated
deprecation_no_replacement("deleteRectangle", "3.0.0")
del self[name]
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L165-L167
| 39 |
[] | 0 |
[] | 0 | false | 91.202346 | 3 | 1 | 100 | 0 |
def deleteRectangle(self: Any, name: str) -> None: # deprecated
deprecation_no_replacement("deleteRectangle", "3.0.0")
del self[name]
| 24,046 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
_create_rectangle_accessor
|
(name: str, fallback: Iterable[str])
|
return property(
lambda self: _get_rectangle(self, name, fallback),
lambda self, value: _set_rectangle(self, name, value),
lambda self: _delete_rectangle(self, name),
)
| 170 | 175 |
def _create_rectangle_accessor(name: str, fallback: Iterable[str]) -> property:
return property(
lambda self: _get_rectangle(self, name, fallback),
lambda self, value: _set_rectangle(self, name, value),
lambda self: _delete_rectangle(self, name),
)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L170-L175
| 39 |
[
0,
1
] | 33.333333 |
[] | 0 | false | 91.202346 | 6 | 1 | 100 | 0 |
def _create_rectangle_accessor(name: str, fallback: Iterable[str]) -> property:
return property(
lambda self: _get_rectangle(self, name, fallback),
lambda self, value: _set_rectangle(self, name, value),
lambda self: _delete_rectangle(self, name),
)
| 24,047 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
createRectangleAccessor
|
(
name: str, fallback: Iterable[str]
)
|
return _create_rectangle_accessor(name, fallback)
| 178 | 182 |
def createRectangleAccessor(
name: str, fallback: Iterable[str]
) -> property: # deprecated
deprecation_no_replacement("createRectangleAccessor", "3.0.0")
return _create_rectangle_accessor(name, fallback)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L178-L182
| 39 |
[] | 0 |
[] | 0 | false | 91.202346 | 5 | 1 | 100 | 0 |
def createRectangleAccessor(
name: str, fallback: Iterable[str]
) -> property: # deprecated
deprecation_no_replacement("createRectangleAccessor", "3.0.0")
return _create_rectangle_accessor(name, fallback)
| 24,048 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
_get_fonts_walk
|
(
obj: DictionaryObject,
fnt: Optional[Set[str]] = None,
emb: Optional[Set[str]] = None,
)
|
return fnt, emb
|
If there is a key called 'BaseFont', that is a font that is used in the document.
If there is a key called 'FontName' and another key in the same dictionary object
that is called 'FontFilex' (where x is null, 2, or 3), then that fontname is
embedded.
We create and add to two sets, fnt = fonts used and emb = fonts embedded.
|
If there is a key called 'BaseFont', that is a font that is used in the document.
If there is a key called 'FontName' and another key in the same dictionary object
that is called 'FontFilex' (where x is null, 2, or 3), then that fontname is
embedded.
| 2,085 | 2,114 |
def _get_fonts_walk(
obj: DictionaryObject,
fnt: Optional[Set[str]] = None,
emb: Optional[Set[str]] = None,
) -> Tuple[Set[str], Set[str]]:
"""
If there is a key called 'BaseFont', that is a font that is used in the document.
If there is a key called 'FontName' and another key in the same dictionary object
that is called 'FontFilex' (where x is null, 2, or 3), then that fontname is
embedded.
We create and add to two sets, fnt = fonts used and emb = fonts embedded.
"""
if fnt is None:
fnt = set()
if emb is None:
emb = set()
if not hasattr(obj, "keys"):
return set(), set()
fontkeys = ("/FontFile", "/FontFile2", "/FontFile3")
if "/BaseFont" in obj:
fnt.add(cast(str, obj["/BaseFont"]))
if "/FontName" in obj:
if [x for x in fontkeys if x in obj]: # test to see if there is FontFile
emb.add(cast(str, obj["/FontName"]))
for key in obj.keys():
_get_fonts_walk(cast(DictionaryObject, obj[key]), fnt, emb)
return fnt, emb
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L2085-L2114
| 39 |
[
0,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29
] | 63.333333 |
[] | 0 | false | 91.202346 | 30 | 9 | 100 | 6 |
def _get_fonts_walk(
obj: DictionaryObject,
fnt: Optional[Set[str]] = None,
emb: Optional[Set[str]] = None,
) -> Tuple[Set[str], Set[str]]:
if fnt is None:
fnt = set()
if emb is None:
emb = set()
if not hasattr(obj, "keys"):
return set(), set()
fontkeys = ("/FontFile", "/FontFile2", "/FontFile3")
if "/BaseFont" in obj:
fnt.add(cast(str, obj["/BaseFont"]))
if "/FontName" in obj:
if [x for x in fontkeys if x in obj]: # test to see if there is FontFile
emb.add(cast(str, obj["/FontName"]))
for key in obj.keys():
_get_fonts_walk(cast(DictionaryObject, obj[key]), fnt, emb)
return fnt, emb
| 24,049 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
Transformation.__init__
|
(self, ctm: CompressedTransformationMatrix = (1, 0, 0, 1, 0, 0))
| 215 | 216 |
def __init__(self, ctm: CompressedTransformationMatrix = (1, 0, 0, 1, 0, 0)):
self.ctm = ctm
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L215-L216
| 39 |
[
0,
1
] | 100 |
[] | 0 | true | 91.202346 | 2 | 1 | 100 | 0 |
def __init__(self, ctm: CompressedTransformationMatrix = (1, 0, 0, 1, 0, 0)):
self.ctm = ctm
| 24,050 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
Transformation.matrix
|
(self)
|
return (
(self.ctm[0], self.ctm[1], 0),
(self.ctm[2], self.ctm[3], 0),
(self.ctm[4], self.ctm[5], 1),
)
|
Return the transformation matrix as a tuple of tuples in the form:
((a, b, 0), (c, d, 0), (e, f, 1))
|
Return the transformation matrix as a tuple of tuples in the form:
((a, b, 0), (c, d, 0), (e, f, 1))
| 219 | 228 |
def matrix(self) -> TransformationMatrixType:
"""
Return the transformation matrix as a tuple of tuples in the form:
((a, b, 0), (c, d, 0), (e, f, 1))
"""
return (
(self.ctm[0], self.ctm[1], 0),
(self.ctm[2], self.ctm[3], 0),
(self.ctm[4], self.ctm[5], 1),
)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L219-L228
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 100 |
[] | 0 | true | 91.202346 | 10 | 1 | 100 | 2 |
def matrix(self) -> TransformationMatrixType:
return (
(self.ctm[0], self.ctm[1], 0),
(self.ctm[2], self.ctm[3], 0),
(self.ctm[4], self.ctm[5], 1),
)
| 24,051 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
Transformation.compress
|
(matrix: TransformationMatrixType)
|
return (
matrix[0][0],
matrix[0][1],
matrix[1][0],
matrix[1][1],
matrix[2][0],
matrix[2][1],
)
|
Compresses the transformation matrix into a tuple of (a, b, c, d, e, f).
Args:
matrix: The transformation matrix as a tuple of tuples.
Returns:
A tuple representing the transformation matrix as (a, b, c, d, e, f)
|
Compresses the transformation matrix into a tuple of (a, b, c, d, e, f).
| 231 | 248 |
def compress(matrix: TransformationMatrixType) -> CompressedTransformationMatrix:
"""
Compresses the transformation matrix into a tuple of (a, b, c, d, e, f).
Args:
matrix: The transformation matrix as a tuple of tuples.
Returns:
A tuple representing the transformation matrix as (a, b, c, d, e, f)
"""
return (
matrix[0][0],
matrix[0][1],
matrix[1][0],
matrix[1][1],
matrix[2][0],
matrix[2][1],
)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L231-L248
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17
] | 100 |
[] | 0 | true | 91.202346 | 18 | 1 | 100 | 7 |
def compress(matrix: TransformationMatrixType) -> CompressedTransformationMatrix:
return (
matrix[0][0],
matrix[0][1],
matrix[1][0],
matrix[1][1],
matrix[2][0],
matrix[2][1],
)
| 24,052 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_page.py
|
Transformation.translate
|
(self, tx: float = 0, ty: float = 0)
|
return Transformation(ctm=(m[0], m[1], m[2], m[3], m[4] + tx, m[5] + ty))
|
Translate the contents of a page.
Args:
tx: The translation along the x-axis.
ty: The translation along the y-axis.
Returns:
A new `Transformation` instance
|
Translate the contents of a page.
| 250 | 262 |
def translate(self, tx: float = 0, ty: float = 0) -> "Transformation":
"""
Translate the contents of a page.
Args:
tx: The translation along the x-axis.
ty: The translation along the y-axis.
Returns:
A new `Transformation` instance
"""
m = self.ctm
return Transformation(ctm=(m[0], m[1], m[2], m[3], m[4] + tx, m[5] + ty))
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_page.py#L250-L262
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12
] | 100 |
[] | 0 | true | 91.202346 | 13 | 1 | 100 | 8 |
def translate(self, tx: float = 0, ty: float = 0) -> "Transformation":
m = self.ctm
return Transformation(ctm=(m[0], m[1], m[2], m[3], m[4] + tx, m[5] + ty))
| 24,053 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.