repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.forget | def forget(self, *keys):
"""
Remove an item from the collection by key.
:param keys: The keys to remove
:type keys: tuple
:rtype: Collection
"""
keys = reversed(sorted(keys))
for key in keys:
del self[key]
return self | python | def forget(self, *keys):
"""
Remove an item from the collection by key.
:param keys: The keys to remove
:type keys: tuple
:rtype: Collection
"""
keys = reversed(sorted(keys))
for key in keys:
del self[key]
return self | [
"def",
"forget",
"(",
"self",
",",
"*",
"keys",
")",
":",
"keys",
"=",
"reversed",
"(",
"sorted",
"(",
"keys",
")",
")",
"for",
"key",
"in",
"keys",
":",
"del",
"self",
"[",
"key",
"]",
"return",
"self"
] | Remove an item from the collection by key.
:param keys: The keys to remove
:type keys: tuple
:rtype: Collection | [
"Remove",
"an",
"item",
"from",
"the",
"collection",
"by",
"key",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L308-L322 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.get | def get(self, key, default=None):
"""
Get an element of the collection.
:param key: The index of the element
:type key: mixed
:param default: The default value to return
:type default: mixed
:rtype: mixed
"""
try:
return self.items[k... | python | def get(self, key, default=None):
"""
Get an element of the collection.
:param key: The index of the element
:type key: mixed
:param default: The default value to return
:type default: mixed
:rtype: mixed
"""
try:
return self.items[k... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"items",
"[",
"key",
"]",
"except",
"IndexError",
":",
"return",
"value",
"(",
"default",
")"
] | Get an element of the collection.
:param key: The index of the element
:type key: mixed
:param default: The default value to return
:type default: mixed
:rtype: mixed | [
"Get",
"an",
"element",
"of",
"the",
"collection",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L324-L339 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.implode | def implode(self, value, glue=''):
"""
Concatenate values of a given key as a string.
:param value: The value
:type value: str
:param glue: The glue
:type glue: str
:rtype: str
"""
first = self.first()
if not isinstance(first, (basestri... | python | def implode(self, value, glue=''):
"""
Concatenate values of a given key as a string.
:param value: The value
:type value: str
:param glue: The glue
:type glue: str
:rtype: str
"""
first = self.first()
if not isinstance(first, (basestri... | [
"def",
"implode",
"(",
"self",
",",
"value",
",",
"glue",
"=",
"''",
")",
":",
"first",
"=",
"self",
".",
"first",
"(",
")",
"if",
"not",
"isinstance",
"(",
"first",
",",
"(",
"basestring",
")",
")",
":",
"return",
"glue",
".",
"join",
"(",
"self... | Concatenate values of a given key as a string.
:param value: The value
:type value: str
:param glue: The glue
:type glue: str
:rtype: str | [
"Concatenate",
"values",
"of",
"a",
"given",
"key",
"as",
"a",
"string",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L341-L358 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.last | def last(self, callback=None, default=None):
"""
Get the last item of the collection.
:param default: The default value
:type default: mixed
"""
if callback is not None:
for val in reversed(self.items):
if callback(val):
re... | python | def last(self, callback=None, default=None):
"""
Get the last item of the collection.
:param default: The default value
:type default: mixed
"""
if callback is not None:
for val in reversed(self.items):
if callback(val):
re... | [
"def",
"last",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"callback",
"is",
"not",
"None",
":",
"for",
"val",
"in",
"reversed",
"(",
"self",
".",
"items",
")",
":",
"if",
"callback",
"(",
"val",
")",
"... | Get the last item of the collection.
:param default: The default value
:type default: mixed | [
"Get",
"the",
"last",
"item",
"of",
"the",
"collection",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L360-L377 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.pluck | def pluck(self, value, key=None):
"""
Get a list with the values of a given key.
:rtype: Collection
"""
if key:
return dict(map(lambda x: (data_get(x, key), data_get(x, value)), self.items))
else:
results = list(map(lambda x: data_get(x, value), s... | python | def pluck(self, value, key=None):
"""
Get a list with the values of a given key.
:rtype: Collection
"""
if key:
return dict(map(lambda x: (data_get(x, key), data_get(x, value)), self.items))
else:
results = list(map(lambda x: data_get(x, value), s... | [
"def",
"pluck",
"(",
"self",
",",
"value",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
":",
"return",
"dict",
"(",
"map",
"(",
"lambda",
"x",
":",
"(",
"data_get",
"(",
"x",
",",
"key",
")",
",",
"data_get",
"(",
"x",
",",
"value",
")",
"... | Get a list with the values of a given key.
:rtype: Collection | [
"Get",
"a",
"list",
"with",
"the",
"values",
"of",
"a",
"given",
"key",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L379-L390 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.map | def map(self, callback):
"""
Run a map over each of the item.
:param callback: The map function
:type callback: callable
:rtype: Collection
"""
return self.__class__(list(map(callback, self.items))) | python | def map(self, callback):
"""
Run a map over each of the item.
:param callback: The map function
:type callback: callable
:rtype: Collection
"""
return self.__class__(list(map(callback, self.items))) | [
"def",
"map",
"(",
"self",
",",
"callback",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"list",
"(",
"map",
"(",
"callback",
",",
"self",
".",
"items",
")",
")",
")"
] | Run a map over each of the item.
:param callback: The map function
:type callback: callable
:rtype: Collection | [
"Run",
"a",
"map",
"over",
"each",
"of",
"the",
"item",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L400-L409 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.max | def max(self, key=None):
"""
Get the max value of a given key.
:param key: The key
:type key: str or None
:rtype: mixed
"""
def _max(result, item):
val = data_get(item, key)
if result is None or val > result:
return valu... | python | def max(self, key=None):
"""
Get the max value of a given key.
:param key: The key
:type key: str or None
:rtype: mixed
"""
def _max(result, item):
val = data_get(item, key)
if result is None or val > result:
return valu... | [
"def",
"max",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"def",
"_max",
"(",
"result",
",",
"item",
")",
":",
"val",
"=",
"data_get",
"(",
"item",
",",
"key",
")",
"if",
"result",
"is",
"None",
"or",
"val",
">",
"result",
":",
"return",
"v... | Get the max value of a given key.
:param key: The key
:type key: str or None
:rtype: mixed | [
"Get",
"the",
"max",
"value",
"of",
"a",
"given",
"key",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L411-L429 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.min | def min(self, key=None):
"""
Get the min value of a given key.
:param key: The key
:type key: str or None
:rtype: mixed
"""
def _min(result, item):
val = data_get(item, key)
if result is None or val < result:
return valu... | python | def min(self, key=None):
"""
Get the min value of a given key.
:param key: The key
:type key: str or None
:rtype: mixed
"""
def _min(result, item):
val = data_get(item, key)
if result is None or val < result:
return valu... | [
"def",
"min",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"def",
"_min",
"(",
"result",
",",
"item",
")",
":",
"val",
"=",
"data_get",
"(",
"item",
",",
"key",
")",
"if",
"result",
"is",
"None",
"or",
"val",
"<",
"result",
":",
"return",
"v... | Get the min value of a given key.
:param key: The key
:type key: str or None
:rtype: mixed | [
"Get",
"the",
"min",
"value",
"of",
"a",
"given",
"key",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L431-L449 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.for_page | def for_page(self, page, per_page):
"""
"Paginate" the collection by slicing it into a smaller collection.
:param page: The current page
:type page: int
:param per_page: Number of items by slice
:type per_page: int
:rtype: Collection
"""
start =... | python | def for_page(self, page, per_page):
"""
"Paginate" the collection by slicing it into a smaller collection.
:param page: The current page
:type page: int
:param per_page: Number of items by slice
:type per_page: int
:rtype: Collection
"""
start =... | [
"def",
"for_page",
"(",
"self",
",",
"page",
",",
"per_page",
")",
":",
"start",
"=",
"(",
"page",
"-",
"1",
")",
"*",
"per_page",
"return",
"self",
"[",
"start",
":",
"start",
"+",
"per_page",
"]"
] | "Paginate" the collection by slicing it into a smaller collection.
:param page: The current page
:type page: int
:param per_page: Number of items by slice
:type per_page: int
:rtype: Collection | [
"Paginate",
"the",
"collection",
"by",
"slicing",
"it",
"into",
"a",
"smaller",
"collection",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L451-L465 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.pull | def pull(self, key, default=None):
"""
Pulls an item from the collection.
:param key: The key
:type key: mixed
:param default: The default value
:type default: mixed
:rtype: mixed
"""
val = self.get(key, default)
self.forget(key)
... | python | def pull(self, key, default=None):
"""
Pulls an item from the collection.
:param key: The key
:type key: mixed
:param default: The default value
:type default: mixed
:rtype: mixed
"""
val = self.get(key, default)
self.forget(key)
... | [
"def",
"pull",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"val",
"=",
"self",
".",
"get",
"(",
"key",
",",
"default",
")",
"self",
".",
"forget",
"(",
"key",
")",
"return",
"val"
] | Pulls an item from the collection.
:param key: The key
:type key: mixed
:param default: The default value
:type default: mixed
:rtype: mixed | [
"Pulls",
"an",
"item",
"from",
"the",
"collection",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L519-L535 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.reject | def reject(self, callback):
"""
Create a collection of all elements that do not pass a given truth test.
:param callback: The truth test
:type callback: callable
:rtype: Collection
"""
if self._use_as_callable(callback):
return self.filter(lambda ite... | python | def reject(self, callback):
"""
Create a collection of all elements that do not pass a given truth test.
:param callback: The truth test
:type callback: callable
:rtype: Collection
"""
if self._use_as_callable(callback):
return self.filter(lambda ite... | [
"def",
"reject",
"(",
"self",
",",
"callback",
")",
":",
"if",
"self",
".",
"_use_as_callable",
"(",
"callback",
")",
":",
"return",
"self",
".",
"filter",
"(",
"lambda",
"item",
":",
"not",
"callback",
"(",
"item",
")",
")",
"return",
"self",
".",
"... | Create a collection of all elements that do not pass a given truth test.
:param callback: The truth test
:type callback: callable
:rtype: Collection | [
"Create",
"a",
"collection",
"of",
"all",
"elements",
"that",
"do",
"not",
"pass",
"a",
"given",
"truth",
"test",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L567-L579 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.sort | def sort(self, callback=None):
"""
Sort through each item with a callback.
:param callback: The callback
:type callback: callable or None
:rtype: Collection
"""
items = self.items
if callback:
return self.__class__(sorted(items, key=callback... | python | def sort(self, callback=None):
"""
Sort through each item with a callback.
:param callback: The callback
:type callback: callable or None
:rtype: Collection
"""
items = self.items
if callback:
return self.__class__(sorted(items, key=callback... | [
"def",
"sort",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"items",
"=",
"self",
".",
"items",
"if",
"callback",
":",
"return",
"self",
".",
"__class__",
"(",
"sorted",
"(",
"items",
",",
"key",
"=",
"callback",
")",
")",
"else",
":",
"ret... | Sort through each item with a callback.
:param callback: The callback
:type callback: callable or None
:rtype: Collection | [
"Sort",
"through",
"each",
"item",
"with",
"a",
"callback",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L597-L611 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.sum | def sum(self, callback=None):
"""
Get the sum of the given values.
:param callback: The callback
:type callback: callable or string or None
:rtype: mixed
"""
if callback is None:
return sum(self.items)
callback = self._value_retriever(callba... | python | def sum(self, callback=None):
"""
Get the sum of the given values.
:param callback: The callback
:type callback: callable or string or None
:rtype: mixed
"""
if callback is None:
return sum(self.items)
callback = self._value_retriever(callba... | [
"def",
"sum",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"if",
"callback",
"is",
"None",
":",
"return",
"sum",
"(",
"self",
".",
"items",
")",
"callback",
"=",
"self",
".",
"_value_retriever",
"(",
"callback",
")",
"return",
"self",
".",
"r... | Get the sum of the given values.
:param callback: The callback
:type callback: callable or string or None
:rtype: mixed | [
"Get",
"the",
"sum",
"of",
"the",
"given",
"values",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L613-L627 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.unique | def unique(self, key=None):
"""
Return only unique items from the collection list.
:param key: The key to chech uniqueness on
:type key: mixed
:rtype: Collection
"""
if key is None:
seen = set()
seen_add = seen.add
return sel... | python | def unique(self, key=None):
"""
Return only unique items from the collection list.
:param key: The key to chech uniqueness on
:type key: mixed
:rtype: Collection
"""
if key is None:
seen = set()
seen_add = seen.add
return sel... | [
"def",
"unique",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"self",
".",
"__class__",
"(",
"[",
"x",
"for",
"x",
"in",
"self",
"."... | Return only unique items from the collection list.
:param key: The key to chech uniqueness on
:type key: mixed
:rtype: Collection | [
"Return",
"only",
"unique",
"items",
"from",
"the",
"collection",
"list",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L643-L669 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.zip | def zip(self, *items):
"""
Zip the collection together with one or more arrays.
:param items: The items to zip
:type items: list
:rtype: Collection
"""
return self.__class__(list(zip(self.items, *items))) | python | def zip(self, *items):
"""
Zip the collection together with one or more arrays.
:param items: The items to zip
:type items: list
:rtype: Collection
"""
return self.__class__(list(zip(self.items, *items))) | [
"def",
"zip",
"(",
"self",
",",
"*",
"items",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"list",
"(",
"zip",
"(",
"self",
".",
"items",
",",
"*",
"items",
")",
")",
")"
] | Zip the collection together with one or more arrays.
:param items: The items to zip
:type items: list
:rtype: Collection | [
"Zip",
"the",
"collection",
"together",
"with",
"one",
"or",
"more",
"arrays",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L687-L696 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.merge | def merge(self, items):
"""
Merge the collection with the given items.
:param items: The items to merge
:type items: list or Collection
:rtype: Collection
"""
if isinstance(items, BaseCollection):
items = items.all()
if not isinstance(items,... | python | def merge(self, items):
"""
Merge the collection with the given items.
:param items: The items to merge
:type items: list or Collection
:rtype: Collection
"""
if isinstance(items, BaseCollection):
items = items.all()
if not isinstance(items,... | [
"def",
"merge",
"(",
"self",
",",
"items",
")",
":",
"if",
"isinstance",
"(",
"items",
",",
"BaseCollection",
")",
":",
"items",
"=",
"items",
".",
"all",
"(",
")",
"if",
"not",
"isinstance",
"(",
"items",
",",
"list",
")",
":",
"raise",
"ValueError"... | Merge the collection with the given items.
:param items: The items to merge
:type items: list or Collection
:rtype: Collection | [
"Merge",
"the",
"collection",
"with",
"the",
"given",
"items",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L701-L718 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.transform | def transform(self, callback):
"""
Transform each item in the collection using a callback.
:param callback: The callback
:type callback: callable
:rtype: Collection
"""
self._items = self.map(callback).all()
return self | python | def transform(self, callback):
"""
Transform each item in the collection using a callback.
:param callback: The callback
:type callback: callable
:rtype: Collection
"""
self._items = self.map(callback).all()
return self | [
"def",
"transform",
"(",
"self",
",",
"callback",
")",
":",
"self",
".",
"_items",
"=",
"self",
".",
"map",
"(",
"callback",
")",
".",
"all",
"(",
")",
"return",
"self"
] | Transform each item in the collection using a callback.
:param callback: The callback
:type callback: callable
:rtype: Collection | [
"Transform",
"each",
"item",
"in",
"the",
"collection",
"using",
"a",
"callback",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L720-L731 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection._value_retriever | def _value_retriever(self, value):
"""
Get a value retrieving callback.
:type value: mixed
:rtype: callable
"""
if self._use_as_callable(value):
return value
return lambda item: data_get(item, value) | python | def _value_retriever(self, value):
"""
Get a value retrieving callback.
:type value: mixed
:rtype: callable
"""
if self._use_as_callable(value):
return value
return lambda item: data_get(item, value) | [
"def",
"_value_retriever",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_use_as_callable",
"(",
"value",
")",
":",
"return",
"value",
"return",
"lambda",
"item",
":",
"data_get",
"(",
"item",
",",
"value",
")"
] | Get a value retrieving callback.
:type value: mixed
:rtype: callable | [
"Get",
"a",
"value",
"retrieving",
"callback",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L733-L744 |
sdispater/backpack | backpack/collections/base_collection.py | BaseCollection.serialize | def serialize(self):
"""
Get the collection of items as a serialized object (ready to be json encoded).
:rtype: dict or list
"""
def _serialize(value):
if hasattr(value, 'serialize'):
return value.serialize()
elif hasattr(value, 'to_dict'... | python | def serialize(self):
"""
Get the collection of items as a serialized object (ready to be json encoded).
:rtype: dict or list
"""
def _serialize(value):
if hasattr(value, 'serialize'):
return value.serialize()
elif hasattr(value, 'to_dict'... | [
"def",
"serialize",
"(",
"self",
")",
":",
"def",
"_serialize",
"(",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'serialize'",
")",
":",
"return",
"value",
".",
"serialize",
"(",
")",
"elif",
"hasattr",
"(",
"value",
",",
"'to_dict'",
")",
... | Get the collection of items as a serialized object (ready to be json encoded).
:rtype: dict or list | [
"Get",
"the",
"collection",
"of",
"items",
"as",
"a",
"serialized",
"object",
"(",
"ready",
"to",
"be",
"json",
"encoded",
")",
"."
] | train | https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L756-L771 |
orsinium/deal | deal/core.py | _Base.validate | def validate(self, *args, **kwargs):
"""
Step 4 (6 for invariant). Process contract (validator)
"""
# Schemes validation interface
if is_scheme(self.validator):
params = getcallargs(self.function, *args, **kwargs)
params.update(kwargs)
validato... | python | def validate(self, *args, **kwargs):
"""
Step 4 (6 for invariant). Process contract (validator)
"""
# Schemes validation interface
if is_scheme(self.validator):
params = getcallargs(self.function, *args, **kwargs)
params.update(kwargs)
validato... | [
"def",
"validate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Schemes validation interface",
"if",
"is_scheme",
"(",
"self",
".",
"validator",
")",
":",
"params",
"=",
"getcallargs",
"(",
"self",
".",
"function",
",",
"*",
"args... | Step 4 (6 for invariant). Process contract (validator) | [
"Step",
"4",
"(",
"6",
"for",
"invariant",
")",
".",
"Process",
"contract",
"(",
"validator",
")"
] | train | https://github.com/orsinium/deal/blob/e23c716216543d0080a956250fb45d9e170c3940/deal/core.py#L32-L66 |
orsinium/deal | deal/core.py | Pre.patched_function | def patched_function(self, *args, **kwargs):
"""
Step 3. Wrapped function calling.
"""
self.validate(*args, **kwargs)
return self.function(*args, **kwargs) | python | def patched_function(self, *args, **kwargs):
"""
Step 3. Wrapped function calling.
"""
self.validate(*args, **kwargs)
return self.function(*args, **kwargs) | [
"def",
"patched_function",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"validate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")... | Step 3. Wrapped function calling. | [
"Step",
"3",
".",
"Wrapped",
"function",
"calling",
"."
] | train | https://github.com/orsinium/deal/blob/e23c716216543d0080a956250fb45d9e170c3940/deal/core.py#L92-L97 |
orsinium/deal | deal/core.py | Post.patched_function | def patched_function(self, *args, **kwargs):
"""
Step 3. Wrapped function calling.
"""
result = self.function(*args, **kwargs)
self.validate(result)
return result | python | def patched_function(self, *args, **kwargs):
"""
Step 3. Wrapped function calling.
"""
result = self.function(*args, **kwargs)
self.validate(result)
return result | [
"def",
"patched_function",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"validate",
"(",
"result",
")",
"return",
"result"
] | Step 3. Wrapped function calling. | [
"Step",
"3",
".",
"Wrapped",
"function",
"calling",
"."
] | train | https://github.com/orsinium/deal/blob/e23c716216543d0080a956250fb45d9e170c3940/deal/core.py#L107-L113 |
orsinium/deal | deal/core.py | InvariantedClass._validate | def _validate(self):
"""
Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.
"""
# disable methods matching before validation
self._disable_patching = True
# validation by Invariant.validate
self._validate_base(self)
# enable methods match... | python | def _validate(self):
"""
Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.
"""
# disable methods matching before validation
self._disable_patching = True
# validation by Invariant.validate
self._validate_base(self)
# enable methods match... | [
"def",
"_validate",
"(",
"self",
")",
":",
"# disable methods matching before validation",
"self",
".",
"_disable_patching",
"=",
"True",
"# validation by Invariant.validate",
"self",
".",
"_validate_base",
"(",
"self",
")",
"# enable methods matching after validation",
"self... | Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object. | [
"Step",
"5",
"(",
"1st",
"flow",
")",
"or",
"Step",
"4",
"(",
"2nd",
"flow",
")",
".",
"Process",
"contract",
"for",
"object",
"."
] | train | https://github.com/orsinium/deal/blob/e23c716216543d0080a956250fb45d9e170c3940/deal/core.py#L119-L128 |
orsinium/deal | deal/core.py | InvariantedClass._patched_method | def _patched_method(self, method, *args, **kwargs):
"""
Step 4 (1st flow). Call method
"""
self._validate()
result = method(*args, **kwargs)
self._validate()
return result | python | def _patched_method(self, method, *args, **kwargs):
"""
Step 4 (1st flow). Call method
"""
self._validate()
result = method(*args, **kwargs)
self._validate()
return result | [
"def",
"_patched_method",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_validate",
"(",
")",
"result",
"=",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_validate",
"(",
... | Step 4 (1st flow). Call method | [
"Step",
"4",
"(",
"1st",
"flow",
")",
".",
"Call",
"method"
] | train | https://github.com/orsinium/deal/blob/e23c716216543d0080a956250fb45d9e170c3940/deal/core.py#L130-L137 |
benmack/eo-box | eobox/raster/gdalutils.py | buildvrt | def buildvrt(input_file_list, output_file,
relative=True, **kwargs):
"""Build a VRT
See also: https://www.gdal.org/gdalbuildvrt.html
You can find the possible BuildVRTOptions (**kwargs**) here:
https://github.com/nextgis/pygdal/blob/78a793057d2162c292af4f6b240e19da5d5e52e2/2.1.0/osgeo/gda... | python | def buildvrt(input_file_list, output_file,
relative=True, **kwargs):
"""Build a VRT
See also: https://www.gdal.org/gdalbuildvrt.html
You can find the possible BuildVRTOptions (**kwargs**) here:
https://github.com/nextgis/pygdal/blob/78a793057d2162c292af4f6b240e19da5d5e52e2/2.1.0/osgeo/gda... | [
"def",
"buildvrt",
"(",
"input_file_list",
",",
"output_file",
",",
"relative",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# create destination directory",
"if",
"not",
"Path",
"(",
"output_file",
")",
".",
"parent",
".",
"exists",
"(",
")",
":",
"Pa... | Build a VRT
See also: https://www.gdal.org/gdalbuildvrt.html
You can find the possible BuildVRTOptions (**kwargs**) here:
https://github.com/nextgis/pygdal/blob/78a793057d2162c292af4f6b240e19da5d5e52e2/2.1.0/osgeo/gdal.py#L1051
Arguments:
input_file_list {list of str or Path objects} -- List ... | [
"Build",
"a",
"VRT"
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/gdalutils.py#L21-L92 |
benmack/eo-box | eobox/raster/gdalutils.py | reproject_on_template_raster | def reproject_on_template_raster(src_file, dst_file, template_file, resampling="near", compress=None, overwrite=False):
"""Reproject a one-band raster to fit the projection, extend, pixel size etc. of a template raster.
Function based on https://stackoverflow.com/questions/10454316/how-to-project-and-res... | python | def reproject_on_template_raster(src_file, dst_file, template_file, resampling="near", compress=None, overwrite=False):
"""Reproject a one-band raster to fit the projection, extend, pixel size etc. of a template raster.
Function based on https://stackoverflow.com/questions/10454316/how-to-project-and-res... | [
"def",
"reproject_on_template_raster",
"(",
"src_file",
",",
"dst_file",
",",
"template_file",
",",
"resampling",
"=",
"\"near\"",
",",
"compress",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"overwrite",
"and",
"Path",
"(",
"dst_file",... | Reproject a one-band raster to fit the projection, extend, pixel size etc. of a template raster.
Function based on https://stackoverflow.com/questions/10454316/how-to-project-and-resample-a-grid-to-match-another-grid-with-gdal-python
Arguments:
src_file {str} -- Filename of the source one-band r... | [
"Reproject",
"a",
"one",
"-",
"band",
"raster",
"to",
"fit",
"the",
"projection",
"extend",
"pixel",
"size",
"etc",
".",
"of",
"a",
"template",
"raster",
".",
"Function",
"based",
"on",
"https",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"... | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/gdalutils.py#L94-L165 |
benmack/eo-box | eobox/raster/gdalutils.py | rasterize | def rasterize(src_vector: str,
burn_attribute: str,
src_raster_template: str,
dst_rasterized: str,
gdal_dtype: int = 4):
"""Rasterize the values of a spatial vector file.
Arguments:
src_vector {str}} -- A OGR vector file (e.g. GeoPackage, ESRI Sha... | python | def rasterize(src_vector: str,
burn_attribute: str,
src_raster_template: str,
dst_rasterized: str,
gdal_dtype: int = 4):
"""Rasterize the values of a spatial vector file.
Arguments:
src_vector {str}} -- A OGR vector file (e.g. GeoPackage, ESRI Sha... | [
"def",
"rasterize",
"(",
"src_vector",
":",
"str",
",",
"burn_attribute",
":",
"str",
",",
"src_raster_template",
":",
"str",
",",
"dst_rasterized",
":",
"str",
",",
"gdal_dtype",
":",
"int",
"=",
"4",
")",
":",
"data",
"=",
"gdal",
".",
"Open",
"(",
"... | Rasterize the values of a spatial vector file.
Arguments:
src_vector {str}} -- A OGR vector file (e.g. GeoPackage, ESRI Shapefile) path containing the
data to be rasterized.
burn_attribute {str} -- The attribute of the vector data to be burned in the raster.
src_raster_template ... | [
"Rasterize",
"the",
"values",
"of",
"a",
"spatial",
"vector",
"file",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/gdalutils.py#L167-L218 |
benmack/eo-box | eobox/vector/conversion.py | calc_distance_to_border | def calc_distance_to_border(polygons, template_raster, dst_raster, overwrite=False,
keep_interim_files=False):
"""Calculate the distance of each raster cell (in and outside the polygons) to the next polygon border.
Arguments:
polygons {str} -- Filename to a geopandas-rea... | python | def calc_distance_to_border(polygons, template_raster, dst_raster, overwrite=False,
keep_interim_files=False):
"""Calculate the distance of each raster cell (in and outside the polygons) to the next polygon border.
Arguments:
polygons {str} -- Filename to a geopandas-rea... | [
"def",
"calc_distance_to_border",
"(",
"polygons",
",",
"template_raster",
",",
"dst_raster",
",",
"overwrite",
"=",
"False",
",",
"keep_interim_files",
"=",
"False",
")",
":",
"if",
"Path",
"(",
"dst_raster",
")",
".",
"exists",
"(",
")",
"and",
"not",
"ove... | Calculate the distance of each raster cell (in and outside the polygons) to the next polygon border.
Arguments:
polygons {str} -- Filename to a geopandas-readable file with polygon features.
template_raster {[type]} -- Filename to a rasterio-readable file.
dst_raster {[type]} -- Destin... | [
"Calculate",
"the",
"distance",
"of",
"each",
"raster",
"cell",
"(",
"in",
"and",
"outside",
"the",
"polygons",
")",
"to",
"the",
"next",
"polygon",
"border",
".",
"Arguments",
":",
"polygons",
"{",
"str",
"}",
"--",
"Filename",
"to",
"a",
"geopandas",
"... | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/vector/conversion.py#L14-L65 |
benmack/eo-box | eobox/vector/conversion.py | convert_polygons_to_lines | def convert_polygons_to_lines(src_polygons, dst_lines, crs=None, add_allone_col=False):
"""Convert polygons to lines.
Arguments:
src_polygons {path to geopandas-readable file} -- Filename of the the polygon vector dataset to be
converted to lines.
dst_lines {[type]} -- Filename whe... | python | def convert_polygons_to_lines(src_polygons, dst_lines, crs=None, add_allone_col=False):
"""Convert polygons to lines.
Arguments:
src_polygons {path to geopandas-readable file} -- Filename of the the polygon vector dataset to be
converted to lines.
dst_lines {[type]} -- Filename whe... | [
"def",
"convert_polygons_to_lines",
"(",
"src_polygons",
",",
"dst_lines",
",",
"crs",
"=",
"None",
",",
"add_allone_col",
"=",
"False",
")",
":",
"gdf",
"=",
"gpd",
".",
"read_file",
"(",
"src_polygons",
")",
"geom_coords",
"=",
"gdf",
"[",
"\"geometry\"",
... | Convert polygons to lines.
Arguments:
src_polygons {path to geopandas-readable file} -- Filename of the the polygon vector dataset to be
converted to lines.
dst_lines {[type]} -- Filename where to write the line vector dataset to.
Keyword Arguments:
crs {dict or str} -- Ou... | [
"Convert",
"polygons",
"to",
"lines",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/vector/conversion.py#L67-L107 |
benmack/eo-box | eobox/raster/utils.py | dtype_checker_df | def dtype_checker_df(df, dtype, return_=None):
"""Check if there are NaN values of values outside of a given datatype range.
Arguments:
df {dataframe} -- A dataframe.
dtype {str} -- The datatype to check for.
Keyword Arguments:
return_ {str} -- Returns a boolean dataframe with the v... | python | def dtype_checker_df(df, dtype, return_=None):
"""Check if there are NaN values of values outside of a given datatype range.
Arguments:
df {dataframe} -- A dataframe.
dtype {str} -- The datatype to check for.
Keyword Arguments:
return_ {str} -- Returns a boolean dataframe with the v... | [
"def",
"dtype_checker_df",
"(",
"df",
",",
"dtype",
",",
"return_",
"=",
"None",
")",
":",
"dtype_range",
"=",
"dtype_ranges",
"[",
"dtype",
"]",
"df_out_of_range",
"=",
"(",
"df",
"<",
"dtype_range",
"[",
"0",
"]",
")",
"|",
"(",
"df",
">",
"dtype_ran... | Check if there are NaN values of values outside of a given datatype range.
Arguments:
df {dataframe} -- A dataframe.
dtype {str} -- The datatype to check for.
Keyword Arguments:
return_ {str} -- Returns a boolean dataframe with the values not in the range of the dtype ('all'),
... | [
"Check",
"if",
"there",
"are",
"NaN",
"values",
"of",
"values",
"outside",
"of",
"a",
"given",
"datatype",
"range",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/utils.py#L13-L40 |
benmack/eo-box | eobox/raster/cube.py | EOCubeAbstract.get_df_ilocs | def get_df_ilocs(self, band, date):
"""Get positions of rows matching specific band(s) and date(s).
The method supports three typical queries:
* one band and one date (both given as strings)
* one band and of several dates (band given as strings, date as list of strings)
* se... | python | def get_df_ilocs(self, band, date):
"""Get positions of rows matching specific band(s) and date(s).
The method supports three typical queries:
* one band and one date (both given as strings)
* one band and of several dates (band given as strings, date as list of strings)
* se... | [
"def",
"get_df_ilocs",
"(",
"self",
",",
"band",
",",
"date",
")",
":",
"df",
"=",
"self",
".",
"df_layers",
".",
"copy",
"(",
")",
"df",
"[",
"\"index\"",
"]",
"=",
"range",
"(",
"df",
".",
"shape",
"[",
"0",
"]",
")",
"idx_layers",
"=",
"[",
... | Get positions of rows matching specific band(s) and date(s).
The method supports three typical queries:
* one band and one date (both given as strings)
* one band and of several dates (band given as strings, date as list of strings)
* several band and of one date (date given as strin... | [
"Get",
"positions",
"of",
"rows",
"matching",
"specific",
"band",
"(",
"s",
")",
"and",
"date",
"(",
"s",
")",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L68-L101 |
benmack/eo-box | eobox/raster/cube.py | EOCubeChunk._get_spatial_bounds | def _get_spatial_bounds(self):
"""Get the spatial bounds of the chunk."""
# This should be a MultiRasterIO method
with rasterio.open(self._mrio._get_template_for_given_resolution(self._mrio.dst_res, "path")) as src_layer:
pass # later we need src_layer for src_layer.window_transform... | python | def _get_spatial_bounds(self):
"""Get the spatial bounds of the chunk."""
# This should be a MultiRasterIO method
with rasterio.open(self._mrio._get_template_for_given_resolution(self._mrio.dst_res, "path")) as src_layer:
pass # later we need src_layer for src_layer.window_transform... | [
"def",
"_get_spatial_bounds",
"(",
"self",
")",
":",
"# This should be a MultiRasterIO method",
"with",
"rasterio",
".",
"open",
"(",
"self",
".",
"_mrio",
".",
"_get_template_for_given_resolution",
"(",
"self",
".",
"_mrio",
".",
"dst_res",
",",
"\"path\"",
")",
... | Get the spatial bounds of the chunk. | [
"Get",
"the",
"spatial",
"bounds",
"of",
"the",
"chunk",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L173-L182 |
benmack/eo-box | eobox/raster/cube.py | EOCubeChunk.convert_data_to_ndarray | def convert_data_to_ndarray(self):
"""Converts the data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.)"""
if self._data_structure != "DataFrame":
raise Exception(f"Data is not a DataFrame but {self._data_structure}.")
self._data = self._convert... | python | def convert_data_to_ndarray(self):
"""Converts the data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.)"""
if self._data_structure != "DataFrame":
raise Exception(f"Data is not a DataFrame but {self._data_structure}.")
self._data = self._convert... | [
"def",
"convert_data_to_ndarray",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_structure",
"!=",
"\"DataFrame\"",
":",
"raise",
"Exception",
"(",
"f\"Data is not a DataFrame but {self._data_structure}.\"",
")",
"self",
".",
"_data",
"=",
"self",
".",
"_convert_to_... | Converts the data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.) | [
"Converts",
"the",
"data",
"from",
"dataframe",
"to",
"ndarray",
"format",
".",
"Assumption",
":",
"df",
"-",
"columns",
"are",
"ndarray",
"-",
"layers",
"(",
"3rd",
"dim",
".",
")"
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L207-L213 |
benmack/eo-box | eobox/raster/cube.py | EOCubeChunk._convert_to_ndarray | def _convert_to_ndarray(self, data):
"""Converts data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.)"""
if data.__class__.__name__ != "DataFrame":
raise Exception(f"data is not a DataFrame but {data.__class__.__name__}.")
shape_ndarray = (self.... | python | def _convert_to_ndarray(self, data):
"""Converts data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.)"""
if data.__class__.__name__ != "DataFrame":
raise Exception(f"data is not a DataFrame but {data.__class__.__name__}.")
shape_ndarray = (self.... | [
"def",
"_convert_to_ndarray",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"__class__",
".",
"__name__",
"!=",
"\"DataFrame\"",
":",
"raise",
"Exception",
"(",
"f\"data is not a DataFrame but {data.__class__.__name__}.\"",
")",
"shape_ndarray",
"=",
"(",
"... | Converts data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.) | [
"Converts",
"data",
"from",
"dataframe",
"to",
"ndarray",
"format",
".",
"Assumption",
":",
"df",
"-",
"columns",
"are",
"ndarray",
"-",
"layers",
"(",
"3rd",
"dim",
".",
")"
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L215-L221 |
benmack/eo-box | eobox/raster/cube.py | EOCubeChunk.write_dataframe | def write_dataframe(self, result, dst_paths, nodata=None, compress='lzw'):
"""Write results (dataframe) to disc."""
result = self._convert_to_ndarray(result)
self.write_ndarray(result, dst_paths, nodata=nodata, compress=compress) | python | def write_dataframe(self, result, dst_paths, nodata=None, compress='lzw'):
"""Write results (dataframe) to disc."""
result = self._convert_to_ndarray(result)
self.write_ndarray(result, dst_paths, nodata=nodata, compress=compress) | [
"def",
"write_dataframe",
"(",
"self",
",",
"result",
",",
"dst_paths",
",",
"nodata",
"=",
"None",
",",
"compress",
"=",
"'lzw'",
")",
":",
"result",
"=",
"self",
".",
"_convert_to_ndarray",
"(",
"result",
")",
"self",
".",
"write_ndarray",
"(",
"result",... | Write results (dataframe) to disc. | [
"Write",
"results",
"(",
"dataframe",
")",
"to",
"disc",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L223-L226 |
benmack/eo-box | eobox/raster/cube.py | EOCubeChunk.write_ndarray | def write_ndarray(self, result, dst_paths, nodata=None, compress='lzw'):
"""Write results (ndarray) to disc."""
assert len(dst_paths) == result.shape[2]
assert result.shape[0] == self._height
assert result.shape[1] == self._width
assert result.shape[2] == len(dst_paths)
... | python | def write_ndarray(self, result, dst_paths, nodata=None, compress='lzw'):
"""Write results (ndarray) to disc."""
assert len(dst_paths) == result.shape[2]
assert result.shape[0] == self._height
assert result.shape[1] == self._width
assert result.shape[2] == len(dst_paths)
... | [
"def",
"write_ndarray",
"(",
"self",
",",
"result",
",",
"dst_paths",
",",
"nodata",
"=",
"None",
",",
"compress",
"=",
"'lzw'",
")",
":",
"assert",
"len",
"(",
"dst_paths",
")",
"==",
"result",
".",
"shape",
"[",
"2",
"]",
"assert",
"result",
".",
"... | Write results (ndarray) to disc. | [
"Write",
"results",
"(",
"ndarray",
")",
"to",
"disc",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L228-L252 |
benmack/eo-box | eobox/raster/cube.py | EOCubeChunk.robust_data_range | def robust_data_range(arr, robust=False, vmin=None, vmax=None):
"""Get a robust data range, i.e. 2nd and 98th percentile for vmin, vmax parameters."""
# from the seaborn code
# https://github.com/mwaskom/seaborn/blob/3a3ec75befab52c02650c62772a90f8c23046038/seaborn/matrix.py#L201
def _... | python | def robust_data_range(arr, robust=False, vmin=None, vmax=None):
"""Get a robust data range, i.e. 2nd and 98th percentile for vmin, vmax parameters."""
# from the seaborn code
# https://github.com/mwaskom/seaborn/blob/3a3ec75befab52c02650c62772a90f8c23046038/seaborn/matrix.py#L201
def _... | [
"def",
"robust_data_range",
"(",
"arr",
",",
"robust",
"=",
"False",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"# from the seaborn code ",
"# https://github.com/mwaskom/seaborn/blob/3a3ec75befab52c02650c62772a90f8c23046038/seaborn/matrix.py#L201",
"def",
... | Get a robust data range, i.e. 2nd and 98th percentile for vmin, vmax parameters. | [
"Get",
"a",
"robust",
"data",
"range",
"i",
".",
"e",
".",
"2nd",
"and",
"98th",
"percentile",
"for",
"vmin",
"vmax",
"parameters",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L255-L277 |
benmack/eo-box | eobox/raster/cube.py | EOCubeChunk.from_eocube | def from_eocube(eocube, ji):
"""Create a EOCubeChunk object from an EOCube object."""
eocubewin = EOCubeChunk(ji, eocube.df_layers, eocube.chunksize, eocube.wdir)
return eocubewin | python | def from_eocube(eocube, ji):
"""Create a EOCubeChunk object from an EOCube object."""
eocubewin = EOCubeChunk(ji, eocube.df_layers, eocube.chunksize, eocube.wdir)
return eocubewin | [
"def",
"from_eocube",
"(",
"eocube",
",",
"ji",
")",
":",
"eocubewin",
"=",
"EOCubeChunk",
"(",
"ji",
",",
"eocube",
".",
"df_layers",
",",
"eocube",
".",
"chunksize",
",",
"eocube",
".",
"wdir",
")",
"return",
"eocubewin"
] | Create a EOCubeChunk object from an EOCube object. | [
"Create",
"a",
"EOCubeChunk",
"object",
"from",
"an",
"EOCube",
"object",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L346-L349 |
benmack/eo-box | eobox/raster/cube.py | EOCubeSceneCollection.get_chunk | def get_chunk(self, ji):
"""Get a EOCubeChunk"""
return EOCubeSceneCollectionChunk(ji=ji,
df_layers=self.df_layers,
chunksize=self.chunksize,
variables=self.variables,
... | python | def get_chunk(self, ji):
"""Get a EOCubeChunk"""
return EOCubeSceneCollectionChunk(ji=ji,
df_layers=self.df_layers,
chunksize=self.chunksize,
variables=self.variables,
... | [
"def",
"get_chunk",
"(",
"self",
",",
"ji",
")",
":",
"return",
"EOCubeSceneCollectionChunk",
"(",
"ji",
"=",
"ji",
",",
"df_layers",
"=",
"self",
".",
"df_layers",
",",
"chunksize",
"=",
"self",
".",
"chunksize",
",",
"variables",
"=",
"self",
".",
"var... | Get a EOCubeChunk | [
"Get",
"a",
"EOCubeChunk"
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L396-L404 |
benmack/eo-box | eobox/raster/cube.py | EOCubeSceneCollectionChunk.read_data_by_variable | def read_data_by_variable(self, mask=True):
"""Reads and masks (if desired) the data and converts it in one dataframe per variable."""
def print_elapsed_time(start, last_stopped, prefix):
# print(f"{prefix} - Elapsed time [s] since start / last stopped: \
# {(int(time.time() ... | python | def read_data_by_variable(self, mask=True):
"""Reads and masks (if desired) the data and converts it in one dataframe per variable."""
def print_elapsed_time(start, last_stopped, prefix):
# print(f"{prefix} - Elapsed time [s] since start / last stopped: \
# {(int(time.time() ... | [
"def",
"read_data_by_variable",
"(",
"self",
",",
"mask",
"=",
"True",
")",
":",
"def",
"print_elapsed_time",
"(",
"start",
",",
"last_stopped",
",",
"prefix",
")",
":",
"# print(f\"{prefix} - Elapsed time [s] since start / last stopped: \\",
"# {(int(time.time() - star... | Reads and masks (if desired) the data and converts it in one dataframe per variable. | [
"Reads",
"and",
"masks",
"(",
"if",
"desired",
")",
"the",
"data",
"and",
"converts",
"it",
"in",
"one",
"dataframe",
"per",
"variable",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L517-L562 |
benmack/eo-box | eobox/sampledata/base.py | get_dataset | def get_dataset(dataset="s2l1c"):
"""Get a specific sampledata to play around.
So far the following sampledata exist:
* 's2l1c': One Sentinel-2 Level 1C scene with a reference dataset.
* 'lsts': A time series of 105 Landsat scenes each with the bands b3 (red), b4 (nir), b5 (swir1) and fmask.
Keyw... | python | def get_dataset(dataset="s2l1c"):
"""Get a specific sampledata to play around.
So far the following sampledata exist:
* 's2l1c': One Sentinel-2 Level 1C scene with a reference dataset.
* 'lsts': A time series of 105 Landsat scenes each with the bands b3 (red), b4 (nir), b5 (swir1) and fmask.
Keyw... | [
"def",
"get_dataset",
"(",
"dataset",
"=",
"\"s2l1c\"",
")",
":",
"if",
"dataset",
"==",
"\"s2l1c\"",
":",
"search_string",
"=",
"os",
".",
"path",
".",
"join",
"(",
"DIR_DATA",
",",
"dataset",
",",
"\"**\"",
",",
"\"*_B??.jp2\"",
")",
"files",
"=",
"glo... | Get a specific sampledata to play around.
So far the following sampledata exist:
* 's2l1c': One Sentinel-2 Level 1C scene with a reference dataset.
* 'lsts': A time series of 105 Landsat scenes each with the bands b3 (red), b4 (nir), b5 (swir1) and fmask.
Keyword Arguments:
dataset {str} -- T... | [
"Get",
"a",
"specific",
"sampledata",
"to",
"play",
"around",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/sampledata/base.py#L12-L56 |
benmack/eo-box | eobox/raster/rasterprocessing.py | windows_from_blocksize | def windows_from_blocksize(blocksize_xy, width, height):
"""Create rasterio.windows.Window instances with given size which fully cover a raster.
Arguments:
blocksize_xy {int or list of two int} -- [description]
width {int} -- With of the raster for which to create the windows.
height {i... | python | def windows_from_blocksize(blocksize_xy, width, height):
"""Create rasterio.windows.Window instances with given size which fully cover a raster.
Arguments:
blocksize_xy {int or list of two int} -- [description]
width {int} -- With of the raster for which to create the windows.
height {i... | [
"def",
"windows_from_blocksize",
"(",
"blocksize_xy",
",",
"width",
",",
"height",
")",
":",
"# checks the blocksize input",
"value_error_msg",
"=",
"\"'blocksize must be an integer or a list of two integers.'\"",
"if",
"isinstance",
"(",
"blocksize_xy",
",",
"int",
")",
":... | Create rasterio.windows.Window instances with given size which fully cover a raster.
Arguments:
blocksize_xy {int or list of two int} -- [description]
width {int} -- With of the raster for which to create the windows.
height {int} -- Heigth of the raster for which to create the windows.
... | [
"Create",
"rasterio",
".",
"windows",
".",
"Window",
"instances",
"with",
"given",
"size",
"which",
"fully",
"cover",
"a",
"raster",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L285-L333 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO._get_dst_resolution | def _get_dst_resolution(self, dst_res=None):
"""Get default resolution, i.e. the highest resolution or smallest cell size."""
if dst_res is None:
dst_res = min(self._res_indices.keys())
return dst_res | python | def _get_dst_resolution(self, dst_res=None):
"""Get default resolution, i.e. the highest resolution or smallest cell size."""
if dst_res is None:
dst_res = min(self._res_indices.keys())
return dst_res | [
"def",
"_get_dst_resolution",
"(",
"self",
",",
"dst_res",
"=",
"None",
")",
":",
"if",
"dst_res",
"is",
"None",
":",
"dst_res",
"=",
"min",
"(",
"self",
".",
"_res_indices",
".",
"keys",
"(",
")",
")",
"return",
"dst_res"
] | Get default resolution, i.e. the highest resolution or smallest cell size. | [
"Get",
"default",
"resolution",
"i",
".",
"e",
".",
"the",
"highest",
"resolution",
"or",
"smallest",
"cell",
"size",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L56-L60 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO.block_windows | def block_windows(self, res=None): # setter and getter ?
"""Load windows for chunks-wise processing from raster internal tiling (first raster of given resolution).
Arguments:
res {numeric} -- Resolution determining the raster (1st of resolution group) from which to take the tiling.
... | python | def block_windows(self, res=None): # setter and getter ?
"""Load windows for chunks-wise processing from raster internal tiling (first raster of given resolution).
Arguments:
res {numeric} -- Resolution determining the raster (1st of resolution group) from which to take the tiling.
... | [
"def",
"block_windows",
"(",
"self",
",",
"res",
"=",
"None",
")",
":",
"# setter and getter ?",
"if",
"res",
"is",
"None",
":",
"res",
"=",
"max",
"(",
"self",
".",
"_res_indices",
".",
"keys",
"(",
")",
")",
"self",
".",
"_windows_res",
"=",
"res",
... | Load windows for chunks-wise processing from raster internal tiling (first raster of given resolution).
Arguments:
res {numeric} -- Resolution determining the raster (1st of resolution group) from which to take the tiling. | [
"Load",
"windows",
"for",
"chunks",
"-",
"wise",
"processing",
"from",
"raster",
"internal",
"tiling",
"(",
"first",
"raster",
"of",
"given",
"resolution",
")",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L62-L77 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO.windows_from_blocksize | def windows_from_blocksize(self, blocksize_xy=512):
"""Create rasterio.windows.Window instances with given size which fully cover the raster.
Arguments:
blocksize_xy {int or list of two int} -- Size of the window. If one integer is given it defines
the width and height of th... | python | def windows_from_blocksize(self, blocksize_xy=512):
"""Create rasterio.windows.Window instances with given size which fully cover the raster.
Arguments:
blocksize_xy {int or list of two int} -- Size of the window. If one integer is given it defines
the width and height of th... | [
"def",
"windows_from_blocksize",
"(",
"self",
",",
"blocksize_xy",
"=",
"512",
")",
":",
"meta",
"=",
"self",
".",
"_get_template_for_given_resolution",
"(",
"self",
".",
"dst_res",
",",
"\"meta\"",
")",
"width",
"=",
"meta",
"[",
"\"width\"",
"]",
"height",
... | Create rasterio.windows.Window instances with given size which fully cover the raster.
Arguments:
blocksize_xy {int or list of two int} -- Size of the window. If one integer is given it defines
the width and height of the window. If a list of two integers if given the first defines ... | [
"Create",
"rasterio",
".",
"windows",
".",
"Window",
"instances",
"with",
"given",
"size",
"which",
"fully",
"cover",
"the",
"raster",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L79-L98 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO._get_template_for_given_resolution | def _get_template_for_given_resolution(self, res, return_):
"""Given specified resolution ('res') return template layer 'path', 'meta' or 'windows'."""
path = self._layer_files[self._res_indices[res][0]]
if return_ == "path":
return_value = path
else:
with rasteri... | python | def _get_template_for_given_resolution(self, res, return_):
"""Given specified resolution ('res') return template layer 'path', 'meta' or 'windows'."""
path = self._layer_files[self._res_indices[res][0]]
if return_ == "path":
return_value = path
else:
with rasteri... | [
"def",
"_get_template_for_given_resolution",
"(",
"self",
",",
"res",
",",
"return_",
")",
":",
"path",
"=",
"self",
".",
"_layer_files",
"[",
"self",
".",
"_res_indices",
"[",
"res",
"]",
"[",
"0",
"]",
"]",
"if",
"return_",
"==",
"\"path\"",
":",
"retu... | Given specified resolution ('res') return template layer 'path', 'meta' or 'windows'. | [
"Given",
"specified",
"resolution",
"(",
"res",
")",
"return",
"template",
"layer",
"path",
"meta",
"or",
"windows",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L100-L113 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO.windows_df | def windows_df(self):
"""Get Windows (W) W-row, W-col and W-index of windows e.g. loaded with :meth:`block_windows` as a dataframe.
Returns:
[dataframe] -- A dataframe with the window information and indices (row, col, index).
"""
import pandas as pd
if self.windows... | python | def windows_df(self):
"""Get Windows (W) W-row, W-col and W-index of windows e.g. loaded with :meth:`block_windows` as a dataframe.
Returns:
[dataframe] -- A dataframe with the window information and indices (row, col, index).
"""
import pandas as pd
if self.windows... | [
"def",
"windows_df",
"(",
"self",
")",
":",
"import",
"pandas",
"as",
"pd",
"if",
"self",
".",
"windows",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"You need to call the block_windows or windows before.\"",
")",
"df_wins",
"=",
"[",
"]",
"for",
"row",
",... | Get Windows (W) W-row, W-col and W-index of windows e.g. loaded with :meth:`block_windows` as a dataframe.
Returns:
[dataframe] -- A dataframe with the window information and indices (row, col, index). | [
"Get",
"Windows",
"(",
"W",
")",
"W",
"-",
"row",
"W",
"-",
"col",
"and",
"W",
"-",
"index",
"of",
"windows",
"e",
".",
"g",
".",
"loaded",
"with",
":",
"meth",
":",
"block_windows",
"as",
"a",
"dataframe",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L115-L131 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO.ji_windows | def ji_windows(self, ij_win): # what can be given to ij_win NOT intuitive/right name by now!!!
"""For a given specific window, i.e. an element of :attr:`windows`, get the windows of all resolutions.
Arguments:
ij_win {int} -- The index specifying the window for which to return the resoluti... | python | def ji_windows(self, ij_win): # what can be given to ij_win NOT intuitive/right name by now!!!
"""For a given specific window, i.e. an element of :attr:`windows`, get the windows of all resolutions.
Arguments:
ij_win {int} -- The index specifying the window for which to return the resoluti... | [
"def",
"ji_windows",
"(",
"self",
",",
"ij_win",
")",
":",
"# what can be given to ij_win NOT intuitive/right name by now!!!",
"ji_windows",
"=",
"{",
"}",
"transform_src",
"=",
"self",
".",
"_layer_meta",
"[",
"self",
".",
"_res_indices",
"[",
"self",
".",
"_window... | For a given specific window, i.e. an element of :attr:`windows`, get the windows of all resolutions.
Arguments:
ij_win {int} -- The index specifying the window for which to return the resolution-windows. | [
"For",
"a",
"given",
"specific",
"window",
"i",
".",
"e",
".",
"an",
"element",
"of",
":",
"attr",
":",
"windows",
"get",
"the",
"windows",
"of",
"all",
"resolutions",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L133-L146 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO.get_arrays | def get_arrays(self, ji_win):
"""Get the data of the a window given the ji_windows derived with :method:`ji_windows`.
Arguments:
ji_win {[type]} -- The index of the window or the (multi-resolution) windows returned by :meth:`ji_window`.
Returns:
(list of) array(s) -- Li... | python | def get_arrays(self, ji_win):
"""Get the data of the a window given the ji_windows derived with :method:`ji_windows`.
Arguments:
ji_win {[type]} -- The index of the window or the (multi-resolution) windows returned by :meth:`ji_window`.
Returns:
(list of) array(s) -- Li... | [
"def",
"get_arrays",
"(",
"self",
",",
"ji_win",
")",
":",
"if",
"isinstance",
"(",
"ji_win",
",",
"dict",
")",
":",
"ji_windows",
"=",
"ji_win",
"else",
":",
"ji_windows",
"=",
"self",
".",
"ji_windows",
"(",
"ji_win",
")",
"arrays",
"=",
"[",
"]",
... | Get the data of the a window given the ji_windows derived with :method:`ji_windows`.
Arguments:
ji_win {[type]} -- The index of the window or the (multi-resolution) windows returned by :meth:`ji_window`.
Returns:
(list of) array(s) -- List of 2D arrays in native resolution in c... | [
"Get",
"the",
"data",
"of",
"the",
"a",
"window",
"given",
"the",
"ji_windows",
"derived",
"with",
":",
"method",
":",
"ji_windows",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L148-L170 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO._resample | def _resample(self, arrays, ji_windows):
"""Resample all arrays with potentially different resolutions to a common resolution."""
# get a destination array template
win_dst = ji_windows[self.dst_res]
aff_dst = self._layer_meta[self._res_indices[self.dst_res][0]]["transform"]
arra... | python | def _resample(self, arrays, ji_windows):
"""Resample all arrays with potentially different resolutions to a common resolution."""
# get a destination array template
win_dst = ji_windows[self.dst_res]
aff_dst = self._layer_meta[self._res_indices[self.dst_res][0]]["transform"]
arra... | [
"def",
"_resample",
"(",
"self",
",",
"arrays",
",",
"ji_windows",
")",
":",
"# get a destination array template",
"win_dst",
"=",
"ji_windows",
"[",
"self",
".",
"dst_res",
"]",
"aff_dst",
"=",
"self",
".",
"_layer_meta",
"[",
"self",
".",
"_res_indices",
"["... | Resample all arrays with potentially different resolutions to a common resolution. | [
"Resample",
"all",
"arrays",
"with",
"potentially",
"different",
"resolutions",
"to",
"a",
"common",
"resolution",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L172-L195 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO._process_windows_merge_stack | def _process_windows_merge_stack(self, func, **kwargs):
"""Load (resampled) array of all windows, apply custom function on it, merge and stack results to one array."""
ji_results = self._process_windows(func, **kwargs)
for idx_layer in range(len(ji_results[0])): # this is the number of output l... | python | def _process_windows_merge_stack(self, func, **kwargs):
"""Load (resampled) array of all windows, apply custom function on it, merge and stack results to one array."""
ji_results = self._process_windows(func, **kwargs)
for idx_layer in range(len(ji_results[0])): # this is the number of output l... | [
"def",
"_process_windows_merge_stack",
"(",
"self",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"ji_results",
"=",
"self",
".",
"_process_windows",
"(",
"func",
",",
"*",
"*",
"kwargs",
")",
"for",
"idx_layer",
"in",
"range",
"(",
"len",
"(",
"ji_res... | Load (resampled) array of all windows, apply custom function on it, merge and stack results to one array. | [
"Load",
"(",
"resampled",
")",
"array",
"of",
"all",
"windows",
"apply",
"custom",
"function",
"on",
"it",
"merge",
"and",
"stack",
"results",
"to",
"one",
"array",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L228-L243 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO._process_windows | def _process_windows(self, func, **kwargs):
"""Load (resampled) array of all windows and apply custom function on it."""
ji_results = []
for ji_win in range(len(self.windows)):
ji_results.append(self._process_window(ji_win, func, **kwargs))
return ji_results | python | def _process_windows(self, func, **kwargs):
"""Load (resampled) array of all windows and apply custom function on it."""
ji_results = []
for ji_win in range(len(self.windows)):
ji_results.append(self._process_window(ji_win, func, **kwargs))
return ji_results | [
"def",
"_process_windows",
"(",
"self",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"ji_results",
"=",
"[",
"]",
"for",
"ji_win",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"windows",
")",
")",
":",
"ji_results",
".",
"append",
"(",
"self",
"... | Load (resampled) array of all windows and apply custom function on it. | [
"Load",
"(",
"resampled",
")",
"array",
"of",
"all",
"windows",
"and",
"apply",
"custom",
"function",
"on",
"it",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L245-L250 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO._process_window | def _process_window(self, ji_win, func, **kwargs):
"""Load (resampled) array of window ji_win and apply custom function on it. """
arr = self.get_arrays(ji_win)
result = func(arr, **kwargs)
return result | python | def _process_window(self, ji_win, func, **kwargs):
"""Load (resampled) array of window ji_win and apply custom function on it. """
arr = self.get_arrays(ji_win)
result = func(arr, **kwargs)
return result | [
"def",
"_process_window",
"(",
"self",
",",
"ji_win",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"arr",
"=",
"self",
".",
"get_arrays",
"(",
"ji_win",
")",
"result",
"=",
"func",
"(",
"arr",
",",
"*",
"*",
"kwargs",
")",
"return",
"result"
] | Load (resampled) array of window ji_win and apply custom function on it. | [
"Load",
"(",
"resampled",
")",
"array",
"of",
"window",
"ji_win",
"and",
"apply",
"custom",
"function",
"on",
"it",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L252-L256 |
benmack/eo-box | eobox/raster/rasterprocessing.py | MultiRasterIO.get_window_from_xy | def get_window_from_xy(self, xy):
"""Get the window index given a coordinate (raster CRS)."""
a_transform = self._get_template_for_given_resolution(res=self.dst_res, return_="meta")["transform"]
row, col = transform.rowcol(a_transform, xy[0], xy[1])
ij_containing_xy = None
for ji... | python | def get_window_from_xy(self, xy):
"""Get the window index given a coordinate (raster CRS)."""
a_transform = self._get_template_for_given_resolution(res=self.dst_res, return_="meta")["transform"]
row, col = transform.rowcol(a_transform, xy[0], xy[1])
ij_containing_xy = None
for ji... | [
"def",
"get_window_from_xy",
"(",
"self",
",",
"xy",
")",
":",
"a_transform",
"=",
"self",
".",
"_get_template_for_given_resolution",
"(",
"res",
"=",
"self",
".",
"dst_res",
",",
"return_",
"=",
"\"meta\"",
")",
"[",
"\"transform\"",
"]",
"row",
",",
"col",... | Get the window index given a coordinate (raster CRS). | [
"Get",
"the",
"window",
"index",
"given",
"a",
"coordinate",
"(",
"raster",
"CRS",
")",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L258-L271 |
benmack/eo-box | eobox/raster/extraction.py | extract | def extract(src_vector: str,
burn_attribute: str,
src_raster: list,
dst_names: list,
dst_dir: str,
src_raster_template: str = None,
gdal_dtype: int = 4,
n_jobs: int = 1):
"""Extract values from list of single band raster for pixels ... | python | def extract(src_vector: str,
burn_attribute: str,
src_raster: list,
dst_names: list,
dst_dir: str,
src_raster_template: str = None,
gdal_dtype: int = 4,
n_jobs: int = 1):
"""Extract values from list of single band raster for pixels ... | [
"def",
"extract",
"(",
"src_vector",
":",
"str",
",",
"burn_attribute",
":",
"str",
",",
"src_raster",
":",
"list",
",",
"dst_names",
":",
"list",
",",
"dst_dir",
":",
"str",
",",
"src_raster_template",
":",
"str",
"=",
"None",
",",
"gdal_dtype",
":",
"i... | Extract values from list of single band raster for pixels overlapping with a vector data.
The extracted data will be stored in the ``dst_dir`` by using the ``dst_names`` for the
filename. If a file with a given name already exists the raster will be skipped.
Arguments:
src_vector {str} -- Filename... | [
"Extract",
"values",
"from",
"list",
"of",
"single",
"band",
"raster",
"for",
"pixels",
"overlapping",
"with",
"a",
"vector",
"data",
"."
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/extraction.py#L14-L106 |
benmack/eo-box | eobox/raster/extraction.py | load_extracted | def load_extracted(src_dir: str,
patterns="*.npy",
vars_in_cols: bool = True,
index: pd.Series = None):
"""Load data extracted and stored by :py:func:`extract`
Arguments:
src_dir {str} -- The directory where the data is stored.
Keyword Argum... | python | def load_extracted(src_dir: str,
patterns="*.npy",
vars_in_cols: bool = True,
index: pd.Series = None):
"""Load data extracted and stored by :py:func:`extract`
Arguments:
src_dir {str} -- The directory where the data is stored.
Keyword Argum... | [
"def",
"load_extracted",
"(",
"src_dir",
":",
"str",
",",
"patterns",
"=",
"\"*.npy\"",
",",
"vars_in_cols",
":",
"bool",
"=",
"True",
",",
"index",
":",
"pd",
".",
"Series",
"=",
"None",
")",
":",
"def",
"_load",
"(",
"path",
",",
"index",
")",
":",... | Load data extracted and stored by :py:func:`extract`
Arguments:
src_dir {str} -- The directory where the data is stored.
Keyword Arguments:
patterns {str, or list of str} -- A pattern (str) or list of patterns (list)
to identify the variables to be loaded.
The default l... | [
"Load",
"data",
"extracted",
"and",
"stored",
"by",
":",
"py",
":",
"func",
":",
"extract"
] | train | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/extraction.py#L145-L195 |
Tenchi2xh/Almonds | almonds/plane.py | Plane.extrema | def extrema(self, x0, y0, w, h):
"""
Returns the minimum and maximum values contained in a given area.
:param x0: Starting x index.
:param y0: Starting y index.
:param w: Width of the area to scan.
:param h: Height of the area to scan.
:return: Tuple containi... | python | def extrema(self, x0, y0, w, h):
"""
Returns the minimum and maximum values contained in a given area.
:param x0: Starting x index.
:param y0: Starting y index.
:param w: Width of the area to scan.
:param h: Height of the area to scan.
:return: Tuple containi... | [
"def",
"extrema",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"w",
",",
"h",
")",
":",
"minimum",
"=",
"9223372036854775807",
"maximum",
"=",
"0",
"for",
"y",
"in",
"range",
"(",
"y0",
",",
"y0",
"+",
"h",
")",
":",
"for",
"x",
"in",
"range",
"(",
... | Returns the minimum and maximum values contained in a given area.
:param x0: Starting x index.
:param y0: Starting y index.
:param w: Width of the area to scan.
:param h: Height of the area to scan.
:return: Tuple containing the minimum and maximum values of the given area. | [
"Returns",
"the",
"minimum",
"and",
"maximum",
"values",
"contained",
"in",
"a",
"given",
"area",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/plane.py#L25-L43 |
Tenchi2xh/Almonds | almonds/cursebox/colortrans.py | rgb2short | def rgb2short(rgb):
""" Find the closest xterm-256 approximation to the given RGB value.
@param rgb: Hex code representing an RGB value, eg, 'abcdef'
@returns: String between 0 and 255, compatible with xterm.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('ffffff')
('231', 'ffffff')
... | python | def rgb2short(rgb):
""" Find the closest xterm-256 approximation to the given RGB value.
@param rgb: Hex code representing an RGB value, eg, 'abcdef'
@returns: String between 0 and 255, compatible with xterm.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('ffffff')
('231', 'ffffff')
... | [
"def",
"rgb2short",
"(",
"rgb",
")",
":",
"incs",
"=",
"(",
"0x00",
",",
"0x5f",
",",
"0x87",
",",
"0xaf",
",",
"0xd7",
",",
"0xff",
")",
"# Break 6-char RGB code into 3 integer vals.",
"parts",
"=",
"[",
"int",
"(",
"h",
",",
"16",
")",
"for",
"h",
... | Find the closest xterm-256 approximation to the given RGB value.
@param rgb: Hex code representing an RGB value, eg, 'abcdef'
@returns: String between 0 and 255, compatible with xterm.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('ffffff')
('231', 'ffffff')
>>> rgb2short('0DADD6') ... | [
"Find",
"the",
"closest",
"xterm",
"-",
"256",
"approximation",
"to",
"the",
"given",
"RGB",
"value",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/cursebox/colortrans.py#L298-L329 |
Tenchi2xh/Almonds | almonds/cursebox/cursebox.py | Cursebox.set_cursor | def set_cursor(self, x, y):
"""
Sets the cursor to the desired position.
:param x: X position
:param y: Y position
"""
curses.curs_set(1)
self.screen.move(y, x) | python | def set_cursor(self, x, y):
"""
Sets the cursor to the desired position.
:param x: X position
:param y: Y position
"""
curses.curs_set(1)
self.screen.move(y, x) | [
"def",
"set_cursor",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"curses",
".",
"curs_set",
"(",
"1",
")",
"self",
".",
"screen",
".",
"move",
"(",
"y",
",",
"x",
")"
] | Sets the cursor to the desired position.
:param x: X position
:param y: Y position | [
"Sets",
"the",
"cursor",
"to",
"the",
"desired",
"position",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/cursebox/cursebox.py#L37-L45 |
Tenchi2xh/Almonds | almonds/cursebox/cursebox.py | Cursebox.put | def put(self, x, y, text, fg, bg):
"""
Puts a string at the desired coordinates using the provided colors.
:param x: X position
:param y: Y position
:param text: Text to write
:param fg: Foreground color number
:param bg: Background color number
... | python | def put(self, x, y, text, fg, bg):
"""
Puts a string at the desired coordinates using the provided colors.
:param x: X position
:param y: Y position
:param text: Text to write
:param fg: Foreground color number
:param bg: Background color number
... | [
"def",
"put",
"(",
"self",
",",
"x",
",",
"y",
",",
"text",
",",
"fg",
",",
"bg",
")",
":",
"if",
"x",
"<",
"self",
".",
"width",
"and",
"y",
"<",
"self",
".",
"height",
":",
"try",
":",
"self",
".",
"screen",
".",
"addstr",
"(",
"y",
",",
... | Puts a string at the desired coordinates using the provided colors.
:param x: X position
:param y: Y position
:param text: Text to write
:param fg: Foreground color number
:param bg: Background color number | [
"Puts",
"a",
"string",
"at",
"the",
"desired",
"coordinates",
"using",
"the",
"provided",
"colors",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/cursebox/cursebox.py#L53-L68 |
Tenchi2xh/Almonds | almonds/cursebox/cursebox.py | Cursebox.poll_event | def poll_event(self):
"""
Waits for an event to happen and returns a string related to the event.
If the event is a normal (letter) key press, the letter is returned (case sensitive)
:return: Event type
"""
# Flush all inputs before this one that were done since last po... | python | def poll_event(self):
"""
Waits for an event to happen and returns a string related to the event.
If the event is a normal (letter) key press, the letter is returned (case sensitive)
:return: Event type
"""
# Flush all inputs before this one that were done since last po... | [
"def",
"poll_event",
"(",
"self",
")",
":",
"# Flush all inputs before this one that were done since last poll",
"curses",
".",
"flushinp",
"(",
")",
"ch",
"=",
"self",
".",
"screen",
".",
"getch",
"(",
")",
"if",
"ch",
"==",
"27",
":",
"return",
"EVENT_ESC",
... | Waits for an event to happen and returns a string related to the event.
If the event is a normal (letter) key press, the letter is returned (case sensitive)
:return: Event type | [
"Waits",
"for",
"an",
"event",
"to",
"happen",
"and",
"returns",
"a",
"string",
"related",
"to",
"the",
"event",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/cursebox/cursebox.py#L107-L141 |
Tenchi2xh/Almonds | almonds/almonds.py | compute | def compute(args):
x, y, params = args
"""Callable function for the multiprocessing pool."""
return x, y, mandelbrot(x, y, params) | python | def compute(args):
x, y, params = args
"""Callable function for the multiprocessing pool."""
return x, y, mandelbrot(x, y, params) | [
"def",
"compute",
"(",
"args",
")",
":",
"x",
",",
"y",
",",
"params",
"=",
"args",
"return",
"x",
",",
"y",
",",
"mandelbrot",
"(",
"x",
",",
"y",
",",
"params",
")"
] | Callable function for the multiprocessing pool. | [
"Callable",
"function",
"for",
"the",
"multiprocessing",
"pool",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/almonds.py#L31-L34 |
Tenchi2xh/Almonds | almonds/almonds.py | compute_capture | def compute_capture(args):
x, y, w, h, params = args
"""Callable function for the multiprocessing pool."""
return x, y, mandelbrot_capture(x, y, w, h, params) | python | def compute_capture(args):
x, y, w, h, params = args
"""Callable function for the multiprocessing pool."""
return x, y, mandelbrot_capture(x, y, w, h, params) | [
"def",
"compute_capture",
"(",
"args",
")",
":",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"params",
"=",
"args",
"return",
"x",
",",
"y",
",",
"mandelbrot_capture",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"params",
")"
] | Callable function for the multiprocessing pool. | [
"Callable",
"function",
"for",
"the",
"multiprocessing",
"pool",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/almonds.py#L37-L40 |
Tenchi2xh/Almonds | almonds/almonds.py | draw_panel | def draw_panel(cb, pool, params, plane):
"""
Draws the application's main panel, displaying the current Mandelbrot view.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the cu... | python | def draw_panel(cb, pool, params, plane):
"""
Draws the application's main panel, displaying the current Mandelbrot view.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the cu... | [
"def",
"draw_panel",
"(",
"cb",
",",
"pool",
",",
"params",
",",
"plane",
")",
":",
"w",
"=",
"cb",
".",
"width",
"-",
"MENU_WIDTH",
"-",
"1",
"h",
"=",
"cb",
".",
"height",
"-",
"1",
"params",
".",
"plane_w",
"=",
"w",
"params",
".",
"plane_h",
... | Draws the application's main panel, displaying the current Mandelbrot view.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:type plane: plane.Plane | [
"Draws",
"the",
"application",
"s",
"main",
"panel",
"displaying",
"the",
"current",
"Mandelbrot",
"view",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/almonds.py#L43-L138 |
Tenchi2xh/Almonds | almonds/almonds.py | draw_menu | def draw_menu(cb, params, qwertz):
"""
Draws the application's side menu and options.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
"""
w = cb.width
h = cb.height
x0 = w - MENU_WIDTH + 1
... | python | def draw_menu(cb, params, qwertz):
"""
Draws the application's side menu and options.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
"""
w = cb.width
h = cb.height
x0 = w - MENU_WIDTH + 1
... | [
"def",
"draw_menu",
"(",
"cb",
",",
"params",
",",
"qwertz",
")",
":",
"w",
"=",
"cb",
".",
"width",
"h",
"=",
"cb",
".",
"height",
"x0",
"=",
"w",
"-",
"MENU_WIDTH",
"+",
"1",
"# Clear buffer inside the box",
"fill",
"(",
"cb",
",",
"x0",
",",
"1"... | Draws the application's side menu and options.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params | [
"Draws",
"the",
"application",
"s",
"side",
"menu",
"and",
"options",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/almonds.py#L141-L232 |
Tenchi2xh/Almonds | almonds/almonds.py | update_display | def update_display(cb, pool, params, plane, qwertz):
"""
Draws everything.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:type plane: plan... | python | def update_display(cb, pool, params, plane, qwertz):
"""
Draws everything.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:type plane: plan... | [
"def",
"update_display",
"(",
"cb",
",",
"pool",
",",
"params",
",",
"plane",
",",
"qwertz",
")",
":",
"cb",
".",
"clear",
"(",
")",
"draw_panel",
"(",
"cb",
",",
"pool",
",",
"params",
",",
"plane",
")",
"update_position",
"(",
"params",
")",
"# Upd... | Draws everything.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:type plane: plane.Plane
:return: | [
"Draws",
"everything",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/almonds.py#L235-L251 |
Tenchi2xh/Almonds | almonds/almonds.py | save | def save(params):
"""
Saves the current parameters to a file.
:param params: Current application parameters.
:return:
"""
if is_python3():
import pickle
cPickle = pickle
else:
import cPickle
ts = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d_%H-... | python | def save(params):
"""
Saves the current parameters to a file.
:param params: Current application parameters.
:return:
"""
if is_python3():
import pickle
cPickle = pickle
else:
import cPickle
ts = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d_%H-... | [
"def",
"save",
"(",
"params",
")",
":",
"if",
"is_python3",
"(",
")",
":",
"import",
"pickle",
"cPickle",
"=",
"pickle",
"else",
":",
"import",
"cPickle",
"ts",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"time",
".",
"time",
"(",
")",... | Saves the current parameters to a file.
:param params: Current application parameters.
:return: | [
"Saves",
"the",
"current",
"parameters",
"to",
"a",
"file",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/almonds.py#L254-L271 |
Tenchi2xh/Almonds | almonds/almonds.py | capture | def capture(cb, pool, params):
"""
Renders and saves a screen-sized picture of the current position.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
"""
w, h = screen_resolution()
# Re-adapt dimens... | python | def capture(cb, pool, params):
"""
Renders and saves a screen-sized picture of the current position.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
"""
w, h = screen_resolution()
# Re-adapt dimens... | [
"def",
"capture",
"(",
"cb",
",",
"pool",
",",
"params",
")",
":",
"w",
",",
"h",
"=",
"screen_resolution",
"(",
")",
"# Re-adapt dimensions to match current plane ratio",
"old_ratio",
"=",
"w",
"/",
"h",
"new_ratio",
"=",
"params",
".",
"plane_ratio",
"if",
... | Renders and saves a screen-sized picture of the current position.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params | [
"Renders",
"and",
"saves",
"a",
"screen",
"-",
"sized",
"picture",
"of",
"the",
"current",
"position",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/almonds.py#L274-L341 |
Tenchi2xh/Almonds | almonds/almonds.py | cycle | def cycle(cb, pool, params, plane):
"""
Fun function to do a palette cycling animation.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:typ... | python | def cycle(cb, pool, params, plane):
"""
Fun function to do a palette cycling animation.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:typ... | [
"def",
"cycle",
"(",
"cb",
",",
"pool",
",",
"params",
",",
"plane",
")",
":",
"step",
"=",
"params",
".",
"max_iterations",
"//",
"20",
"if",
"step",
"==",
"0",
":",
"step",
"=",
"1",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"params",
".",
"m... | Fun function to do a palette cycling animation.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:type plane: plane.Plane
:return: | [
"Fun",
"function",
"to",
"do",
"a",
"palette",
"cycling",
"animation",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/almonds.py#L344-L363 |
Tenchi2xh/Almonds | almonds/almonds.py | init_coords | def init_coords(cb, params):
"""
Initializes coordinates and zoom for first use.
Loads coordinates from Mandelbrot-space.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:return:
"""
w = cb.wid... | python | def init_coords(cb, params):
"""
Initializes coordinates and zoom for first use.
Loads coordinates from Mandelbrot-space.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:return:
"""
w = cb.wid... | [
"def",
"init_coords",
"(",
"cb",
",",
"params",
")",
":",
"w",
"=",
"cb",
".",
"width",
"-",
"MENU_WIDTH",
"-",
"1",
"h",
"=",
"cb",
".",
"height",
"-",
"1",
"params",
".",
"plane_w",
"=",
"w",
"params",
".",
"plane_h",
"=",
"h",
"params",
".",
... | Initializes coordinates and zoom for first use.
Loads coordinates from Mandelbrot-space.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:return: | [
"Initializes",
"coordinates",
"and",
"zoom",
"for",
"first",
"use",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/almonds.py#L366-L385 |
Tenchi2xh/Almonds | almonds/utils.py | clamp | def clamp(n, lower, upper):
"""
Restricts the given number to a lower and upper bound (inclusive)
:param n: input number
:param lower: lower bound (inclusive)
:param upper: upper bound (inclusive)
:return: clamped number
"""
if lower > upper:
lower, upper = upper, lower... | python | def clamp(n, lower, upper):
"""
Restricts the given number to a lower and upper bound (inclusive)
:param n: input number
:param lower: lower bound (inclusive)
:param upper: upper bound (inclusive)
:return: clamped number
"""
if lower > upper:
lower, upper = upper, lower... | [
"def",
"clamp",
"(",
"n",
",",
"lower",
",",
"upper",
")",
":",
"if",
"lower",
">",
"upper",
":",
"lower",
",",
"upper",
"=",
"upper",
",",
"lower",
"return",
"max",
"(",
"min",
"(",
"upper",
",",
"n",
")",
",",
"lower",
")"
] | Restricts the given number to a lower and upper bound (inclusive)
:param n: input number
:param lower: lower bound (inclusive)
:param upper: upper bound (inclusive)
:return: clamped number | [
"Restricts",
"the",
"given",
"number",
"to",
"a",
"lower",
"and",
"upper",
"bound",
"(",
"inclusive",
")"
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/utils.py#L8-L19 |
Tenchi2xh/Almonds | almonds/utils.py | screen_resolution | def screen_resolution():
"""
Returns the current screen's resolution.
Should be multi-platform.
:return: A tuple containing the width and height of the screen.
"""
w = 0
h = 0
try:
# Windows
import ctypes
user32 = ctypes.windll.user32
w, h = user32.GetSy... | python | def screen_resolution():
"""
Returns the current screen's resolution.
Should be multi-platform.
:return: A tuple containing the width and height of the screen.
"""
w = 0
h = 0
try:
# Windows
import ctypes
user32 = ctypes.windll.user32
w, h = user32.GetSy... | [
"def",
"screen_resolution",
"(",
")",
":",
"w",
"=",
"0",
"h",
"=",
"0",
"try",
":",
"# Windows",
"import",
"ctypes",
"user32",
"=",
"ctypes",
".",
"windll",
".",
"user32",
"w",
",",
"h",
"=",
"user32",
".",
"GetSystemMetrics",
"(",
"0",
")",
",",
... | Returns the current screen's resolution.
Should be multi-platform.
:return: A tuple containing the width and height of the screen. | [
"Returns",
"the",
"current",
"screen",
"s",
"resolution",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/utils.py#L22-L56 |
Tenchi2xh/Almonds | almonds/utils.py | open_file | def open_file(filename):
"""
Multi-platform way to make the OS open a file with its default application
"""
if sys.platform.startswith("darwin"):
subprocess.call(("open", filename))
elif sys.platform == "cygwin":
subprocess.call(("cygstart", filename))
elif os.name == "nt":
... | python | def open_file(filename):
"""
Multi-platform way to make the OS open a file with its default application
"""
if sys.platform.startswith("darwin"):
subprocess.call(("open", filename))
elif sys.platform == "cygwin":
subprocess.call(("cygstart", filename))
elif os.name == "nt":
... | [
"def",
"open_file",
"(",
"filename",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"darwin\"",
")",
":",
"subprocess",
".",
"call",
"(",
"(",
"\"open\"",
",",
"filename",
")",
")",
"elif",
"sys",
".",
"platform",
"==",
"\"cygwin\"",
... | Multi-platform way to make the OS open a file with its default application | [
"Multi",
"-",
"platform",
"way",
"to",
"make",
"the",
"OS",
"open",
"a",
"file",
"with",
"its",
"default",
"application"
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/utils.py#L59-L70 |
Tenchi2xh/Almonds | almonds/graphics/drawing.py | dither_symbol | def dither_symbol(value, dither):
"""
Returns the appropriate block drawing symbol for the given intensity.
:param value: intensity of the color, in the range [0.0, 1.0]
:return: dithered symbol representing that intensity
"""
dither = DITHER_TYPES[dither][1]
return dither[int(round(value * ... | python | def dither_symbol(value, dither):
"""
Returns the appropriate block drawing symbol for the given intensity.
:param value: intensity of the color, in the range [0.0, 1.0]
:return: dithered symbol representing that intensity
"""
dither = DITHER_TYPES[dither][1]
return dither[int(round(value * ... | [
"def",
"dither_symbol",
"(",
"value",
",",
"dither",
")",
":",
"dither",
"=",
"DITHER_TYPES",
"[",
"dither",
"]",
"[",
"1",
"]",
"return",
"dither",
"[",
"int",
"(",
"round",
"(",
"value",
"*",
"(",
"len",
"(",
"dither",
")",
"-",
"1",
")",
")",
... | Returns the appropriate block drawing symbol for the given intensity.
:param value: intensity of the color, in the range [0.0, 1.0]
:return: dithered symbol representing that intensity | [
"Returns",
"the",
"appropriate",
"block",
"drawing",
"symbol",
"for",
"the",
"given",
"intensity",
".",
":",
"param",
"value",
":",
"intensity",
"of",
"the",
"color",
"in",
"the",
"range",
"[",
"0",
".",
"0",
"1",
".",
"0",
"]",
":",
"return",
":",
"... | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/graphics/drawing.py#L66-L73 |
Tenchi2xh/Almonds | almonds/graphics/drawing.py | draw_dithered_color | def draw_dithered_color(cb, x, y, palette, dither, n, n_max, crosshairs_coord=None):
"""
Draws a dithered color block on the terminal, given a palette.
:type cb: cursebox.CurseBox
"""
i = n * (len(palette) - 1) / n_max
c1 = palette[int(math.floor(i))]
c2 = palette[int(math.ceil(i))]
valu... | python | def draw_dithered_color(cb, x, y, palette, dither, n, n_max, crosshairs_coord=None):
"""
Draws a dithered color block on the terminal, given a palette.
:type cb: cursebox.CurseBox
"""
i = n * (len(palette) - 1) / n_max
c1 = palette[int(math.floor(i))]
c2 = palette[int(math.ceil(i))]
valu... | [
"def",
"draw_dithered_color",
"(",
"cb",
",",
"x",
",",
"y",
",",
"palette",
",",
"dither",
",",
"n",
",",
"n_max",
",",
"crosshairs_coord",
"=",
"None",
")",
":",
"i",
"=",
"n",
"*",
"(",
"len",
"(",
"palette",
")",
"-",
"1",
")",
"/",
"n_max",
... | Draws a dithered color block on the terminal, given a palette.
:type cb: cursebox.CurseBox | [
"Draws",
"a",
"dithered",
"color",
"block",
"on",
"the",
"terminal",
"given",
"a",
"palette",
".",
":",
"type",
"cb",
":",
"cursebox",
".",
"CurseBox"
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/graphics/drawing.py#L76-L101 |
Tenchi2xh/Almonds | almonds/graphics/drawing.py | draw_box | def draw_box(cb, x0, y0, w, h, fg=colors.default_fg, bg=colors.default_bg, h_seps=[], v_seps=[]):
"""
Draws a box in the given terminal.
:type cb: cursebox.CurseBox
"""
w -= 1
h -= 1
corners = [(x0, y0), (x0 + w, y0), (x0, y0 + h), (x0 + w, y0 + h)]
fg = fg()
bg = bg()
for i, c... | python | def draw_box(cb, x0, y0, w, h, fg=colors.default_fg, bg=colors.default_bg, h_seps=[], v_seps=[]):
"""
Draws a box in the given terminal.
:type cb: cursebox.CurseBox
"""
w -= 1
h -= 1
corners = [(x0, y0), (x0 + w, y0), (x0, y0 + h), (x0 + w, y0 + h)]
fg = fg()
bg = bg()
for i, c... | [
"def",
"draw_box",
"(",
"cb",
",",
"x0",
",",
"y0",
",",
"w",
",",
"h",
",",
"fg",
"=",
"colors",
".",
"default_fg",
",",
"bg",
"=",
"colors",
".",
"default_bg",
",",
"h_seps",
"=",
"[",
"]",
",",
"v_seps",
"=",
"[",
"]",
")",
":",
"w",
"-=",... | Draws a box in the given terminal.
:type cb: cursebox.CurseBox | [
"Draws",
"a",
"box",
"in",
"the",
"given",
"terminal",
".",
":",
"type",
"cb",
":",
"cursebox",
".",
"CurseBox"
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/graphics/drawing.py#L132-L160 |
Tenchi2xh/Almonds | almonds/graphics/drawing.py | draw_progress_bar | def draw_progress_bar(cb, message, value, max_value):
"""
:type cb: cursebox.Cursebox
"""
m_x = cb.width // 2
m_y = cb.height // 2
w = len(message) + 4
h = 3
draw_box(cb, m_x - w // 2, m_y - 1, w, h)
message = " %s " % message
i = int((value / max_value) * (len(message) + 2))
... | python | def draw_progress_bar(cb, message, value, max_value):
"""
:type cb: cursebox.Cursebox
"""
m_x = cb.width // 2
m_y = cb.height // 2
w = len(message) + 4
h = 3
draw_box(cb, m_x - w // 2, m_y - 1, w, h)
message = " %s " % message
i = int((value / max_value) * (len(message) + 2))
... | [
"def",
"draw_progress_bar",
"(",
"cb",
",",
"message",
",",
"value",
",",
"max_value",
")",
":",
"m_x",
"=",
"cb",
".",
"width",
"//",
"2",
"m_y",
"=",
"cb",
".",
"height",
"//",
"2",
"w",
"=",
"len",
"(",
"message",
")",
"+",
"4",
"h",
"=",
"3... | :type cb: cursebox.Cursebox | [
":",
"type",
"cb",
":",
"cursebox",
".",
"Cursebox"
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/graphics/drawing.py#L163-L175 |
Tenchi2xh/Almonds | almonds/mandelbrot.py | mandelbrot_iterate | def mandelbrot_iterate(c, max_iterations, julia_seed=None):
"""
Returns the number of iterations before escaping the Mandelbrot fractal.
:param c: Coordinates as a complex number
:type c: complex
:param max_iterations: Limit of how many tries are attempted.
:return: Tuple containing the last co... | python | def mandelbrot_iterate(c, max_iterations, julia_seed=None):
"""
Returns the number of iterations before escaping the Mandelbrot fractal.
:param c: Coordinates as a complex number
:type c: complex
:param max_iterations: Limit of how many tries are attempted.
:return: Tuple containing the last co... | [
"def",
"mandelbrot_iterate",
"(",
"c",
",",
"max_iterations",
",",
"julia_seed",
"=",
"None",
")",
":",
"z",
"=",
"c",
"if",
"julia_seed",
"is",
"not",
"None",
":",
"c",
"=",
"julia_seed",
"for",
"iterations",
"in",
"range",
"(",
"max_iterations",
")",
"... | Returns the number of iterations before escaping the Mandelbrot fractal.
:param c: Coordinates as a complex number
:type c: complex
:param max_iterations: Limit of how many tries are attempted.
:return: Tuple containing the last complex number in the sequence and the number of iterations. | [
"Returns",
"the",
"number",
"of",
"iterations",
"before",
"escaping",
"the",
"Mandelbrot",
"fractal",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/mandelbrot.py#L11-L27 |
Tenchi2xh/Almonds | almonds/mandelbrot.py | get_coords | def get_coords(x, y, params):
"""
Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary).
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Tuple c... | python | def get_coords(x, y, params):
"""
Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary).
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Tuple c... | [
"def",
"get_coords",
"(",
"x",
",",
"y",
",",
"params",
")",
":",
"n_x",
"=",
"x",
"*",
"2.0",
"/",
"params",
".",
"plane_w",
"*",
"params",
".",
"plane_ratio",
"-",
"1.0",
"n_y",
"=",
"y",
"*",
"2.0",
"/",
"params",
".",
"plane_h",
"-",
"1.0",
... | Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary).
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Tuple containing the re-mapped coordinates in Man... | [
"Transforms",
"the",
"given",
"coordinates",
"from",
"plane",
"-",
"space",
"to",
"Mandelbrot",
"-",
"space",
"(",
"real",
"and",
"imaginary",
")",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/mandelbrot.py#L30-L44 |
Tenchi2xh/Almonds | almonds/mandelbrot.py | mandelbrot | def mandelbrot(x, y, params):
"""
Computes the number of iterations of the given plane-space coordinates.
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Discrete number of iteratio... | python | def mandelbrot(x, y, params):
"""
Computes the number of iterations of the given plane-space coordinates.
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Discrete number of iteratio... | [
"def",
"mandelbrot",
"(",
"x",
",",
"y",
",",
"params",
")",
":",
"mb_x",
",",
"mb_y",
"=",
"get_coords",
"(",
"x",
",",
"y",
",",
"params",
")",
"mb",
"=",
"mandelbrot_iterate",
"(",
"mb_x",
"+",
"1j",
"*",
"mb_y",
",",
"params",
".",
"max_iterati... | Computes the number of iterations of the given plane-space coordinates.
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Discrete number of iterations. | [
"Computes",
"the",
"number",
"of",
"iterations",
"of",
"the",
"given",
"plane",
"-",
"space",
"coordinates",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/mandelbrot.py#L47-L60 |
Tenchi2xh/Almonds | almonds/mandelbrot.py | mandelbrot_capture | def mandelbrot_capture(x, y, w, h, params):
"""
Computes the number of iterations of the given pixel-space coordinates,
for high-res capture purposes.
Contrary to :func:`mandelbrot`, this function returns a continuous
number of iterations to avoid banding.
:param x: X coordinate on the picture... | python | def mandelbrot_capture(x, y, w, h, params):
"""
Computes the number of iterations of the given pixel-space coordinates,
for high-res capture purposes.
Contrary to :func:`mandelbrot`, this function returns a continuous
number of iterations to avoid banding.
:param x: X coordinate on the picture... | [
"def",
"mandelbrot_capture",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"params",
")",
":",
"# FIXME: Figure out why these corrections are necessary or how to make them perfect",
"# Viewport is offset compared to window when capturing without these (found empirically)",
"if",
"pa... | Computes the number of iterations of the given pixel-space coordinates,
for high-res capture purposes.
Contrary to :func:`mandelbrot`, this function returns a continuous
number of iterations to avoid banding.
:param x: X coordinate on the picture
:param y: Y coordinate on the picture
:param w:... | [
"Computes",
"the",
"number",
"of",
"iterations",
"of",
"the",
"given",
"pixel",
"-",
"space",
"coordinates",
"for",
"high",
"-",
"res",
"capture",
"purposes",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/mandelbrot.py#L63-L102 |
Tenchi2xh/Almonds | almonds/mandelbrot.py | update_position | def update_position(params):
"""
Computes the center of the viewport's Mandelbrot-space coordinates.
:param params: Current application parameters.
:type params: params.Params
"""
cx = params.plane_x0 + params.plane_w / 2.0
cy = params.plane_y0 + params.plane_h / 2.0
params.mb_cx, param... | python | def update_position(params):
"""
Computes the center of the viewport's Mandelbrot-space coordinates.
:param params: Current application parameters.
:type params: params.Params
"""
cx = params.plane_x0 + params.plane_w / 2.0
cy = params.plane_y0 + params.plane_h / 2.0
params.mb_cx, param... | [
"def",
"update_position",
"(",
"params",
")",
":",
"cx",
"=",
"params",
".",
"plane_x0",
"+",
"params",
".",
"plane_w",
"/",
"2.0",
"cy",
"=",
"params",
".",
"plane_y0",
"+",
"params",
".",
"plane_h",
"/",
"2.0",
"params",
".",
"mb_cx",
",",
"params",
... | Computes the center of the viewport's Mandelbrot-space coordinates.
:param params: Current application parameters.
:type params: params.Params | [
"Computes",
"the",
"center",
"of",
"the",
"viewport",
"s",
"Mandelbrot",
"-",
"space",
"coordinates",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/mandelbrot.py#L105-L114 |
Tenchi2xh/Almonds | almonds/mandelbrot.py | zoom | def zoom(params, factor):
"""
Applies a zoom on the current parameters.
Computes the top-left plane-space coordinates from the Mandelbrot-space coordinates.
:param params: Current application parameters.
:param factor: Zoom factor by which the zoom ratio is divided (bigger factor, more zoom)
"... | python | def zoom(params, factor):
"""
Applies a zoom on the current parameters.
Computes the top-left plane-space coordinates from the Mandelbrot-space coordinates.
:param params: Current application parameters.
:param factor: Zoom factor by which the zoom ratio is divided (bigger factor, more zoom)
"... | [
"def",
"zoom",
"(",
"params",
",",
"factor",
")",
":",
"params",
".",
"zoom",
"/=",
"factor",
"n_x",
"=",
"params",
".",
"mb_cx",
"/",
"params",
".",
"zoom",
"n_y",
"=",
"params",
".",
"mb_cy",
"/",
"params",
".",
"zoom",
"params",
".",
"plane_x0",
... | Applies a zoom on the current parameters.
Computes the top-left plane-space coordinates from the Mandelbrot-space coordinates.
:param params: Current application parameters.
:param factor: Zoom factor by which the zoom ratio is divided (bigger factor, more zoom) | [
"Applies",
"a",
"zoom",
"on",
"the",
"current",
"parameters",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/mandelbrot.py#L117-L132 |
Tenchi2xh/Almonds | almonds/params.py | Params.resize | def resize(self, w, h):
"""
Used when resizing the plane, resets the plane ratio factor.
:param w: New width of the visible section of the plane.
:param h: New height of the visible section of the plane.
"""
self.plane_w = w
self.plane_h = h
self.plane_ra... | python | def resize(self, w, h):
"""
Used when resizing the plane, resets the plane ratio factor.
:param w: New width of the visible section of the plane.
:param h: New height of the visible section of the plane.
"""
self.plane_w = w
self.plane_h = h
self.plane_ra... | [
"def",
"resize",
"(",
"self",
",",
"w",
",",
"h",
")",
":",
"self",
".",
"plane_w",
"=",
"w",
"self",
".",
"plane_h",
"=",
"h",
"self",
".",
"plane_ratio",
"=",
"self",
".",
"char_ratio",
"*",
"w",
"/",
"h",
"if",
"self",
".",
"crosshairs",
":",
... | Used when resizing the plane, resets the plane ratio factor.
:param w: New width of the visible section of the plane.
:param h: New height of the visible section of the plane. | [
"Used",
"when",
"resizing",
"the",
"plane",
"resets",
"the",
"plane",
"ratio",
"factor",
"."
] | train | https://github.com/Tenchi2xh/Almonds/blob/6b27024729f055f2cb5e14ae3ca3cb428ae054bc/almonds/params.py#L71-L83 |
jaywink/federation | federation/entities/diaspora/mappers.py | check_sender_and_entity_handle_match | def check_sender_and_entity_handle_match(sender_handle, entity_handle):
"""Ensure that sender and entity handles match.
Basically we've already verified the sender is who they say when receiving the payload. However, the sender might
be trying to set another author in the payload itself, since Diaspora has... | python | def check_sender_and_entity_handle_match(sender_handle, entity_handle):
"""Ensure that sender and entity handles match.
Basically we've already verified the sender is who they say when receiving the payload. However, the sender might
be trying to set another author in the payload itself, since Diaspora has... | [
"def",
"check_sender_and_entity_handle_match",
"(",
"sender_handle",
",",
"entity_handle",
")",
":",
"if",
"sender_handle",
"!=",
"entity_handle",
":",
"logger",
".",
"warning",
"(",
"\"sender_handle and entity_handle don't match, aborting! sender_handle: %s, entity_handle: %s\"",
... | Ensure that sender and entity handles match.
Basically we've already verified the sender is who they say when receiving the payload. However, the sender might
be trying to set another author in the payload itself, since Diaspora has the sender in both the payload headers
AND the object. We must ensure they... | [
"Ensure",
"that",
"sender",
"and",
"entity",
"handles",
"match",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/mappers.py#L62-L73 |
jaywink/federation | federation/entities/diaspora/mappers.py | element_to_objects | def element_to_objects(
element: etree.ElementTree, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None,
) -> List:
"""Transform an Element to a list of entities recursively.
Possible child entities are added to each entity ``_children`` list.
:param tree: Element
:... | python | def element_to_objects(
element: etree.ElementTree, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None,
) -> List:
"""Transform an Element to a list of entities recursively.
Possible child entities are added to each entity ``_children`` list.
:param tree: Element
:... | [
"def",
"element_to_objects",
"(",
"element",
":",
"etree",
".",
"ElementTree",
",",
"sender",
":",
"str",
",",
"sender_key_fetcher",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"str",
"]",
"=",
"None",
",",
"user",
":",
"UserType",
"=",
"None",
",",
")... | Transform an Element to a list of entities recursively.
Possible child entities are added to each entity ``_children`` list.
:param tree: Element
:param sender: Payload sender id
:param sender_key_fetcher: Function to fetch sender public key. If not given, key will always be fetched
over netwo... | [
"Transform",
"an",
"Element",
"to",
"a",
"list",
"of",
"entities",
"recursively",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/mappers.py#L76-L135 |
jaywink/federation | federation/entities/diaspora/mappers.py | message_to_objects | def message_to_objects(
message: str, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None,
) -> List:
"""Takes in a message extracted by a protocol and maps it to entities.
:param message: XML payload
:type message: str
:param sender: Payload sender id
:type mess... | python | def message_to_objects(
message: str, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None,
) -> List:
"""Takes in a message extracted by a protocol and maps it to entities.
:param message: XML payload
:type message: str
:param sender: Payload sender id
:type mess... | [
"def",
"message_to_objects",
"(",
"message",
":",
"str",
",",
"sender",
":",
"str",
",",
"sender_key_fetcher",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"str",
"]",
"=",
"None",
",",
"user",
":",
"UserType",
"=",
"None",
",",
")",
"->",
"List",
":"... | Takes in a message extracted by a protocol and maps it to entities.
:param message: XML payload
:type message: str
:param sender: Payload sender id
:type message: str
:param sender_key_fetcher: Function to fetch sender public key. If not given, key will always be fetched
over network. The f... | [
"Takes",
"in",
"a",
"message",
"extracted",
"by",
"a",
"protocol",
"and",
"maps",
"it",
"to",
"entities",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/mappers.py#L138-L155 |
jaywink/federation | federation/entities/diaspora/mappers.py | transform_attributes | def transform_attributes(attrs, cls):
"""Transform some attribute keys.
:param attrs: Properties from the XML
:type attrs: dict
:param cls: Class of the entity
:type cls: class
"""
transformed = {}
for key, value in attrs.items():
if value is None:
value = ""
... | python | def transform_attributes(attrs, cls):
"""Transform some attribute keys.
:param attrs: Properties from the XML
:type attrs: dict
:param cls: Class of the entity
:type cls: class
"""
transformed = {}
for key, value in attrs.items():
if value is None:
value = ""
... | [
"def",
"transform_attributes",
"(",
"attrs",
",",
"cls",
")",
":",
"transformed",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"\"\"",
"if",
"key",
"==",
"\"t... | Transform some attribute keys.
:param attrs: Properties from the XML
:type attrs: dict
:param cls: Class of the entity
:type cls: class | [
"Transform",
"some",
"attribute",
"keys",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/mappers.py#L158-L233 |
jaywink/federation | federation/entities/diaspora/mappers.py | get_outbound_entity | def get_outbound_entity(entity: BaseEntity, private_key: RsaKey):
"""Get the correct outbound entity for this protocol.
We might have to look at entity values to decide the correct outbound entity.
If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol.
Private... | python | def get_outbound_entity(entity: BaseEntity, private_key: RsaKey):
"""Get the correct outbound entity for this protocol.
We might have to look at entity values to decide the correct outbound entity.
If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol.
Private... | [
"def",
"get_outbound_entity",
"(",
"entity",
":",
"BaseEntity",
",",
"private_key",
":",
"RsaKey",
")",
":",
"if",
"getattr",
"(",
"entity",
",",
"\"outbound_doc\"",
",",
"None",
")",
":",
"# If the entity already has an outbound doc, just return the entity as is",
"ret... | Get the correct outbound entity for this protocol.
We might have to look at entity values to decide the correct outbound entity.
If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol.
Private key of author is needed to be passed for signing the outbound entity.
... | [
"Get",
"the",
"correct",
"outbound",
"entity",
"for",
"this",
"protocol",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/mappers.py#L236-L283 |
jaywink/federation | federation/protocols/diaspora/signatures.py | get_element_child_info | def get_element_child_info(doc, attr):
"""Get information from child elements of this elementas a list since order is important.
Don't include signature tags.
:param doc: XML element
:param attr: Attribute to get from the elements, for example "tag" or "text".
"""
props = []
for child in d... | python | def get_element_child_info(doc, attr):
"""Get information from child elements of this elementas a list since order is important.
Don't include signature tags.
:param doc: XML element
:param attr: Attribute to get from the elements, for example "tag" or "text".
"""
props = []
for child in d... | [
"def",
"get_element_child_info",
"(",
"doc",
",",
"attr",
")",
":",
"props",
"=",
"[",
"]",
"for",
"child",
"in",
"doc",
":",
"if",
"child",
".",
"tag",
"not",
"in",
"[",
"\"author_signature\"",
",",
"\"parent_author_signature\"",
"]",
":",
"props",
".",
... | Get information from child elements of this elementas a list since order is important.
Don't include signature tags.
:param doc: XML element
:param attr: Attribute to get from the elements, for example "tag" or "text". | [
"Get",
"information",
"from",
"child",
"elements",
"of",
"this",
"elementas",
"a",
"list",
"since",
"order",
"is",
"important",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/signatures.py#L9-L21 |
jaywink/federation | federation/protocols/diaspora/signatures.py | verify_relayable_signature | def verify_relayable_signature(public_key, doc, signature):
"""
Verify the signed XML elements to have confidence that the claimed
author did actually generate this message.
"""
sig_hash = _create_signature_hash(doc)
cipher = PKCS1_v1_5.new(RSA.importKey(public_key))
return cipher.verify(sig... | python | def verify_relayable_signature(public_key, doc, signature):
"""
Verify the signed XML elements to have confidence that the claimed
author did actually generate this message.
"""
sig_hash = _create_signature_hash(doc)
cipher = PKCS1_v1_5.new(RSA.importKey(public_key))
return cipher.verify(sig... | [
"def",
"verify_relayable_signature",
"(",
"public_key",
",",
"doc",
",",
"signature",
")",
":",
"sig_hash",
"=",
"_create_signature_hash",
"(",
"doc",
")",
"cipher",
"=",
"PKCS1_v1_5",
".",
"new",
"(",
"RSA",
".",
"importKey",
"(",
"public_key",
")",
")",
"r... | Verify the signed XML elements to have confidence that the claimed
author did actually generate this message. | [
"Verify",
"the",
"signed",
"XML",
"elements",
"to",
"have",
"confidence",
"that",
"the",
"claimed",
"author",
"did",
"actually",
"generate",
"this",
"message",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/signatures.py#L30-L37 |
jaywink/federation | federation/hostmeta/django/generators.py | rfc7033_webfinger_view | def rfc7033_webfinger_view(request, *args, **kwargs):
"""
Django view to generate an RFC7033 webfinger.
"""
resource = request.GET.get("resource")
if not resource:
return HttpResponseBadRequest("No resource found")
if not resource.startswith("acct:"):
return HttpResponseBadReques... | python | def rfc7033_webfinger_view(request, *args, **kwargs):
"""
Django view to generate an RFC7033 webfinger.
"""
resource = request.GET.get("resource")
if not resource:
return HttpResponseBadRequest("No resource found")
if not resource.startswith("acct:"):
return HttpResponseBadReques... | [
"def",
"rfc7033_webfinger_view",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"resource\"",
")",
"if",
"not",
"resource",
":",
"return",
"HttpResponseBadRequest",
"(",
"\"No... | Django view to generate an RFC7033 webfinger. | [
"Django",
"view",
"to",
"generate",
"an",
"RFC7033",
"webfinger",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/hostmeta/django/generators.py#L22-L56 |
jaywink/federation | federation/utils/diaspora.py | parse_diaspora_webfinger | def parse_diaspora_webfinger(document):
"""
Parse Diaspora webfinger which is either in JSON format (new) or XRD (old).
https://diaspora.github.io/diaspora_federation/discovery/webfinger.html
"""
webfinger = {
"hcard_url": None,
}
try:
doc = json.loads(document)
for ... | python | def parse_diaspora_webfinger(document):
"""
Parse Diaspora webfinger which is either in JSON format (new) or XRD (old).
https://diaspora.github.io/diaspora_federation/discovery/webfinger.html
"""
webfinger = {
"hcard_url": None,
}
try:
doc = json.loads(document)
for ... | [
"def",
"parse_diaspora_webfinger",
"(",
"document",
")",
":",
"webfinger",
"=",
"{",
"\"hcard_url\"",
":",
"None",
",",
"}",
"try",
":",
"doc",
"=",
"json",
".",
"loads",
"(",
"document",
")",
"for",
"link",
"in",
"doc",
"[",
"\"links\"",
"]",
":",
"if... | Parse Diaspora webfinger which is either in JSON format (new) or XRD (old).
https://diaspora.github.io/diaspora_federation/discovery/webfinger.html | [
"Parse",
"Diaspora",
"webfinger",
"which",
"is",
"either",
"in",
"JSON",
"format",
"(",
"new",
")",
"or",
"XRD",
"(",
"old",
")",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L28-L53 |
jaywink/federation | federation/utils/diaspora.py | retrieve_diaspora_hcard | def retrieve_diaspora_hcard(handle):
"""
Retrieve a remote Diaspora hCard document.
:arg handle: Remote handle to retrieve
:return: str (HTML document)
"""
webfinger = retrieve_and_parse_diaspora_webfinger(handle)
document, code, exception = fetch_document(webfinger.get("hcard_url"))
if... | python | def retrieve_diaspora_hcard(handle):
"""
Retrieve a remote Diaspora hCard document.
:arg handle: Remote handle to retrieve
:return: str (HTML document)
"""
webfinger = retrieve_and_parse_diaspora_webfinger(handle)
document, code, exception = fetch_document(webfinger.get("hcard_url"))
if... | [
"def",
"retrieve_diaspora_hcard",
"(",
"handle",
")",
":",
"webfinger",
"=",
"retrieve_and_parse_diaspora_webfinger",
"(",
"handle",
")",
"document",
",",
"code",
",",
"exception",
"=",
"fetch_document",
"(",
"webfinger",
".",
"get",
"(",
"\"hcard_url\"",
")",
")"... | Retrieve a remote Diaspora hCard document.
:arg handle: Remote handle to retrieve
:return: str (HTML document) | [
"Retrieve",
"a",
"remote",
"Diaspora",
"hCard",
"document",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L56-L67 |
jaywink/federation | federation/utils/diaspora.py | retrieve_and_parse_diaspora_webfinger | def retrieve_and_parse_diaspora_webfinger(handle):
"""
Retrieve a and parse a remote Diaspora webfinger document.
:arg handle: Remote handle to retrieve
:returns: dict
"""
try:
host = handle.split("@")[1]
except AttributeError:
logger.warning("retrieve_and_parse_diaspora_web... | python | def retrieve_and_parse_diaspora_webfinger(handle):
"""
Retrieve a and parse a remote Diaspora webfinger document.
:arg handle: Remote handle to retrieve
:returns: dict
"""
try:
host = handle.split("@")[1]
except AttributeError:
logger.warning("retrieve_and_parse_diaspora_web... | [
"def",
"retrieve_and_parse_diaspora_webfinger",
"(",
"handle",
")",
":",
"try",
":",
"host",
"=",
"handle",
".",
"split",
"(",
"\"@\"",
")",
"[",
"1",
"]",
"except",
"AttributeError",
":",
"logger",
".",
"warning",
"(",
"\"retrieve_and_parse_diaspora_webfinger: in... | Retrieve a and parse a remote Diaspora webfinger document.
:arg handle: Remote handle to retrieve
:returns: dict | [
"Retrieve",
"a",
"and",
"parse",
"a",
"remote",
"Diaspora",
"webfinger",
"document",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L70-L94 |
jaywink/federation | federation/utils/diaspora.py | retrieve_diaspora_host_meta | def retrieve_diaspora_host_meta(host):
"""
Retrieve a remote Diaspora host-meta document.
:arg host: Host to retrieve from
:returns: ``XRD`` instance
"""
document, code, exception = fetch_document(host=host, path="/.well-known/host-meta")
if exception:
return None
xrd = XRD.pars... | python | def retrieve_diaspora_host_meta(host):
"""
Retrieve a remote Diaspora host-meta document.
:arg host: Host to retrieve from
:returns: ``XRD`` instance
"""
document, code, exception = fetch_document(host=host, path="/.well-known/host-meta")
if exception:
return None
xrd = XRD.pars... | [
"def",
"retrieve_diaspora_host_meta",
"(",
"host",
")",
":",
"document",
",",
"code",
",",
"exception",
"=",
"fetch_document",
"(",
"host",
"=",
"host",
",",
"path",
"=",
"\"/.well-known/host-meta\"",
")",
"if",
"exception",
":",
"return",
"None",
"xrd",
"=",
... | Retrieve a remote Diaspora host-meta document.
:arg host: Host to retrieve from
:returns: ``XRD`` instance | [
"Retrieve",
"a",
"remote",
"Diaspora",
"host",
"-",
"meta",
"document",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L97-L108 |
jaywink/federation | federation/utils/diaspora.py | _get_element_text_or_none | def _get_element_text_or_none(document, selector):
"""
Using a CSS selector, get the element and return the text, or None if no element.
:arg document: ``HTMLElement`` document
:arg selector: CSS selector
:returns: str or None
"""
element = document.cssselect(selector)
if element:
... | python | def _get_element_text_or_none(document, selector):
"""
Using a CSS selector, get the element and return the text, or None if no element.
:arg document: ``HTMLElement`` document
:arg selector: CSS selector
:returns: str or None
"""
element = document.cssselect(selector)
if element:
... | [
"def",
"_get_element_text_or_none",
"(",
"document",
",",
"selector",
")",
":",
"element",
"=",
"document",
".",
"cssselect",
"(",
"selector",
")",
"if",
"element",
":",
"return",
"element",
"[",
"0",
"]",
".",
"text",
"return",
"None"
] | Using a CSS selector, get the element and return the text, or None if no element.
:arg document: ``HTMLElement`` document
:arg selector: CSS selector
:returns: str or None | [
"Using",
"a",
"CSS",
"selector",
"get",
"the",
"element",
"and",
"return",
"the",
"text",
"or",
"None",
"if",
"no",
"element",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L111-L122 |
jaywink/federation | federation/utils/diaspora.py | _get_element_attr_or_none | def _get_element_attr_or_none(document, selector, attribute):
"""
Using a CSS selector, get the element and return the given attribute value, or None if no element.
Args:
document (HTMLElement) - HTMLElement document
selector (str) - CSS selector
attribute (str) - The attribute to g... | python | def _get_element_attr_or_none(document, selector, attribute):
"""
Using a CSS selector, get the element and return the given attribute value, or None if no element.
Args:
document (HTMLElement) - HTMLElement document
selector (str) - CSS selector
attribute (str) - The attribute to g... | [
"def",
"_get_element_attr_or_none",
"(",
"document",
",",
"selector",
",",
"attribute",
")",
":",
"element",
"=",
"document",
".",
"cssselect",
"(",
"selector",
")",
"if",
"element",
":",
"return",
"element",
"[",
"0",
"]",
".",
"get",
"(",
"attribute",
")... | Using a CSS selector, get the element and return the given attribute value, or None if no element.
Args:
document (HTMLElement) - HTMLElement document
selector (str) - CSS selector
attribute (str) - The attribute to get from the element | [
"Using",
"a",
"CSS",
"selector",
"get",
"the",
"element",
"and",
"return",
"the",
"given",
"attribute",
"value",
"or",
"None",
"if",
"no",
"element",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L125-L137 |
jaywink/federation | federation/utils/diaspora.py | parse_profile_from_hcard | def parse_profile_from_hcard(hcard: str, handle: str):
"""
Parse all the fields we can from a hCard document to get a Profile.
:arg hcard: HTML hcard document (str)
:arg handle: User handle in username@domain.tld format
:returns: ``federation.entities.diaspora.entities.DiasporaProfile`` instance
... | python | def parse_profile_from_hcard(hcard: str, handle: str):
"""
Parse all the fields we can from a hCard document to get a Profile.
:arg hcard: HTML hcard document (str)
:arg handle: User handle in username@domain.tld format
:returns: ``federation.entities.diaspora.entities.DiasporaProfile`` instance
... | [
"def",
"parse_profile_from_hcard",
"(",
"hcard",
":",
"str",
",",
"handle",
":",
"str",
")",
":",
"from",
"federation",
".",
"entities",
".",
"diaspora",
".",
"entities",
"import",
"DiasporaProfile",
"# Circulars",
"doc",
"=",
"html",
".",
"fromstring",
"(",
... | Parse all the fields we can from a hCard document to get a Profile.
:arg hcard: HTML hcard document (str)
:arg handle: User handle in username@domain.tld format
:returns: ``federation.entities.diaspora.entities.DiasporaProfile`` instance | [
"Parse",
"all",
"the",
"fields",
"we",
"can",
"from",
"a",
"hCard",
"document",
"to",
"get",
"a",
"Profile",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L140-L163 |
jaywink/federation | federation/utils/diaspora.py | retrieve_and_parse_content | def retrieve_and_parse_content(
guid: str, handle: str, entity_type: str, sender_key_fetcher: Callable[[str], str]=None,
):
"""Retrieve remote content and return an Entity class instance.
This is basically the inverse of receiving an entity. Instead, we fetch it, then call "handle_receive".
:param... | python | def retrieve_and_parse_content(
guid: str, handle: str, entity_type: str, sender_key_fetcher: Callable[[str], str]=None,
):
"""Retrieve remote content and return an Entity class instance.
This is basically the inverse of receiving an entity. Instead, we fetch it, then call "handle_receive".
:param... | [
"def",
"retrieve_and_parse_content",
"(",
"guid",
":",
"str",
",",
"handle",
":",
"str",
",",
"entity_type",
":",
"str",
",",
"sender_key_fetcher",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"str",
"]",
"=",
"None",
",",
")",
":",
"if",
"not",
"valida... | Retrieve remote content and return an Entity class instance.
This is basically the inverse of receiving an entity. Instead, we fetch it, then call "handle_receive".
:param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used
to fetch the profile and the ke... | [
"Retrieve",
"remote",
"content",
"and",
"return",
"an",
"Entity",
"class",
"instance",
"."
] | train | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L166-L198 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.