repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
horejsek/python-fastjsonschema
fastjsonschema/draft04.py
CodeGeneratorDraft04.generate_one_of
def generate_one_of(self): """ Means that value have to be valid by only one of those definitions. It can't be valid by two or more of them. .. code-block:: python { 'oneOf': [ {'type': 'number', 'multipleOf': 3}, {'type': 'number', 'multipleOf': 5}, ], } Valid values for this definition are 3, 5, 6, ... but not 15 for example. """ self.l('{variable}_one_of_count = 0') for definition_item in self._definition['oneOf']: # When we know it's failing (one of means exactly once), we do not need to do another expensive try-except. with self.l('if {variable}_one_of_count < 2:'): with self.l('try:'): self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True) self.l('{variable}_one_of_count += 1') self.l('except JsonSchemaException: pass') with self.l('if {variable}_one_of_count != 1:'): self.l('raise JsonSchemaException("{name} must be valid exactly by one of oneOf definition")')
python
def generate_one_of(self): """ Means that value have to be valid by only one of those definitions. It can't be valid by two or more of them. .. code-block:: python { 'oneOf': [ {'type': 'number', 'multipleOf': 3}, {'type': 'number', 'multipleOf': 5}, ], } Valid values for this definition are 3, 5, 6, ... but not 15 for example. """ self.l('{variable}_one_of_count = 0') for definition_item in self._definition['oneOf']: # When we know it's failing (one of means exactly once), we do not need to do another expensive try-except. with self.l('if {variable}_one_of_count < 2:'): with self.l('try:'): self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True) self.l('{variable}_one_of_count += 1') self.l('except JsonSchemaException: pass') with self.l('if {variable}_one_of_count != 1:'): self.l('raise JsonSchemaException("{name} must be valid exactly by one of oneOf definition")')
[ "def", "generate_one_of", "(", "self", ")", ":", "self", ".", "l", "(", "'{variable}_one_of_count = 0'", ")", "for", "definition_item", "in", "self", ".", "_definition", "[", "'oneOf'", "]", ":", "# When we know it's failing (one of means exactly once), we do not need to ...
Means that value have to be valid by only one of those definitions. It can't be valid by two or more of them. .. code-block:: python { 'oneOf': [ {'type': 'number', 'multipleOf': 3}, {'type': 'number', 'multipleOf': 5}, ], } Valid values for this definition are 3, 5, 6, ... but not 15 for example.
[ "Means", "that", "value", "have", "to", "be", "valid", "by", "only", "one", "of", "those", "definitions", ".", "It", "can", "t", "be", "valid", "by", "two", "or", "more", "of", "them", "." ]
8c38d0f91fa5d928ff629080cdb75ab23f96590f
https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L151-L177
train
208,900
horejsek/python-fastjsonschema
fastjsonschema/draft04.py
CodeGeneratorDraft04.generate_not
def generate_not(self): """ Means that value have not to be valid by this definition. .. code-block:: python {'not': {'type': 'null'}} Valid values for this definition are 'hello', 42, {} ... but not None. Since draft 06 definition can be boolean. False means nothing, True means everything is invalid. """ not_definition = self._definition['not'] if not_definition is True: self.l('raise JsonSchemaException("{name} must not be there")') elif not_definition is False: return elif not not_definition: with self.l('if {}:', self._variable): self.l('raise JsonSchemaException("{name} must not be valid by not definition")') else: with self.l('try:'): self.generate_func_code_block(not_definition, self._variable, self._variable_name) self.l('except JsonSchemaException: pass') self.l('else: raise JsonSchemaException("{name} must not be valid by not definition")')
python
def generate_not(self): """ Means that value have not to be valid by this definition. .. code-block:: python {'not': {'type': 'null'}} Valid values for this definition are 'hello', 42, {} ... but not None. Since draft 06 definition can be boolean. False means nothing, True means everything is invalid. """ not_definition = self._definition['not'] if not_definition is True: self.l('raise JsonSchemaException("{name} must not be there")') elif not_definition is False: return elif not not_definition: with self.l('if {}:', self._variable): self.l('raise JsonSchemaException("{name} must not be valid by not definition")') else: with self.l('try:'): self.generate_func_code_block(not_definition, self._variable, self._variable_name) self.l('except JsonSchemaException: pass') self.l('else: raise JsonSchemaException("{name} must not be valid by not definition")')
[ "def", "generate_not", "(", "self", ")", ":", "not_definition", "=", "self", ".", "_definition", "[", "'not'", "]", "if", "not_definition", "is", "True", ":", "self", ".", "l", "(", "'raise JsonSchemaException(\"{name} must not be there\")'", ")", "elif", "not_def...
Means that value have not to be valid by this definition. .. code-block:: python {'not': {'type': 'null'}} Valid values for this definition are 'hello', 42, {} ... but not None. Since draft 06 definition can be boolean. False means nothing, True means everything is invalid.
[ "Means", "that", "value", "have", "not", "to", "be", "valid", "by", "this", "definition", "." ]
8c38d0f91fa5d928ff629080cdb75ab23f96590f
https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L179-L204
train
208,901
horejsek/python-fastjsonschema
fastjsonschema/draft04.py
CodeGeneratorDraft04.generate_format
def generate_format(self): """ Means that value have to be in specified format. For example date, email or other. .. code-block:: python {'format': 'email'} Valid value for this definition is user@example.com but not @username """ with self.l('if isinstance({variable}, str):'): format_ = self._definition['format'] if format_ in self.FORMAT_REGEXS: format_regex = self.FORMAT_REGEXS[format_] self._generate_format(format_, format_ + '_re_pattern', format_regex) # format regex is used only in meta schemas elif format_ == 'regex': with self.l('try:'): self.l('re.compile({variable})') with self.l('except Exception:'): self.l('raise JsonSchemaException("{name} must be a valid regex")') else: self.l('pass')
python
def generate_format(self): """ Means that value have to be in specified format. For example date, email or other. .. code-block:: python {'format': 'email'} Valid value for this definition is user@example.com but not @username """ with self.l('if isinstance({variable}, str):'): format_ = self._definition['format'] if format_ in self.FORMAT_REGEXS: format_regex = self.FORMAT_REGEXS[format_] self._generate_format(format_, format_ + '_re_pattern', format_regex) # format regex is used only in meta schemas elif format_ == 'regex': with self.l('try:'): self.l('re.compile({variable})') with self.l('except Exception:'): self.l('raise JsonSchemaException("{name} must be a valid regex")') else: self.l('pass')
[ "def", "generate_format", "(", "self", ")", ":", "with", "self", ".", "l", "(", "'if isinstance({variable}, str):'", ")", ":", "format_", "=", "self", ".", "_definition", "[", "'format'", "]", "if", "format_", "in", "self", ".", "FORMAT_REGEXS", ":", "format...
Means that value have to be in specified format. For example date, email or other. .. code-block:: python {'format': 'email'} Valid value for this definition is user@example.com but not @username
[ "Means", "that", "value", "have", "to", "be", "in", "specified", "format", ".", "For", "example", "date", "email", "or", "other", "." ]
8c38d0f91fa5d928ff629080cdb75ab23f96590f
https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L231-L253
train
208,902
horejsek/python-fastjsonschema
fastjsonschema/draft04.py
CodeGeneratorDraft04.generate_items
def generate_items(self): """ Means array is valid only when all items are valid by this definition. .. code-block:: python { 'items': [ {'type': 'integer'}, {'type': 'string'}, ], } Valid arrays are those with integers or strings, nothing else. Since draft 06 definition can be also boolean. True means nothing, False means everything is invalid. """ items_definition = self._definition['items'] if items_definition is True: return self.create_variable_is_list() with self.l('if {variable}_is_list:'): self.create_variable_with_length() if items_definition is False: with self.l('if {variable}:'): self.l('raise JsonSchemaException("{name} must not be there")') elif isinstance(items_definition, list): for idx, item_definition in enumerate(items_definition): with self.l('if {variable}_len > {}:', idx): self.l('{variable}__{0} = {variable}[{0}]', idx) self.generate_func_code_block( item_definition, '{}__{}'.format(self._variable, idx), '{}[{}]'.format(self._variable_name, idx), ) if isinstance(item_definition, dict) and 'default' in item_definition: self.l('else: {variable}.append({})', repr(item_definition['default'])) if 'additionalItems' in self._definition: if self._definition['additionalItems'] is False: self.l('if {variable}_len > {}: raise JsonSchemaException("{name} must contain only specified items")', len(items_definition)) else: with self.l('for {variable}_x, {variable}_item in enumerate({variable}[{0}:], {0}):', len(items_definition)): self.generate_func_code_block( self._definition['additionalItems'], '{}_item'.format(self._variable), '{}[{{{}_x}}]'.format(self._variable_name, self._variable), ) else: if items_definition: with self.l('for {variable}_x, {variable}_item in enumerate({variable}):'): self.generate_func_code_block( items_definition, '{}_item'.format(self._variable), '{}[{{{}_x}}]'.format(self._variable_name, self._variable), )
python
def generate_items(self): """ Means array is valid only when all items are valid by this definition. .. code-block:: python { 'items': [ {'type': 'integer'}, {'type': 'string'}, ], } Valid arrays are those with integers or strings, nothing else. Since draft 06 definition can be also boolean. True means nothing, False means everything is invalid. """ items_definition = self._definition['items'] if items_definition is True: return self.create_variable_is_list() with self.l('if {variable}_is_list:'): self.create_variable_with_length() if items_definition is False: with self.l('if {variable}:'): self.l('raise JsonSchemaException("{name} must not be there")') elif isinstance(items_definition, list): for idx, item_definition in enumerate(items_definition): with self.l('if {variable}_len > {}:', idx): self.l('{variable}__{0} = {variable}[{0}]', idx) self.generate_func_code_block( item_definition, '{}__{}'.format(self._variable, idx), '{}[{}]'.format(self._variable_name, idx), ) if isinstance(item_definition, dict) and 'default' in item_definition: self.l('else: {variable}.append({})', repr(item_definition['default'])) if 'additionalItems' in self._definition: if self._definition['additionalItems'] is False: self.l('if {variable}_len > {}: raise JsonSchemaException("{name} must contain only specified items")', len(items_definition)) else: with self.l('for {variable}_x, {variable}_item in enumerate({variable}[{0}:], {0}):', len(items_definition)): self.generate_func_code_block( self._definition['additionalItems'], '{}_item'.format(self._variable), '{}[{{{}_x}}]'.format(self._variable_name, self._variable), ) else: if items_definition: with self.l('for {variable}_x, {variable}_item in enumerate({variable}):'): self.generate_func_code_block( items_definition, '{}_item'.format(self._variable), '{}[{{{}_x}}]'.format(self._variable_name, self._variable), )
[ "def", "generate_items", "(", "self", ")", ":", "items_definition", "=", "self", ".", "_definition", "[", "'items'", "]", "if", "items_definition", "is", "True", ":", "return", "self", ".", "create_variable_is_list", "(", ")", "with", "self", ".", "l", "(", ...
Means array is valid only when all items are valid by this definition. .. code-block:: python { 'items': [ {'type': 'integer'}, {'type': 'string'}, ], } Valid arrays are those with integers or strings, nothing else. Since draft 06 definition can be also boolean. True means nothing, False means everything is invalid.
[ "Means", "array", "is", "valid", "only", "when", "all", "items", "are", "valid", "by", "this", "definition", "." ]
8c38d0f91fa5d928ff629080cdb75ab23f96590f
https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L329-L386
train
208,903
horejsek/python-fastjsonschema
fastjsonschema/draft04.py
CodeGeneratorDraft04.generate_properties
def generate_properties(self): """ Means object with defined keys. .. code-block:: python { 'properties': { 'key': {'type': 'number'}, }, } Valid object is containing key called 'key' and value any number. """ self.create_variable_is_dict() with self.l('if {variable}_is_dict:'): self.create_variable_keys() for key, prop_definition in self._definition['properties'].items(): key_name = re.sub(r'($[^a-zA-Z]|[^a-zA-Z0-9])', '', key) with self.l('if "{}" in {variable}_keys:', key): self.l('{variable}_keys.remove("{}")', key) self.l('{variable}__{0} = {variable}["{1}"]', key_name, key) self.generate_func_code_block( prop_definition, '{}__{}'.format(self._variable, key_name), '{}.{}'.format(self._variable_name, key), ) if isinstance(prop_definition, dict) and 'default' in prop_definition: self.l('else: {variable}["{}"] = {}', key, repr(prop_definition['default']))
python
def generate_properties(self): """ Means object with defined keys. .. code-block:: python { 'properties': { 'key': {'type': 'number'}, }, } Valid object is containing key called 'key' and value any number. """ self.create_variable_is_dict() with self.l('if {variable}_is_dict:'): self.create_variable_keys() for key, prop_definition in self._definition['properties'].items(): key_name = re.sub(r'($[^a-zA-Z]|[^a-zA-Z0-9])', '', key) with self.l('if "{}" in {variable}_keys:', key): self.l('{variable}_keys.remove("{}")', key) self.l('{variable}__{0} = {variable}["{1}"]', key_name, key) self.generate_func_code_block( prop_definition, '{}__{}'.format(self._variable, key_name), '{}.{}'.format(self._variable_name, key), ) if isinstance(prop_definition, dict) and 'default' in prop_definition: self.l('else: {variable}["{}"] = {}', key, repr(prop_definition['default']))
[ "def", "generate_properties", "(", "self", ")", ":", "self", ".", "create_variable_is_dict", "(", ")", "with", "self", ".", "l", "(", "'if {variable}_is_dict:'", ")", ":", "self", ".", "create_variable_keys", "(", ")", "for", "key", ",", "prop_definition", "in...
Means object with defined keys. .. code-block:: python { 'properties': { 'key': {'type': 'number'}, }, } Valid object is containing key called 'key' and value any number.
[ "Means", "object", "with", "defined", "keys", "." ]
8c38d0f91fa5d928ff629080cdb75ab23f96590f
https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L415-L443
train
208,904
horejsek/python-fastjsonschema
fastjsonschema/draft04.py
CodeGeneratorDraft04.generate_pattern_properties
def generate_pattern_properties(self): """ Means object with defined keys as patterns. .. code-block:: python { 'patternProperties': { '^x': {'type': 'number'}, }, } Valid object is containing key starting with a 'x' and value any number. """ self.create_variable_is_dict() with self.l('if {variable}_is_dict:'): self.create_variable_keys() for pattern, definition in self._definition['patternProperties'].items(): self._compile_regexps[pattern] = re.compile(pattern) with self.l('for {variable}_key, {variable}_val in {variable}.items():'): for pattern, definition in self._definition['patternProperties'].items(): with self.l('if REGEX_PATTERNS["{}"].search({variable}_key):', pattern): with self.l('if {variable}_key in {variable}_keys:'): self.l('{variable}_keys.remove({variable}_key)') self.generate_func_code_block( definition, '{}_val'.format(self._variable), '{}.{{{}_key}}'.format(self._variable_name, self._variable), )
python
def generate_pattern_properties(self): """ Means object with defined keys as patterns. .. code-block:: python { 'patternProperties': { '^x': {'type': 'number'}, }, } Valid object is containing key starting with a 'x' and value any number. """ self.create_variable_is_dict() with self.l('if {variable}_is_dict:'): self.create_variable_keys() for pattern, definition in self._definition['patternProperties'].items(): self._compile_regexps[pattern] = re.compile(pattern) with self.l('for {variable}_key, {variable}_val in {variable}.items():'): for pattern, definition in self._definition['patternProperties'].items(): with self.l('if REGEX_PATTERNS["{}"].search({variable}_key):', pattern): with self.l('if {variable}_key in {variable}_keys:'): self.l('{variable}_keys.remove({variable}_key)') self.generate_func_code_block( definition, '{}_val'.format(self._variable), '{}.{{{}_key}}'.format(self._variable_name, self._variable), )
[ "def", "generate_pattern_properties", "(", "self", ")", ":", "self", ".", "create_variable_is_dict", "(", ")", "with", "self", ".", "l", "(", "'if {variable}_is_dict:'", ")", ":", "self", ".", "create_variable_keys", "(", ")", "for", "pattern", ",", "definition"...
Means object with defined keys as patterns. .. code-block:: python { 'patternProperties': { '^x': {'type': 'number'}, }, } Valid object is containing key starting with a 'x' and value any number.
[ "Means", "object", "with", "defined", "keys", "as", "patterns", "." ]
8c38d0f91fa5d928ff629080cdb75ab23f96590f
https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L445-L473
train
208,905
horejsek/python-fastjsonschema
fastjsonschema/draft04.py
CodeGeneratorDraft04.generate_additional_properties
def generate_additional_properties(self): """ Means object with keys with values defined by definition. .. code-block:: python { 'properties': { 'key': {'type': 'number'}, } 'additionalProperties': {'type': 'string'}, } Valid object is containing key called 'key' and it's value any number and any other key with any string. """ self.create_variable_is_dict() with self.l('if {variable}_is_dict:'): self.create_variable_keys() add_prop_definition = self._definition["additionalProperties"] if add_prop_definition: properties_keys = list(self._definition.get("properties", {}).keys()) with self.l('for {variable}_key in {variable}_keys:'): with self.l('if {variable}_key not in {}:', properties_keys): self.l('{variable}_value = {variable}.get({variable}_key)') self.generate_func_code_block( add_prop_definition, '{}_value'.format(self._variable), '{}.{{{}_key}}'.format(self._variable_name, self._variable), ) else: with self.l('if {variable}_keys:'): self.l('raise JsonSchemaException("{name} must contain only specified properties")')
python
def generate_additional_properties(self): """ Means object with keys with values defined by definition. .. code-block:: python { 'properties': { 'key': {'type': 'number'}, } 'additionalProperties': {'type': 'string'}, } Valid object is containing key called 'key' and it's value any number and any other key with any string. """ self.create_variable_is_dict() with self.l('if {variable}_is_dict:'): self.create_variable_keys() add_prop_definition = self._definition["additionalProperties"] if add_prop_definition: properties_keys = list(self._definition.get("properties", {}).keys()) with self.l('for {variable}_key in {variable}_keys:'): with self.l('if {variable}_key not in {}:', properties_keys): self.l('{variable}_value = {variable}.get({variable}_key)') self.generate_func_code_block( add_prop_definition, '{}_value'.format(self._variable), '{}.{{{}_key}}'.format(self._variable_name, self._variable), ) else: with self.l('if {variable}_keys:'): self.l('raise JsonSchemaException("{name} must contain only specified properties")')
[ "def", "generate_additional_properties", "(", "self", ")", ":", "self", ".", "create_variable_is_dict", "(", ")", "with", "self", ".", "l", "(", "'if {variable}_is_dict:'", ")", ":", "self", ".", "create_variable_keys", "(", ")", "add_prop_definition", "=", "self"...
Means object with keys with values defined by definition. .. code-block:: python { 'properties': { 'key': {'type': 'number'}, } 'additionalProperties': {'type': 'string'}, } Valid object is containing key called 'key' and it's value any number and any other key with any string.
[ "Means", "object", "with", "keys", "with", "values", "defined", "by", "definition", "." ]
8c38d0f91fa5d928ff629080cdb75ab23f96590f
https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L475-L507
train
208,906
horejsek/python-fastjsonschema
fastjsonschema/draft04.py
CodeGeneratorDraft04.generate_dependencies
def generate_dependencies(self): """ Means when object has property, it needs to have also other property. .. code-block:: python { 'dependencies': { 'bar': ['foo'], }, } Valid object is containing only foo, both bar and foo or none of them, but not object with only bar. Since draft 06 definition can be boolean or empty array. True and empty array means nothing, False means that key cannot be there at all. """ self.create_variable_is_dict() with self.l('if {variable}_is_dict:'): self.create_variable_keys() for key, values in self._definition["dependencies"].items(): if values == [] or values is True: continue with self.l('if "{}" in {variable}_keys:', key): if values is False: self.l('raise JsonSchemaException("{} in {name} must not be there")', key) elif isinstance(values, list): for value in values: with self.l('if "{}" not in {variable}_keys:', value): self.l('raise JsonSchemaException("{name} missing dependency {} for {}")', value, key) else: self.generate_func_code_block(values, self._variable, self._variable_name, clear_variables=True)
python
def generate_dependencies(self): """ Means when object has property, it needs to have also other property. .. code-block:: python { 'dependencies': { 'bar': ['foo'], }, } Valid object is containing only foo, both bar and foo or none of them, but not object with only bar. Since draft 06 definition can be boolean or empty array. True and empty array means nothing, False means that key cannot be there at all. """ self.create_variable_is_dict() with self.l('if {variable}_is_dict:'): self.create_variable_keys() for key, values in self._definition["dependencies"].items(): if values == [] or values is True: continue with self.l('if "{}" in {variable}_keys:', key): if values is False: self.l('raise JsonSchemaException("{} in {name} must not be there")', key) elif isinstance(values, list): for value in values: with self.l('if "{}" not in {variable}_keys:', value): self.l('raise JsonSchemaException("{name} missing dependency {} for {}")', value, key) else: self.generate_func_code_block(values, self._variable, self._variable_name, clear_variables=True)
[ "def", "generate_dependencies", "(", "self", ")", ":", "self", ".", "create_variable_is_dict", "(", ")", "with", "self", ".", "l", "(", "'if {variable}_is_dict:'", ")", ":", "self", ".", "create_variable_keys", "(", ")", "for", "key", ",", "values", "in", "s...
Means when object has property, it needs to have also other property. .. code-block:: python { 'dependencies': { 'bar': ['foo'], }, } Valid object is containing only foo, both bar and foo or none of them, but not object with only bar. Since draft 06 definition can be boolean or empty array. True and empty array means nothing, False means that key cannot be there at all.
[ "Means", "when", "object", "has", "property", "it", "needs", "to", "have", "also", "other", "property", "." ]
8c38d0f91fa5d928ff629080cdb75ab23f96590f
https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L509-L541
train
208,907
developmentseed/landsat-util
landsat/ndvi.py
NDVI._read_cmap
def _read_cmap(self): """ reads the colormap from a text file given in settings.py. See colormap_cubehelix.txt. File must contain 256 RGB values """ try: i = 0 colormap = {0: (0, 0, 0)} with open(settings.COLORMAP) as cmap: lines = cmap.readlines() for line in lines: if i == 0 and 'mode = ' in line: i = 1 maxval = float(line.replace('mode = ', '')) elif i > 0: str = line.split() if str == []: # when there are empty lines at the end of the file break colormap.update( { i: (int(round(float(str[0]) * 255 / maxval)), int(round(float(str[1]) * 255 / maxval)), int(round(float(str[2]) * 255 / maxval))) } ) i += 1 except IOError: pass self.cmap = {k: v[:4] for k, v in colormap.items()}
python
def _read_cmap(self): """ reads the colormap from a text file given in settings.py. See colormap_cubehelix.txt. File must contain 256 RGB values """ try: i = 0 colormap = {0: (0, 0, 0)} with open(settings.COLORMAP) as cmap: lines = cmap.readlines() for line in lines: if i == 0 and 'mode = ' in line: i = 1 maxval = float(line.replace('mode = ', '')) elif i > 0: str = line.split() if str == []: # when there are empty lines at the end of the file break colormap.update( { i: (int(round(float(str[0]) * 255 / maxval)), int(round(float(str[1]) * 255 / maxval)), int(round(float(str[2]) * 255 / maxval))) } ) i += 1 except IOError: pass self.cmap = {k: v[:4] for k, v in colormap.items()}
[ "def", "_read_cmap", "(", "self", ")", ":", "try", ":", "i", "=", "0", "colormap", "=", "{", "0", ":", "(", "0", ",", "0", ",", "0", ")", "}", "with", "open", "(", "settings", ".", "COLORMAP", ")", "as", "cmap", ":", "lines", "=", "cmap", "."...
reads the colormap from a text file given in settings.py. See colormap_cubehelix.txt. File must contain 256 RGB values
[ "reads", "the", "colormap", "from", "a", "text", "file", "given", "in", "settings", ".", "py", ".", "See", "colormap_cubehelix", ".", "txt", ".", "File", "must", "contain", "256", "RGB", "values" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/ndvi.py#L20-L50
train
208,908
developmentseed/landsat-util
landsat/ndvi.py
NDVI.run
def run(self): """ Executes NDVI processing """ self.output("* NDVI processing started.", normal=True) bands = self._read_bands() image_data = self._get_image_data() new_bands = [] for i in range(0, 2): new_bands.append(numpy.empty(image_data['shape'], dtype=numpy.float32)) self._warp(image_data, bands, new_bands) # Bands are no longer needed del bands calc_band = numpy.true_divide((new_bands[1] - new_bands[0]), (new_bands[1] + new_bands[0])) output_band = numpy.rint((calc_band + 1) * 255 / 2).astype(numpy.uint8) output_file = join(self.dst_path, self._filename(suffix='NDVI')) return self.write_band(output_band, output_file, image_data)
python
def run(self): """ Executes NDVI processing """ self.output("* NDVI processing started.", normal=True) bands = self._read_bands() image_data = self._get_image_data() new_bands = [] for i in range(0, 2): new_bands.append(numpy.empty(image_data['shape'], dtype=numpy.float32)) self._warp(image_data, bands, new_bands) # Bands are no longer needed del bands calc_band = numpy.true_divide((new_bands[1] - new_bands[0]), (new_bands[1] + new_bands[0])) output_band = numpy.rint((calc_band + 1) * 255 / 2).astype(numpy.uint8) output_file = join(self.dst_path, self._filename(suffix='NDVI')) return self.write_band(output_band, output_file, image_data)
[ "def", "run", "(", "self", ")", ":", "self", ".", "output", "(", "\"* NDVI processing started.\"", ",", "normal", "=", "True", ")", "bands", "=", "self", ".", "_read_bands", "(", ")", "image_data", "=", "self", ".", "_get_image_data", "(", ")", "new_bands"...
Executes NDVI processing
[ "Executes", "NDVI", "processing" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/ndvi.py#L53-L77
train
208,909
developmentseed/landsat-util
landsat/uploader.py
data_collector
def data_collector(iterable, def_buf_size=5242880): """ Buffers n bytes of data. :param iterable: Could be a list, generator or string :type iterable: List, generator, String :returns: A generator object """ buf = b'' for data in iterable: buf += data if len(buf) >= def_buf_size: output = buf[:def_buf_size] buf = buf[def_buf_size:] yield output if len(buf) > 0: yield buf
python
def data_collector(iterable, def_buf_size=5242880): """ Buffers n bytes of data. :param iterable: Could be a list, generator or string :type iterable: List, generator, String :returns: A generator object """ buf = b'' for data in iterable: buf += data if len(buf) >= def_buf_size: output = buf[:def_buf_size] buf = buf[def_buf_size:] yield output if len(buf) > 0: yield buf
[ "def", "data_collector", "(", "iterable", ",", "def_buf_size", "=", "5242880", ")", ":", "buf", "=", "b''", "for", "data", "in", "iterable", ":", "buf", "+=", "data", "if", "len", "(", "buf", ")", ">=", "def_buf_size", ":", "output", "=", "buf", "[", ...
Buffers n bytes of data. :param iterable: Could be a list, generator or string :type iterable: List, generator, String :returns: A generator object
[ "Buffers", "n", "bytes", "of", "data", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/uploader.py#L115-L134
train
208,910
developmentseed/landsat-util
landsat/uploader.py
upload
def upload(bucket, aws_access_key, aws_secret_key, iterable, key, progress_cb=None, threads=5, replace=False, secure=True, connection=None): """ Upload data to s3 using the s3 multipart upload API. :param bucket: Name of the S3 bucket :type bucket: String :param aws_access_key: AWS access key id (optional) :type aws_access_key: String :param aws_secret_key: AWS access secret key (optional) :type aws_secret_key: String :param iterable: The data to upload. Each 'part' in the list. will be uploaded in parallel. Each part must be at least 5242880 bytes (5mb). :type iterable: An iterable object :param key: The name of the key (filename) to create in the s3 bucket :type key: String :param progress_cb: Progress callback, will be called with (part_no, uploaded, total) each time a progress update is available. (optional) :type progress_cb: function :param threads: the number of threads to use while uploading. (Default is 5) :type threads: int :param replace: will replace the key (filename) on S3 if set to true. (Default is false) :type replace: boolean :param secure: Use ssl when talking to s3. (Default is true) :type secure: boolean :param connection: Used for testing (optional) :type connection: S3 connection class :returns: void """ if not connection: from boto.s3.connection import S3Connection as connection c = connection(aws_access_key, aws_secret_key, is_secure=secure) else: c = connection b = c.get_bucket(bucket) if not replace and b.lookup(key): raise Exception('s3 key ' + key + ' already exists') multipart_obj = b.initiate_multipart_upload(key) err_queue = queue.Queue() lock = threading.Lock() upload.counter = 0 try: tpool = pool.ThreadPool(processes=threads) def check_errors(): try: exc = err_queue.get(block=False) except queue.Empty: pass else: raise exc def waiter(): while upload.counter >= threads: check_errors() time.sleep(0.1) def cb(err): if err: err_queue.put(err) with lock: upload.counter -= 1 args = [multipart_obj.upload_part_from_file, progress_cb] for part_no, part in enumerate(iterable): part_no += 1 tpool.apply_async(upload_part, args + [part_no, part], callback=cb) with lock: upload.counter += 1 waiter() tpool.close() tpool.join() # Check for thread errors before completing the upload, # sometimes an error can be left unchecked until we # get to this point. check_errors() multipart_obj.complete_upload() except: multipart_obj.cancel_upload() tpool.terminate() raise
python
def upload(bucket, aws_access_key, aws_secret_key, iterable, key, progress_cb=None, threads=5, replace=False, secure=True, connection=None): """ Upload data to s3 using the s3 multipart upload API. :param bucket: Name of the S3 bucket :type bucket: String :param aws_access_key: AWS access key id (optional) :type aws_access_key: String :param aws_secret_key: AWS access secret key (optional) :type aws_secret_key: String :param iterable: The data to upload. Each 'part' in the list. will be uploaded in parallel. Each part must be at least 5242880 bytes (5mb). :type iterable: An iterable object :param key: The name of the key (filename) to create in the s3 bucket :type key: String :param progress_cb: Progress callback, will be called with (part_no, uploaded, total) each time a progress update is available. (optional) :type progress_cb: function :param threads: the number of threads to use while uploading. (Default is 5) :type threads: int :param replace: will replace the key (filename) on S3 if set to true. (Default is false) :type replace: boolean :param secure: Use ssl when talking to s3. (Default is true) :type secure: boolean :param connection: Used for testing (optional) :type connection: S3 connection class :returns: void """ if not connection: from boto.s3.connection import S3Connection as connection c = connection(aws_access_key, aws_secret_key, is_secure=secure) else: c = connection b = c.get_bucket(bucket) if not replace and b.lookup(key): raise Exception('s3 key ' + key + ' already exists') multipart_obj = b.initiate_multipart_upload(key) err_queue = queue.Queue() lock = threading.Lock() upload.counter = 0 try: tpool = pool.ThreadPool(processes=threads) def check_errors(): try: exc = err_queue.get(block=False) except queue.Empty: pass else: raise exc def waiter(): while upload.counter >= threads: check_errors() time.sleep(0.1) def cb(err): if err: err_queue.put(err) with lock: upload.counter -= 1 args = [multipart_obj.upload_part_from_file, progress_cb] for part_no, part in enumerate(iterable): part_no += 1 tpool.apply_async(upload_part, args + [part_no, part], callback=cb) with lock: upload.counter += 1 waiter() tpool.close() tpool.join() # Check for thread errors before completing the upload, # sometimes an error can be left unchecked until we # get to this point. check_errors() multipart_obj.complete_upload() except: multipart_obj.cancel_upload() tpool.terminate() raise
[ "def", "upload", "(", "bucket", ",", "aws_access_key", ",", "aws_secret_key", ",", "iterable", ",", "key", ",", "progress_cb", "=", "None", ",", "threads", "=", "5", ",", "replace", "=", "False", ",", "secure", "=", "True", ",", "connection", "=", "None"...
Upload data to s3 using the s3 multipart upload API. :param bucket: Name of the S3 bucket :type bucket: String :param aws_access_key: AWS access key id (optional) :type aws_access_key: String :param aws_secret_key: AWS access secret key (optional) :type aws_secret_key: String :param iterable: The data to upload. Each 'part' in the list. will be uploaded in parallel. Each part must be at least 5242880 bytes (5mb). :type iterable: An iterable object :param key: The name of the key (filename) to create in the s3 bucket :type key: String :param progress_cb: Progress callback, will be called with (part_no, uploaded, total) each time a progress update is available. (optional) :type progress_cb: function :param threads: the number of threads to use while uploading. (Default is 5) :type threads: int :param replace: will replace the key (filename) on S3 if set to true. (Default is false) :type replace: boolean :param secure: Use ssl when talking to s3. (Default is true) :type secure: boolean :param connection: Used for testing (optional) :type connection: S3 connection class :returns: void
[ "Upload", "data", "to", "s3", "using", "the", "s3", "multipart", "upload", "API", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/uploader.py#L155-L265
train
208,911
developmentseed/landsat-util
landsat/uploader.py
Uploader.run
def run(self, bucket_name, filename, path): """ Initiate the upload. :param bucket_name: Name of the S3 bucket :type bucket_name: String :param filename: The filname :type filename: String :param path: The path to the file that needs to be uploaded :type path: String :returns: void """ f = open(path, 'rb') self.source_size = os.stat(path).st_size total_dict = {} def cb(part_no, uploaded, total): total_dict[part_no] = uploaded params = { 'uploaded': round(sum(total_dict.values()) / 1048576, 0), 'size': round(self.source_size / 1048576, 0), } p = (self.progress_template + '\r') % params STREAM.write(p) STREAM.flush() self.output('Uploading to S3', normal=True, arrow=True) upload(bucket_name, self.key, self.secret, data_collector(iter(f)), filename, cb, threads=10, replace=True, secure=True, connection=self.conn) print('\n') self.output('Upload Completed', normal=True, arrow=True)
python
def run(self, bucket_name, filename, path): """ Initiate the upload. :param bucket_name: Name of the S3 bucket :type bucket_name: String :param filename: The filname :type filename: String :param path: The path to the file that needs to be uploaded :type path: String :returns: void """ f = open(path, 'rb') self.source_size = os.stat(path).st_size total_dict = {} def cb(part_no, uploaded, total): total_dict[part_no] = uploaded params = { 'uploaded': round(sum(total_dict.values()) / 1048576, 0), 'size': round(self.source_size / 1048576, 0), } p = (self.progress_template + '\r') % params STREAM.write(p) STREAM.flush() self.output('Uploading to S3', normal=True, arrow=True) upload(bucket_name, self.key, self.secret, data_collector(iter(f)), filename, cb, threads=10, replace=True, secure=True, connection=self.conn) print('\n') self.output('Upload Completed', normal=True, arrow=True)
[ "def", "run", "(", "self", ",", "bucket_name", ",", "filename", ",", "path", ")", ":", "f", "=", "open", "(", "path", ",", "'rb'", ")", "self", ".", "source_size", "=", "os", ".", "stat", "(", "path", ")", ".", "st_size", "total_dict", "=", "{", ...
Initiate the upload. :param bucket_name: Name of the S3 bucket :type bucket_name: String :param filename: The filname :type filename: String :param path: The path to the file that needs to be uploaded :type path: String :returns: void
[ "Initiate", "the", "upload", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/uploader.py#L67-L112
train
208,912
developmentseed/landsat-util
landsat/downloader.py
Downloader.download
def download(self, scenes, bands=None): """ Download scenese from Google Storage or Amazon S3 if bands are provided :param scenes: A list of scene IDs :type scenes: List :param bands: A list of bands. Default value is None. :type scenes: List :returns: (List) includes downloaded scenes as key and source as value (aws or google) """ if isinstance(scenes, list): files = [] for scene in scenes: # for all scenes if bands provided, first check AWS, if the bands exist # download them, otherwise use Google and then USGS. try: # if bands are not provided, directly go to Goodle and then USGS if not isinstance(bands, list): raise RemoteFileDoesntExist files.append(self.amazon_s3(scene, bands)) except RemoteFileDoesntExist: try: files.append(self.google_storage(scene, self.download_dir)) except RemoteFileDoesntExist: files.append(self.usgs_eros(scene, self.download_dir)) return files else: raise Exception('Expected sceneIDs list')
python
def download(self, scenes, bands=None): """ Download scenese from Google Storage or Amazon S3 if bands are provided :param scenes: A list of scene IDs :type scenes: List :param bands: A list of bands. Default value is None. :type scenes: List :returns: (List) includes downloaded scenes as key and source as value (aws or google) """ if isinstance(scenes, list): files = [] for scene in scenes: # for all scenes if bands provided, first check AWS, if the bands exist # download them, otherwise use Google and then USGS. try: # if bands are not provided, directly go to Goodle and then USGS if not isinstance(bands, list): raise RemoteFileDoesntExist files.append(self.amazon_s3(scene, bands)) except RemoteFileDoesntExist: try: files.append(self.google_storage(scene, self.download_dir)) except RemoteFileDoesntExist: files.append(self.usgs_eros(scene, self.download_dir)) return files else: raise Exception('Expected sceneIDs list')
[ "def", "download", "(", "self", ",", "scenes", ",", "bands", "=", "None", ")", ":", "if", "isinstance", "(", "scenes", ",", "list", ")", ":", "files", "=", "[", "]", "for", "scene", "in", "scenes", ":", "# for all scenes if bands provided, first check AWS, i...
Download scenese from Google Storage or Amazon S3 if bands are provided :param scenes: A list of scene IDs :type scenes: List :param bands: A list of bands. Default value is None. :type scenes: List :returns: (List) includes downloaded scenes as key and source as value (aws or google)
[ "Download", "scenese", "from", "Google", "Storage", "or", "Amazon", "S3", "if", "bands", "are", "provided" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/downloader.py#L46-L85
train
208,913
developmentseed/landsat-util
landsat/downloader.py
Downloader.usgs_eros
def usgs_eros(self, scene, path): """ Downloads the image from USGS """ # download from usgs if login information is provided if self.usgs_user and self.usgs_pass: try: api_key = api.login(self.usgs_user, self.usgs_pass) except USGSError as e: error_tree = ElementTree.fromstring(str(e.message)) error_text = error_tree.find("SOAP-ENV:Body/SOAP-ENV:Fault/faultstring", api.NAMESPACES).text raise USGSInventoryAccessMissing(error_text) download_url = api.download('LANDSAT_8', 'EE', [scene], api_key=api_key) if download_url: self.output('Source: USGS EarthExplorer', normal=True, arrow=True) return self.fetch(download_url[0], path) raise RemoteFileDoesntExist('%s is not available on AWS S3, Google or USGS Earth Explorer' % scene) raise RemoteFileDoesntExist('%s is not available on AWS S3 or Google Storage' % scene)
python
def usgs_eros(self, scene, path): """ Downloads the image from USGS """ # download from usgs if login information is provided if self.usgs_user and self.usgs_pass: try: api_key = api.login(self.usgs_user, self.usgs_pass) except USGSError as e: error_tree = ElementTree.fromstring(str(e.message)) error_text = error_tree.find("SOAP-ENV:Body/SOAP-ENV:Fault/faultstring", api.NAMESPACES).text raise USGSInventoryAccessMissing(error_text) download_url = api.download('LANDSAT_8', 'EE', [scene], api_key=api_key) if download_url: self.output('Source: USGS EarthExplorer', normal=True, arrow=True) return self.fetch(download_url[0], path) raise RemoteFileDoesntExist('%s is not available on AWS S3, Google or USGS Earth Explorer' % scene) raise RemoteFileDoesntExist('%s is not available on AWS S3 or Google Storage' % scene)
[ "def", "usgs_eros", "(", "self", ",", "scene", ",", "path", ")", ":", "# download from usgs if login information is provided", "if", "self", ".", "usgs_user", "and", "self", ".", "usgs_pass", ":", "try", ":", "api_key", "=", "api", ".", "login", "(", "self", ...
Downloads the image from USGS
[ "Downloads", "the", "image", "from", "USGS" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/downloader.py#L87-L105
train
208,914
developmentseed/landsat-util
landsat/downloader.py
Downloader.google_storage
def google_storage(self, scene, path): """ Google Storage Downloader. :param scene: The scene id :type scene: String :param path: The directory path to where the image should be stored :type path: String :returns: Boolean """ sat = self.scene_interpreter(scene) url = self.google_storage_url(sat) self.remote_file_exists(url) self.output('Source: Google Storage', normal=True, arrow=True) return self.fetch(url, path)
python
def google_storage(self, scene, path): """ Google Storage Downloader. :param scene: The scene id :type scene: String :param path: The directory path to where the image should be stored :type path: String :returns: Boolean """ sat = self.scene_interpreter(scene) url = self.google_storage_url(sat) self.remote_file_exists(url) self.output('Source: Google Storage', normal=True, arrow=True) return self.fetch(url, path)
[ "def", "google_storage", "(", "self", ",", "scene", ",", "path", ")", ":", "sat", "=", "self", ".", "scene_interpreter", "(", "scene", ")", "url", "=", "self", ".", "google_storage_url", "(", "sat", ")", "self", ".", "remote_file_exists", "(", "url", ")"...
Google Storage Downloader. :param scene: The scene id :type scene: String :param path: The directory path to where the image should be stored :type path: String :returns: Boolean
[ "Google", "Storage", "Downloader", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/downloader.py#L107-L130
train
208,915
developmentseed/landsat-util
landsat/downloader.py
Downloader.amazon_s3
def amazon_s3(self, scene, bands): """ Amazon S3 downloader """ sat = self.scene_interpreter(scene) # Always grab MTL.txt and QA band if bands are specified if 'BQA' not in bands: bands.append('QA') if 'MTL' not in bands: bands.append('MTL') urls = [] for band in bands: # get url for the band url = self.amazon_s3_url(sat, band) # make sure it exist self.remote_file_exists(url) urls.append(url) # create folder path = check_create_folder(join(self.download_dir, scene)) self.output('Source: AWS S3', normal=True, arrow=True) for url in urls: self.fetch(url, path) return path
python
def amazon_s3(self, scene, bands): """ Amazon S3 downloader """ sat = self.scene_interpreter(scene) # Always grab MTL.txt and QA band if bands are specified if 'BQA' not in bands: bands.append('QA') if 'MTL' not in bands: bands.append('MTL') urls = [] for band in bands: # get url for the band url = self.amazon_s3_url(sat, band) # make sure it exist self.remote_file_exists(url) urls.append(url) # create folder path = check_create_folder(join(self.download_dir, scene)) self.output('Source: AWS S3', normal=True, arrow=True) for url in urls: self.fetch(url, path) return path
[ "def", "amazon_s3", "(", "self", ",", "scene", ",", "bands", ")", ":", "sat", "=", "self", ".", "scene_interpreter", "(", "scene", ")", "# Always grab MTL.txt and QA band if bands are specified", "if", "'BQA'", "not", "in", "bands", ":", "bands", ".", "append", ...
Amazon S3 downloader
[ "Amazon", "S3", "downloader" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/downloader.py#L132-L163
train
208,916
developmentseed/landsat-util
landsat/downloader.py
Downloader.fetch
def fetch(self, url, path): """ Downloads the given url. :param url: The url to be downloaded. :type url: String :param path: The directory path to where the image should be stored :type path: String :param filename: The filename that has to be downloaded :type filename: String :returns: Boolean """ segments = url.split('/') filename = segments[-1] # remove query parameters from the filename filename = filename.split('?')[0] self.output('Downloading: %s' % filename, normal=True, arrow=True) # print(join(path, filename)) # raise Exception if exists(join(path, filename)): size = getsize(join(path, filename)) if size == self.get_remote_file_size(url): self.output('%s already exists on your system' % filename, normal=True, color='green', indent=1) else: fetch(url, path) self.output('stored at %s' % path, normal=True, color='green', indent=1) return join(path, filename)
python
def fetch(self, url, path): """ Downloads the given url. :param url: The url to be downloaded. :type url: String :param path: The directory path to where the image should be stored :type path: String :param filename: The filename that has to be downloaded :type filename: String :returns: Boolean """ segments = url.split('/') filename = segments[-1] # remove query parameters from the filename filename = filename.split('?')[0] self.output('Downloading: %s' % filename, normal=True, arrow=True) # print(join(path, filename)) # raise Exception if exists(join(path, filename)): size = getsize(join(path, filename)) if size == self.get_remote_file_size(url): self.output('%s already exists on your system' % filename, normal=True, color='green', indent=1) else: fetch(url, path) self.output('stored at %s' % path, normal=True, color='green', indent=1) return join(path, filename)
[ "def", "fetch", "(", "self", ",", "url", ",", "path", ")", ":", "segments", "=", "url", ".", "split", "(", "'/'", ")", "filename", "=", "segments", "[", "-", "1", "]", "# remove query parameters from the filename", "filename", "=", "filename", ".", "split"...
Downloads the given url. :param url: The url to be downloaded. :type url: String :param path: The directory path to where the image should be stored :type path: String :param filename: The filename that has to be downloaded :type filename: String :returns: Boolean
[ "Downloads", "the", "given", "url", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/downloader.py#L165-L204
train
208,917
developmentseed/landsat-util
landsat/downloader.py
Downloader.google_storage_url
def google_storage_url(self, sat): """ Returns a google storage url the contains the scene provided. :param sat: Expects an object created by scene_interpreter method :type sat: dict :returns: (String) The URL to a google storage file """ filename = sat['scene'] + '.tar.bz' return url_builder([self.google, sat['sat'], sat['path'], sat['row'], filename])
python
def google_storage_url(self, sat): """ Returns a google storage url the contains the scene provided. :param sat: Expects an object created by scene_interpreter method :type sat: dict :returns: (String) The URL to a google storage file """ filename = sat['scene'] + '.tar.bz' return url_builder([self.google, sat['sat'], sat['path'], sat['row'], filename])
[ "def", "google_storage_url", "(", "self", ",", "sat", ")", ":", "filename", "=", "sat", "[", "'scene'", "]", "+", "'.tar.bz'", "return", "url_builder", "(", "[", "self", ".", "google", ",", "sat", "[", "'sat'", "]", ",", "sat", "[", "'path'", "]", ",...
Returns a google storage url the contains the scene provided. :param sat: Expects an object created by scene_interpreter method :type sat: dict :returns: (String) The URL to a google storage file
[ "Returns", "a", "google", "storage", "url", "the", "contains", "the", "scene", "provided", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/downloader.py#L206-L219
train
208,918
developmentseed/landsat-util
landsat/downloader.py
Downloader.amazon_s3_url
def amazon_s3_url(self, sat, band): """ Return an amazon s3 url the contains the scene and band provided. :param sat: Expects an object created by scene_interpreter method :type sat: dict :param filename: The filename that has to be downloaded from Amazon :type filename: String :returns: (String) The URL to a S3 file """ if band != 'MTL': filename = '%s_B%s.TIF' % (sat['scene'], band) else: filename = '%s_%s.txt' % (sat['scene'], band) return url_builder([self.s3, sat['sat'], sat['path'], sat['row'], sat['scene'], filename])
python
def amazon_s3_url(self, sat, band): """ Return an amazon s3 url the contains the scene and band provided. :param sat: Expects an object created by scene_interpreter method :type sat: dict :param filename: The filename that has to be downloaded from Amazon :type filename: String :returns: (String) The URL to a S3 file """ if band != 'MTL': filename = '%s_B%s.TIF' % (sat['scene'], band) else: filename = '%s_%s.txt' % (sat['scene'], band) return url_builder([self.s3, sat['sat'], sat['path'], sat['row'], sat['scene'], filename])
[ "def", "amazon_s3_url", "(", "self", ",", "sat", ",", "band", ")", ":", "if", "band", "!=", "'MTL'", ":", "filename", "=", "'%s_B%s.TIF'", "%", "(", "sat", "[", "'scene'", "]", ",", "band", ")", "else", ":", "filename", "=", "'%s_%s.txt'", "%", "(", ...
Return an amazon s3 url the contains the scene and band provided. :param sat: Expects an object created by scene_interpreter method :type sat: dict :param filename: The filename that has to be downloaded from Amazon :type filename: String :returns: (String) The URL to a S3 file
[ "Return", "an", "amazon", "s3", "url", "the", "contains", "the", "scene", "and", "band", "provided", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/downloader.py#L221-L242
train
208,919
developmentseed/landsat-util
landsat/downloader.py
Downloader.remote_file_exists
def remote_file_exists(self, url): """ Checks whether the remote file exists. :param url: The url that has to be checked. :type url: String :returns: **True** if remote file exists and **False** if it doesn't exist. """ status = requests.head(url).status_code if status != 200: raise RemoteFileDoesntExist
python
def remote_file_exists(self, url): """ Checks whether the remote file exists. :param url: The url that has to be checked. :type url: String :returns: **True** if remote file exists and **False** if it doesn't exist. """ status = requests.head(url).status_code if status != 200: raise RemoteFileDoesntExist
[ "def", "remote_file_exists", "(", "self", ",", "url", ")", ":", "status", "=", "requests", ".", "head", "(", "url", ")", ".", "status_code", "if", "status", "!=", "200", ":", "raise", "RemoteFileDoesntExist" ]
Checks whether the remote file exists. :param url: The url that has to be checked. :type url: String :returns: **True** if remote file exists and **False** if it doesn't exist.
[ "Checks", "whether", "the", "remote", "file", "exists", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/downloader.py#L244-L258
train
208,920
developmentseed/landsat-util
landsat/downloader.py
Downloader.get_remote_file_size
def get_remote_file_size(self, url): """ Gets the filesize of a remote file. :param url: The url that has to be checked. :type url: String :returns: int """ headers = requests.head(url).headers return int(headers['content-length'])
python
def get_remote_file_size(self, url): """ Gets the filesize of a remote file. :param url: The url that has to be checked. :type url: String :returns: int """ headers = requests.head(url).headers return int(headers['content-length'])
[ "def", "get_remote_file_size", "(", "self", ",", "url", ")", ":", "headers", "=", "requests", ".", "head", "(", "url", ")", ".", "headers", "return", "int", "(", "headers", "[", "'content-length'", "]", ")" ]
Gets the filesize of a remote file. :param url: The url that has to be checked. :type url: String :returns: int
[ "Gets", "the", "filesize", "of", "a", "remote", "file", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/downloader.py#L260-L272
train
208,921
developmentseed/landsat-util
landsat/downloader.py
Downloader.scene_interpreter
def scene_interpreter(self, scene): """ Conver sceneID to rows, paths and dates. :param scene: The scene ID. :type scene: String :returns: dict :Example output: >>> anatomy = { 'path': None, 'row': None, 'sat': None, 'scene': scene } """ anatomy = { 'path': None, 'row': None, 'sat': None, 'scene': scene } if isinstance(scene, str) and len(scene) == 21: anatomy['path'] = scene[3:6] anatomy['row'] = scene[6:9] anatomy['sat'] = 'L' + scene[2:3] return anatomy else: raise IncorrectSceneId('Received incorrect scene')
python
def scene_interpreter(self, scene): """ Conver sceneID to rows, paths and dates. :param scene: The scene ID. :type scene: String :returns: dict :Example output: >>> anatomy = { 'path': None, 'row': None, 'sat': None, 'scene': scene } """ anatomy = { 'path': None, 'row': None, 'sat': None, 'scene': scene } if isinstance(scene, str) and len(scene) == 21: anatomy['path'] = scene[3:6] anatomy['row'] = scene[6:9] anatomy['sat'] = 'L' + scene[2:3] return anatomy else: raise IncorrectSceneId('Received incorrect scene')
[ "def", "scene_interpreter", "(", "self", ",", "scene", ")", ":", "anatomy", "=", "{", "'path'", ":", "None", ",", "'row'", ":", "None", ",", "'sat'", ":", "None", ",", "'scene'", ":", "scene", "}", "if", "isinstance", "(", "scene", ",", "str", ")", ...
Conver sceneID to rows, paths and dates. :param scene: The scene ID. :type scene: String :returns: dict :Example output: >>> anatomy = { 'path': None, 'row': None, 'sat': None, 'scene': scene }
[ "Conver", "sceneID", "to", "rows", "paths", "and", "dates", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/downloader.py#L274-L307
train
208,922
developmentseed/landsat-util
landsat/search.py
Search.search
def search(self, paths_rows=None, lat=None, lon=None, address=None, start_date=None, end_date=None, cloud_min=None, cloud_max=None, limit=1, geojson=False): """ The main method of Search class. It searches Development Seed's Landsat API. :param paths_rows: A string in this format: "003,003,004,004". Must be in pairs and separated by comma. :type paths_rows: String :param lat: The latitude :type lat: String, float, integer :param lon: The The longitude :type lon: String, float, integer :param address: The address :type address: String :param start_date: Date string. format: YYYY-MM-DD :type start_date: String :param end_date: date string. format: YYYY-MM-DD :type end_date: String :param cloud_min: float specifying the minimum percentage. e.g. 4.3 :type cloud_min: float :param cloud_max: float specifying the maximum percentage. e.g. 78.9 :type cloud_max: float :param limit: integer specigying the maximum results return. :type limit: integer :param geojson: boolean specifying whether to return a geojson object :type geojson: boolean :returns: dict :example: >>> search = Search() >>> search('003,003', '2014-01-01', '2014-06-01') >>> { 'status': u'SUCCESS', 'total_returned': 1, 'total': 1, 'limit': 1 'results': [ { 'sat_type': u'L8', 'sceneID': u'LC80030032014142LGN00', 'date': u'2014-05-22', 'path': u'003', 'thumbnail': u'http://....../landsat_8/2014/003/003/LC80030032014142LGN00.jpg', 'cloud': 33.36, 'row': u'003 } ] } """ search_string = self.query_builder(paths_rows, lat, lon, address, start_date, end_date, cloud_min, cloud_max) # Have to manually build the URI to bypass requests URI encoding # The api server doesn't accept encoded URIs r = requests.get('%s?search=%s&limit=%s' % (self.api_url, search_string, limit)) r_dict = json.loads(r.text) result = {} if 'error' in r_dict: result['status'] = u'error' result['code'] = r_dict['error']['code'] result['message'] = r_dict['error']['message'] elif 'meta' in r_dict: if geojson: result = { 'type': 'FeatureCollection', 'features': [] } for r in r_dict['results']: feature = { 'type': 'Feature', 'properties': { 'sceneID': r['sceneID'], 'row': three_digit(r['row']), 'path': three_digit(r['path']), 'thumbnail': r['browseURL'], 'date': r['acquisitionDate'], 'cloud': r['cloud_coverage'] }, 'geometry': { 'type': 'Polygon', 'coordinates': [ [ [r['upperLeftCornerLongitude'], r['upperLeftCornerLatitude']], [r['lowerLeftCornerLongitude'], r['lowerLeftCornerLatitude']], [r['lowerRightCornerLongitude'], r['lowerRightCornerLatitude']], [r['upperRightCornerLongitude'], r['upperRightCornerLatitude']], [r['upperLeftCornerLongitude'], r['upperLeftCornerLatitude']] ] ] } } result['features'].append(feature) else: result['status'] = u'SUCCESS' result['total'] = r_dict['meta']['found'] result['limit'] = r_dict['meta']['limit'] result['total_returned'] = len(r_dict['results']) result['results'] = [{'sceneID': i['sceneID'], 'sat_type': u'L8', 'path': three_digit(i['path']), 'row': three_digit(i['row']), 'thumbnail': i['browseURL'], 'date': i['acquisitionDate'], 'cloud': i['cloud_coverage']} for i in r_dict['results']] return result
python
def search(self, paths_rows=None, lat=None, lon=None, address=None, start_date=None, end_date=None, cloud_min=None, cloud_max=None, limit=1, geojson=False): """ The main method of Search class. It searches Development Seed's Landsat API. :param paths_rows: A string in this format: "003,003,004,004". Must be in pairs and separated by comma. :type paths_rows: String :param lat: The latitude :type lat: String, float, integer :param lon: The The longitude :type lon: String, float, integer :param address: The address :type address: String :param start_date: Date string. format: YYYY-MM-DD :type start_date: String :param end_date: date string. format: YYYY-MM-DD :type end_date: String :param cloud_min: float specifying the minimum percentage. e.g. 4.3 :type cloud_min: float :param cloud_max: float specifying the maximum percentage. e.g. 78.9 :type cloud_max: float :param limit: integer specigying the maximum results return. :type limit: integer :param geojson: boolean specifying whether to return a geojson object :type geojson: boolean :returns: dict :example: >>> search = Search() >>> search('003,003', '2014-01-01', '2014-06-01') >>> { 'status': u'SUCCESS', 'total_returned': 1, 'total': 1, 'limit': 1 'results': [ { 'sat_type': u'L8', 'sceneID': u'LC80030032014142LGN00', 'date': u'2014-05-22', 'path': u'003', 'thumbnail': u'http://....../landsat_8/2014/003/003/LC80030032014142LGN00.jpg', 'cloud': 33.36, 'row': u'003 } ] } """ search_string = self.query_builder(paths_rows, lat, lon, address, start_date, end_date, cloud_min, cloud_max) # Have to manually build the URI to bypass requests URI encoding # The api server doesn't accept encoded URIs r = requests.get('%s?search=%s&limit=%s' % (self.api_url, search_string, limit)) r_dict = json.loads(r.text) result = {} if 'error' in r_dict: result['status'] = u'error' result['code'] = r_dict['error']['code'] result['message'] = r_dict['error']['message'] elif 'meta' in r_dict: if geojson: result = { 'type': 'FeatureCollection', 'features': [] } for r in r_dict['results']: feature = { 'type': 'Feature', 'properties': { 'sceneID': r['sceneID'], 'row': three_digit(r['row']), 'path': three_digit(r['path']), 'thumbnail': r['browseURL'], 'date': r['acquisitionDate'], 'cloud': r['cloud_coverage'] }, 'geometry': { 'type': 'Polygon', 'coordinates': [ [ [r['upperLeftCornerLongitude'], r['upperLeftCornerLatitude']], [r['lowerLeftCornerLongitude'], r['lowerLeftCornerLatitude']], [r['lowerRightCornerLongitude'], r['lowerRightCornerLatitude']], [r['upperRightCornerLongitude'], r['upperRightCornerLatitude']], [r['upperLeftCornerLongitude'], r['upperLeftCornerLatitude']] ] ] } } result['features'].append(feature) else: result['status'] = u'SUCCESS' result['total'] = r_dict['meta']['found'] result['limit'] = r_dict['meta']['limit'] result['total_returned'] = len(r_dict['results']) result['results'] = [{'sceneID': i['sceneID'], 'sat_type': u'L8', 'path': three_digit(i['path']), 'row': three_digit(i['row']), 'thumbnail': i['browseURL'], 'date': i['acquisitionDate'], 'cloud': i['cloud_coverage']} for i in r_dict['results']] return result
[ "def", "search", "(", "self", ",", "paths_rows", "=", "None", ",", "lat", "=", "None", ",", "lon", "=", "None", ",", "address", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "cloud_min", "=", "None", ",", "cloud_max"...
The main method of Search class. It searches Development Seed's Landsat API. :param paths_rows: A string in this format: "003,003,004,004". Must be in pairs and separated by comma. :type paths_rows: String :param lat: The latitude :type lat: String, float, integer :param lon: The The longitude :type lon: String, float, integer :param address: The address :type address: String :param start_date: Date string. format: YYYY-MM-DD :type start_date: String :param end_date: date string. format: YYYY-MM-DD :type end_date: String :param cloud_min: float specifying the minimum percentage. e.g. 4.3 :type cloud_min: float :param cloud_max: float specifying the maximum percentage. e.g. 78.9 :type cloud_max: float :param limit: integer specigying the maximum results return. :type limit: integer :param geojson: boolean specifying whether to return a geojson object :type geojson: boolean :returns: dict :example: >>> search = Search() >>> search('003,003', '2014-01-01', '2014-06-01') >>> { 'status': u'SUCCESS', 'total_returned': 1, 'total': 1, 'limit': 1 'results': [ { 'sat_type': u'L8', 'sceneID': u'LC80030032014142LGN00', 'date': u'2014-05-22', 'path': u'003', 'thumbnail': u'http://....../landsat_8/2014/003/003/LC80030032014142LGN00.jpg', 'cloud': 33.36, 'row': u'003 } ] }
[ "The", "main", "method", "of", "Search", "class", ".", "It", "searches", "Development", "Seed", "s", "Landsat", "API", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/search.py#L20-L153
train
208,923
developmentseed/landsat-util
landsat/search.py
Search.date_range_builder
def date_range_builder(self, start='2013-02-11', end=None): """ Builds date range query. :param start: Date string. format: YYYY-MM-DD :type start: String :param end: date string. format: YYYY-MM-DD :type end: String :returns: String """ if not end: end = time.strftime('%Y-%m-%d') return 'acquisitionDate:[%s+TO+%s]' % (start, end)
python
def date_range_builder(self, start='2013-02-11', end=None): """ Builds date range query. :param start: Date string. format: YYYY-MM-DD :type start: String :param end: date string. format: YYYY-MM-DD :type end: String :returns: String """ if not end: end = time.strftime('%Y-%m-%d') return 'acquisitionDate:[%s+TO+%s]' % (start, end)
[ "def", "date_range_builder", "(", "self", ",", "start", "=", "'2013-02-11'", ",", "end", "=", "None", ")", ":", "if", "not", "end", ":", "end", "=", "time", ".", "strftime", "(", "'%Y-%m-%d'", ")", "return", "'acquisitionDate:[%s+TO+%s]'", "%", "(", "start...
Builds date range query. :param start: Date string. format: YYYY-MM-DD :type start: String :param end: date string. format: YYYY-MM-DD :type end: String :returns: String
[ "Builds", "date", "range", "query", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/search.py#L254-L273
train
208,924
developmentseed/landsat-util
landsat/utils.py
exit
def exit(message, code=0): """ output a message to stdout and terminates the process. :param message: Message to be outputed. :type message: String :param code: The termination code. Default is 0 :type code: int :returns: void """ v = VerbosityMixin() if code == 0: v.output(message, normal=True, arrow=True) v.output('Done!', normal=True, arrow=True) else: v.output(message, normal=True, error=True) sys.exit(code)
python
def exit(message, code=0): """ output a message to stdout and terminates the process. :param message: Message to be outputed. :type message: String :param code: The termination code. Default is 0 :type code: int :returns: void """ v = VerbosityMixin() if code == 0: v.output(message, normal=True, arrow=True) v.output('Done!', normal=True, arrow=True) else: v.output(message, normal=True, error=True) sys.exit(code)
[ "def", "exit", "(", "message", ",", "code", "=", "0", ")", ":", "v", "=", "VerbosityMixin", "(", ")", "if", "code", "==", "0", ":", "v", ".", "output", "(", "message", ",", "normal", "=", "True", ",", "arrow", "=", "True", ")", "v", ".", "outpu...
output a message to stdout and terminates the process. :param message: Message to be outputed. :type message: String :param code: The termination code. Default is 0 :type code: int :returns: void
[ "output", "a", "message", "to", "stdout", "and", "terminates", "the", "process", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L57-L79
train
208,925
developmentseed/landsat-util
landsat/utils.py
create_paired_list
def create_paired_list(value): """ Create a list of paired items from a string. :param value: the format must be 003,003,004,004 (commas with no space) :type value: String :returns: List :example: >>> create_paired_list('003,003,004,004') [['003','003'], ['004', '004']] """ if isinstance(value, list): value = ",".join(value) array = re.split('\D+', value) # Make sure the elements in the list are even and pairable if len(array) % 2 == 0: new_array = [list(array[i:i + 2]) for i in range(0, len(array), 2)] return new_array else: raise ValueError('The string should include pairs and be formated. ' 'The format must be 003,003,004,004 (commas with ' 'no space)')
python
def create_paired_list(value): """ Create a list of paired items from a string. :param value: the format must be 003,003,004,004 (commas with no space) :type value: String :returns: List :example: >>> create_paired_list('003,003,004,004') [['003','003'], ['004', '004']] """ if isinstance(value, list): value = ",".join(value) array = re.split('\D+', value) # Make sure the elements in the list are even and pairable if len(array) % 2 == 0: new_array = [list(array[i:i + 2]) for i in range(0, len(array), 2)] return new_array else: raise ValueError('The string should include pairs and be formated. ' 'The format must be 003,003,004,004 (commas with ' 'no space)')
[ "def", "create_paired_list", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "\",\"", ".", "join", "(", "value", ")", "array", "=", "re", ".", "split", "(", "'\\D+'", ",", "value", ")", "# Make sure the el...
Create a list of paired items from a string. :param value: the format must be 003,003,004,004 (commas with no space) :type value: String :returns: List :example: >>> create_paired_list('003,003,004,004') [['003','003'], ['004', '004']]
[ "Create", "a", "list", "of", "paired", "items", "from", "a", "string", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L82-L111
train
208,926
developmentseed/landsat-util
landsat/utils.py
check_create_folder
def check_create_folder(folder_path): """ Check whether a folder exists, if not the folder is created. :param folder_path: Path to the folder :type folder_path: String :returns: (String) the path to the folder """ if not os.path.exists(folder_path): os.makedirs(folder_path) return folder_path
python
def check_create_folder(folder_path): """ Check whether a folder exists, if not the folder is created. :param folder_path: Path to the folder :type folder_path: String :returns: (String) the path to the folder """ if not os.path.exists(folder_path): os.makedirs(folder_path) return folder_path
[ "def", "check_create_folder", "(", "folder_path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "folder_path", ")", ":", "os", ".", "makedirs", "(", "folder_path", ")", "return", "folder_path" ]
Check whether a folder exists, if not the folder is created. :param folder_path: Path to the folder :type folder_path: String :returns: (String) the path to the folder
[ "Check", "whether", "a", "folder", "exists", "if", "not", "the", "folder", "is", "created", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L114-L128
train
208,927
developmentseed/landsat-util
landsat/utils.py
three_digit
def three_digit(number): """ Add 0s to inputs that their length is less than 3. :param number: The number to convert :type number: int :returns: String :example: >>> three_digit(1) '001' """ number = str(number) if len(number) == 1: return u'00%s' % number elif len(number) == 2: return u'0%s' % number else: return number
python
def three_digit(number): """ Add 0s to inputs that their length is less than 3. :param number: The number to convert :type number: int :returns: String :example: >>> three_digit(1) '001' """ number = str(number) if len(number) == 1: return u'00%s' % number elif len(number) == 2: return u'0%s' % number else: return number
[ "def", "three_digit", "(", "number", ")", ":", "number", "=", "str", "(", "number", ")", "if", "len", "(", "number", ")", "==", "1", ":", "return", "u'00%s'", "%", "number", "elif", "len", "(", "number", ")", "==", "2", ":", "return", "u'0%s'", "%"...
Add 0s to inputs that their length is less than 3. :param number: The number to convert :type number: int :returns: String :example: >>> three_digit(1) '001'
[ "Add", "0s", "to", "inputs", "that", "their", "length", "is", "less", "than", "3", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L167-L188
train
208,928
developmentseed/landsat-util
landsat/utils.py
georgian_day
def georgian_day(date): """ Returns the number of days passed since the start of the year. :param date: The string date with this format %m/%d/%Y :type date: String :returns: int :example: >>> georgian_day('05/1/2015') 121 """ try: fmt = '%m/%d/%Y' return datetime.strptime(date, fmt).timetuple().tm_yday except (ValueError, TypeError): return 0
python
def georgian_day(date): """ Returns the number of days passed since the start of the year. :param date: The string date with this format %m/%d/%Y :type date: String :returns: int :example: >>> georgian_day('05/1/2015') 121 """ try: fmt = '%m/%d/%Y' return datetime.strptime(date, fmt).timetuple().tm_yday except (ValueError, TypeError): return 0
[ "def", "georgian_day", "(", "date", ")", ":", "try", ":", "fmt", "=", "'%m/%d/%Y'", "return", "datetime", ".", "strptime", "(", "date", ",", "fmt", ")", ".", "timetuple", "(", ")", ".", "tm_yday", "except", "(", "ValueError", ",", "TypeError", ")", ":"...
Returns the number of days passed since the start of the year. :param date: The string date with this format %m/%d/%Y :type date: String :returns: int :example: >>> georgian_day('05/1/2015') 121
[ "Returns", "the", "number", "of", "days", "passed", "since", "the", "start", "of", "the", "year", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L191-L210
train
208,929
developmentseed/landsat-util
landsat/utils.py
year
def year(date): """ Returns the year. :param date: The string date with this format %m/%d/%Y :type date: String :returns: int :example: >>> year('05/1/2015') 2015 """ try: fmt = '%m/%d/%Y' return datetime.strptime(date, fmt).timetuple().tm_year except ValueError: return 0
python
def year(date): """ Returns the year. :param date: The string date with this format %m/%d/%Y :type date: String :returns: int :example: >>> year('05/1/2015') 2015 """ try: fmt = '%m/%d/%Y' return datetime.strptime(date, fmt).timetuple().tm_year except ValueError: return 0
[ "def", "year", "(", "date", ")", ":", "try", ":", "fmt", "=", "'%m/%d/%Y'", "return", "datetime", ".", "strptime", "(", "date", ",", "fmt", ")", ".", "timetuple", "(", ")", ".", "tm_year", "except", "ValueError", ":", "return", "0" ]
Returns the year. :param date: The string date with this format %m/%d/%Y :type date: String :returns: int :example: >>> year('05/1/2015') 2015
[ "Returns", "the", "year", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L213-L232
train
208,930
developmentseed/landsat-util
landsat/utils.py
reformat_date
def reformat_date(date, new_fmt='%Y-%m-%d'): """ Returns reformated date. :param date: The string date with this format %m/%d/%Y :type date: String :param new_fmt: date format string. Default is '%Y-%m-%d' :type date: String :returns: int :example: >>> reformat_date('05/1/2015', '%d/%m/%Y') '1/05/2015' """ try: if isinstance(date, datetime): return date.strftime(new_fmt) else: fmt = '%m/%d/%Y' return datetime.strptime(date, fmt).strftime(new_fmt) except ValueError: return date
python
def reformat_date(date, new_fmt='%Y-%m-%d'): """ Returns reformated date. :param date: The string date with this format %m/%d/%Y :type date: String :param new_fmt: date format string. Default is '%Y-%m-%d' :type date: String :returns: int :example: >>> reformat_date('05/1/2015', '%d/%m/%Y') '1/05/2015' """ try: if isinstance(date, datetime): return date.strftime(new_fmt) else: fmt = '%m/%d/%Y' return datetime.strptime(date, fmt).strftime(new_fmt) except ValueError: return date
[ "def", "reformat_date", "(", "date", ",", "new_fmt", "=", "'%Y-%m-%d'", ")", ":", "try", ":", "if", "isinstance", "(", "date", ",", "datetime", ")", ":", "return", "date", ".", "strftime", "(", "new_fmt", ")", "else", ":", "fmt", "=", "'%m/%d/%Y'", "re...
Returns reformated date. :param date: The string date with this format %m/%d/%Y :type date: String :param new_fmt: date format string. Default is '%Y-%m-%d' :type date: String :returns: int :example: >>> reformat_date('05/1/2015', '%d/%m/%Y') '1/05/2015'
[ "Returns", "reformated", "date", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L235-L261
train
208,931
developmentseed/landsat-util
landsat/utils.py
geocode
def geocode(address, required_precision_km=1.): """ Identifies the coordinates of an address :param address: the address to be geocoded :type value: String :param required_precision_km: the maximum permissible geographic uncertainty for the geocoding :type required_precision_km: float :returns: dict :example: >>> geocode('1600 Pennsylvania Ave NW, Washington, DC 20500') {'lat': 38.89767579999999, 'lon': -77.0364827} """ geocoded = geocoder.google(address) precision_km = geocode_confidences[geocoded.confidence] if precision_km <= required_precision_km: (lon, lat) = geocoded.geometry['coordinates'] return {'lat': lat, 'lon': lon} else: raise ValueError("Address could not be precisely located")
python
def geocode(address, required_precision_km=1.): """ Identifies the coordinates of an address :param address: the address to be geocoded :type value: String :param required_precision_km: the maximum permissible geographic uncertainty for the geocoding :type required_precision_km: float :returns: dict :example: >>> geocode('1600 Pennsylvania Ave NW, Washington, DC 20500') {'lat': 38.89767579999999, 'lon': -77.0364827} """ geocoded = geocoder.google(address) precision_km = geocode_confidences[geocoded.confidence] if precision_km <= required_precision_km: (lon, lat) = geocoded.geometry['coordinates'] return {'lat': lat, 'lon': lon} else: raise ValueError("Address could not be precisely located")
[ "def", "geocode", "(", "address", ",", "required_precision_km", "=", "1.", ")", ":", "geocoded", "=", "geocoder", ".", "google", "(", "address", ")", "precision_km", "=", "geocode_confidences", "[", "geocoded", ".", "confidence", "]", "if", "precision_km", "<=...
Identifies the coordinates of an address :param address: the address to be geocoded :type value: String :param required_precision_km: the maximum permissible geographic uncertainty for the geocoding :type required_precision_km: float :returns: dict :example: >>> geocode('1600 Pennsylvania Ave NW, Washington, DC 20500') {'lat': 38.89767579999999, 'lon': -77.0364827}
[ "Identifies", "the", "coordinates", "of", "an", "address" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L308-L335
train
208,932
developmentseed/landsat-util
landsat/utils.py
adjust_bounding_box
def adjust_bounding_box(bounds1, bounds2): """ If the bounds 2 corners are outside of bounds1, they will be adjusted to bounds1 corners @params bounds1 - The source bounding box bounds2 - The target bounding box that has to be within bounds1 @return A bounding box tuple in (y1, x1, y2, x2) format """ # out of bound check # If it is completely outside of target bounds, return target bounds if ((bounds2[0] > bounds1[0] and bounds2[2] > bounds1[0]) or (bounds2[2] < bounds1[2] and bounds2[2] < bounds1[0])): return bounds1 if ((bounds2[1] < bounds1[1] and bounds2[3] < bounds1[1]) or (bounds2[3] > bounds1[3] and bounds2[1] > bounds1[3])): return bounds1 new_bounds = list(bounds2) # Adjust Y axis (Longitude) if (bounds2[0] > bounds1[0] or bounds2[0] < bounds1[3]): new_bounds[0] = bounds1[0] if (bounds2[2] < bounds1[2] or bounds2[2] > bounds1[0]): new_bounds[2] = bounds1[2] # Adjust X axis (Latitude) if (bounds2[1] < bounds1[1] or bounds2[1] > bounds1[3]): new_bounds[1] = bounds1[1] if (bounds2[3] > bounds1[3] or bounds2[3] < bounds1[1]): new_bounds[3] = bounds1[3] return tuple(new_bounds)
python
def adjust_bounding_box(bounds1, bounds2): """ If the bounds 2 corners are outside of bounds1, they will be adjusted to bounds1 corners @params bounds1 - The source bounding box bounds2 - The target bounding box that has to be within bounds1 @return A bounding box tuple in (y1, x1, y2, x2) format """ # out of bound check # If it is completely outside of target bounds, return target bounds if ((bounds2[0] > bounds1[0] and bounds2[2] > bounds1[0]) or (bounds2[2] < bounds1[2] and bounds2[2] < bounds1[0])): return bounds1 if ((bounds2[1] < bounds1[1] and bounds2[3] < bounds1[1]) or (bounds2[3] > bounds1[3] and bounds2[1] > bounds1[3])): return bounds1 new_bounds = list(bounds2) # Adjust Y axis (Longitude) if (bounds2[0] > bounds1[0] or bounds2[0] < bounds1[3]): new_bounds[0] = bounds1[0] if (bounds2[2] < bounds1[2] or bounds2[2] > bounds1[0]): new_bounds[2] = bounds1[2] # Adjust X axis (Latitude) if (bounds2[1] < bounds1[1] or bounds2[1] > bounds1[3]): new_bounds[1] = bounds1[1] if (bounds2[3] > bounds1[3] or bounds2[3] < bounds1[1]): new_bounds[3] = bounds1[3] return tuple(new_bounds)
[ "def", "adjust_bounding_box", "(", "bounds1", ",", "bounds2", ")", ":", "# out of bound check", "# If it is completely outside of target bounds, return target bounds", "if", "(", "(", "bounds2", "[", "0", "]", ">", "bounds1", "[", "0", "]", "and", "bounds2", "[", "2...
If the bounds 2 corners are outside of bounds1, they will be adjusted to bounds1 corners @params bounds1 - The source bounding box bounds2 - The target bounding box that has to be within bounds1 @return A bounding box tuple in (y1, x1, y2, x2) format
[ "If", "the", "bounds", "2", "corners", "are", "outside", "of", "bounds1", "they", "will", "be", "adjusted", "to", "bounds1", "corners" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L366-L401
train
208,933
developmentseed/landsat-util
landsat/landsat.py
process_image
def process_image(path, bands=None, verbose=False, pansharpen=False, ndvi=False, force_unzip=None, ndvigrey=False, bounds=None): """ Handles constructing and image process. :param path: The path to the image that has to be processed :type path: String :param bands: List of bands that has to be processed. (optional) :type bands: List :param verbose: Sets the level of verbosity. Default is False. :type verbose: boolean :param pansharpen: Whether to pansharpen the image. Default is False. :type pansharpen: boolean :returns: (String) path to the processed image """ try: bands = convert_to_integer_list(bands) if pansharpen: p = PanSharpen(path, bands=bands, dst_path=settings.PROCESSED_IMAGE, verbose=verbose, force_unzip=force_unzip, bounds=bounds) elif ndvigrey: p = NDVI(path, verbose=verbose, dst_path=settings.PROCESSED_IMAGE, force_unzip=force_unzip, bounds=bounds) elif ndvi: p = NDVIWithManualColorMap(path, dst_path=settings.PROCESSED_IMAGE, verbose=verbose, force_unzip=force_unzip, bounds=bounds) else: p = Simple(path, bands=bands, dst_path=settings.PROCESSED_IMAGE, verbose=verbose, force_unzip=force_unzip, bounds=bounds) except IOError as err: exit(str(err), 1) except FileDoesNotExist as err: exit(str(err), 1) return p.run()
python
def process_image(path, bands=None, verbose=False, pansharpen=False, ndvi=False, force_unzip=None, ndvigrey=False, bounds=None): """ Handles constructing and image process. :param path: The path to the image that has to be processed :type path: String :param bands: List of bands that has to be processed. (optional) :type bands: List :param verbose: Sets the level of verbosity. Default is False. :type verbose: boolean :param pansharpen: Whether to pansharpen the image. Default is False. :type pansharpen: boolean :returns: (String) path to the processed image """ try: bands = convert_to_integer_list(bands) if pansharpen: p = PanSharpen(path, bands=bands, dst_path=settings.PROCESSED_IMAGE, verbose=verbose, force_unzip=force_unzip, bounds=bounds) elif ndvigrey: p = NDVI(path, verbose=verbose, dst_path=settings.PROCESSED_IMAGE, force_unzip=force_unzip, bounds=bounds) elif ndvi: p = NDVIWithManualColorMap(path, dst_path=settings.PROCESSED_IMAGE, verbose=verbose, force_unzip=force_unzip, bounds=bounds) else: p = Simple(path, bands=bands, dst_path=settings.PROCESSED_IMAGE, verbose=verbose, force_unzip=force_unzip, bounds=bounds) except IOError as err: exit(str(err), 1) except FileDoesNotExist as err: exit(str(err), 1) return p.run()
[ "def", "process_image", "(", "path", ",", "bands", "=", "None", ",", "verbose", "=", "False", ",", "pansharpen", "=", "False", ",", "ndvi", "=", "False", ",", "force_unzip", "=", "None", ",", "ndvigrey", "=", "False", ",", "bounds", "=", "None", ")", ...
Handles constructing and image process. :param path: The path to the image that has to be processed :type path: String :param bands: List of bands that has to be processed. (optional) :type bands: List :param verbose: Sets the level of verbosity. Default is False. :type verbose: boolean :param pansharpen: Whether to pansharpen the image. Default is False. :type pansharpen: boolean :returns: (String) path to the processed image
[ "Handles", "constructing", "and", "image", "process", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/landsat.py#L435-L478
train
208,934
developmentseed/landsat-util
landsat/image.py
BaseProcess._read_bands
def _read_bands(self): """ Reads a band with rasterio """ bands = [] try: for i, band in enumerate(self.bands): bands.append(rasterio.open(self.bands_path[i]).read_band(1)) except IOError as e: exit(e.message, 1) return bands
python
def _read_bands(self): """ Reads a band with rasterio """ bands = [] try: for i, band in enumerate(self.bands): bands.append(rasterio.open(self.bands_path[i]).read_band(1)) except IOError as e: exit(e.message, 1) return bands
[ "def", "_read_bands", "(", "self", ")", ":", "bands", "=", "[", "]", "try", ":", "for", "i", ",", "band", "in", "enumerate", "(", "self", ".", "bands", ")", ":", "bands", ".", "append", "(", "rasterio", ".", "open", "(", "self", ".", "bands_path", ...
Reads a band with rasterio
[ "Reads", "a", "band", "with", "rasterio" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/image.py#L141-L151
train
208,935
developmentseed/landsat-util
landsat/image.py
BaseProcess._unzip
def _unzip(self, src, dst, scene, force_unzip=False): """ Unzip tar files """ self.output("Unzipping %s - It might take some time" % scene, normal=True, arrow=True) try: # check if file is already unzipped, skip if isdir(dst) and not force_unzip: self.output('%s is already unzipped.' % scene, normal=True, color='green', indent=1) return else: tar = tarfile.open(src, 'r') tar.extractall(path=dst) tar.close() except tarfile.ReadError: check_create_folder(dst) subprocess.check_call(['tar', '-xf', src, '-C', dst])
python
def _unzip(self, src, dst, scene, force_unzip=False): """ Unzip tar files """ self.output("Unzipping %s - It might take some time" % scene, normal=True, arrow=True) try: # check if file is already unzipped, skip if isdir(dst) and not force_unzip: self.output('%s is already unzipped.' % scene, normal=True, color='green', indent=1) return else: tar = tarfile.open(src, 'r') tar.extractall(path=dst) tar.close() except tarfile.ReadError: check_create_folder(dst) subprocess.check_call(['tar', '-xf', src, '-C', dst])
[ "def", "_unzip", "(", "self", ",", "src", ",", "dst", ",", "scene", ",", "force_unzip", "=", "False", ")", ":", "self", ".", "output", "(", "\"Unzipping %s - It might take some time\"", "%", "scene", ",", "normal", "=", "True", ",", "arrow", "=", "True", ...
Unzip tar files
[ "Unzip", "tar", "files" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/image.py#L161-L176
train
208,936
developmentseed/landsat-util
landsat/image.py
BaseProcess._filename
def _filename(self, name=None, suffix=None, prefix=None): """ File name generator for processed images """ filename = '' if prefix: filename += str(prefix) + '_' if name: filename += str(name) else: filename += str(self.scene) if suffix: filename += '_' + str(suffix) if self.clipped: bounds = [tuple(self.bounds[0:2]), tuple(self.bounds[2:4])] polyline = PolylineCodec().encode(bounds) filename += '_clipped_' + polyline filename += '.TIF' return filename
python
def _filename(self, name=None, suffix=None, prefix=None): """ File name generator for processed images """ filename = '' if prefix: filename += str(prefix) + '_' if name: filename += str(name) else: filename += str(self.scene) if suffix: filename += '_' + str(suffix) if self.clipped: bounds = [tuple(self.bounds[0:2]), tuple(self.bounds[2:4])] polyline = PolylineCodec().encode(bounds) filename += '_clipped_' + polyline filename += '.TIF' return filename
[ "def", "_filename", "(", "self", ",", "name", "=", "None", ",", "suffix", "=", "None", ",", "prefix", "=", "None", ")", ":", "filename", "=", "''", "if", "prefix", ":", "filename", "+=", "str", "(", "prefix", ")", "+", "'_'", "if", "name", ":", "...
File name generator for processed images
[ "File", "name", "generator", "for", "processed", "images" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/image.py#L309-L332
train
208,937
developmentseed/landsat-util
landsat/image.py
Simple.run
def run(self): """ Executes the image processing. :returns: (String) the path to the processed image """ self.output('Image processing started for bands %s' % '-'.join(map(str, self.bands)), normal=True, arrow=True) bands = self._read_bands() image_data = self._get_image_data() new_bands = self._generate_new_bands(image_data['shape']) self._warp(image_data, bands, new_bands) # Bands are no longer needed del bands rasterio_options = { 'driver': 'GTiff', 'width': image_data['shape'][1], 'height': image_data['shape'][0], 'count': 3, 'dtype': numpy.uint8, 'nodata': 0, 'transform': image_data['dst_transform'], 'photometric': 'RGB', 'crs': self.dst_crs } return self._write_to_file(new_bands, **rasterio_options)
python
def run(self): """ Executes the image processing. :returns: (String) the path to the processed image """ self.output('Image processing started for bands %s' % '-'.join(map(str, self.bands)), normal=True, arrow=True) bands = self._read_bands() image_data = self._get_image_data() new_bands = self._generate_new_bands(image_data['shape']) self._warp(image_data, bands, new_bands) # Bands are no longer needed del bands rasterio_options = { 'driver': 'GTiff', 'width': image_data['shape'][1], 'height': image_data['shape'][0], 'count': 3, 'dtype': numpy.uint8, 'nodata': 0, 'transform': image_data['dst_transform'], 'photometric': 'RGB', 'crs': self.dst_crs } return self._write_to_file(new_bands, **rasterio_options)
[ "def", "run", "(", "self", ")", ":", "self", ".", "output", "(", "'Image processing started for bands %s'", "%", "'-'", ".", "join", "(", "map", "(", "str", ",", "self", ".", "bands", ")", ")", ",", "normal", "=", "True", ",", "arrow", "=", "True", "...
Executes the image processing. :returns: (String) the path to the processed image
[ "Executes", "the", "image", "processing", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/image.py#L394-L425
train
208,938
developmentseed/landsat-util
landsat/mixins.py
VerbosityMixin.output
def output(self, value, normal=False, color=None, error=False, arrow=False, indent=None): """ Handles verbosity of this calls. if priority is set to 1, the value is printed if class instance verbose is True, the value is printed :param value: a string representing the message to be printed :type value: String :param normal: if set to true the message is always printed, otherwise it is only shown if verbosity is set :type normal: boolean :param color: The color of the message, choices: 'red', 'green', 'blue' :type normal: String :param error: if set to true the message appears in red :type error: Boolean :param arrow: if set to true an arrow appears before the message :type arrow: Boolean :param indent: indents the message based on the number provided :type indent: Boolean :returns: void """ if error and value and (normal or self.verbose): return self._print(value, color='red', indent=indent) if self.verbose or normal: return self._print(value, color, arrow, indent) return
python
def output(self, value, normal=False, color=None, error=False, arrow=False, indent=None): """ Handles verbosity of this calls. if priority is set to 1, the value is printed if class instance verbose is True, the value is printed :param value: a string representing the message to be printed :type value: String :param normal: if set to true the message is always printed, otherwise it is only shown if verbosity is set :type normal: boolean :param color: The color of the message, choices: 'red', 'green', 'blue' :type normal: String :param error: if set to true the message appears in red :type error: Boolean :param arrow: if set to true an arrow appears before the message :type arrow: Boolean :param indent: indents the message based on the number provided :type indent: Boolean :returns: void """ if error and value and (normal or self.verbose): return self._print(value, color='red', indent=indent) if self.verbose or normal: return self._print(value, color, arrow, indent) return
[ "def", "output", "(", "self", ",", "value", ",", "normal", "=", "False", ",", "color", "=", "None", ",", "error", "=", "False", ",", "arrow", "=", "False", ",", "indent", "=", "None", ")", ":", "if", "error", "and", "value", "and", "(", "normal", ...
Handles verbosity of this calls. if priority is set to 1, the value is printed if class instance verbose is True, the value is printed :param value: a string representing the message to be printed :type value: String :param normal: if set to true the message is always printed, otherwise it is only shown if verbosity is set :type normal: boolean :param color: The color of the message, choices: 'red', 'green', 'blue' :type normal: String :param error: if set to true the message appears in red :type error: Boolean :param arrow: if set to true an arrow appears before the message :type arrow: Boolean :param indent: indents the message based on the number provided :type indent: Boolean :returns: void
[ "Handles", "verbosity", "of", "this", "calls", ".", "if", "priority", "is", "set", "to", "1", "the", "value", "is", "printed" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/mixins.py#L19-L61
train
208,939
developmentseed/landsat-util
landsat/mixins.py
VerbosityMixin.subprocess
def subprocess(self, argv): """ Execute subprocess commands with proper ouput. This is no longer used in landsat-util :param argv: A list of subprocess arguments :type argv: List :returns: void """ if self.verbose: proc = subprocess.Popen(argv, stderr=subprocess.PIPE) else: proc = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.output(proc.stderr.read(), error=True) return
python
def subprocess(self, argv): """ Execute subprocess commands with proper ouput. This is no longer used in landsat-util :param argv: A list of subprocess arguments :type argv: List :returns: void """ if self.verbose: proc = subprocess.Popen(argv, stderr=subprocess.PIPE) else: proc = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.output(proc.stderr.read(), error=True) return
[ "def", "subprocess", "(", "self", ",", "argv", ")", ":", "if", "self", ".", "verbose", ":", "proc", "=", "subprocess", ".", "Popen", "(", "argv", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "else", ":", "proc", "=", "subprocess", ".", "Popen"...
Execute subprocess commands with proper ouput. This is no longer used in landsat-util :param argv: A list of subprocess arguments :type argv: List :returns: void
[ "Execute", "subprocess", "commands", "with", "proper", "ouput", ".", "This", "is", "no", "longer", "used", "in", "landsat", "-", "util" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/mixins.py#L63-L85
train
208,940
developmentseed/landsat-util
landsat/mixins.py
VerbosityMixin.exit
def exit(self, message): """ outputs an exit message and exits :param message: The message to be outputed :type message: String :returns: void """ self.output(message, normal=True, color="green") sys.exit()
python
def exit(self, message): """ outputs an exit message and exits :param message: The message to be outputed :type message: String :returns: void """ self.output(message, normal=True, color="green") sys.exit()
[ "def", "exit", "(", "self", ",", "message", ")", ":", "self", ".", "output", "(", "message", ",", "normal", "=", "True", ",", "color", "=", "\"green\"", ")", "sys", ".", "exit", "(", ")" ]
outputs an exit message and exits :param message: The message to be outputed :type message: String :returns: void
[ "outputs", "an", "exit", "message", "and", "exits" ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/mixins.py#L87-L100
train
208,941
developmentseed/landsat-util
landsat/mixins.py
VerbosityMixin._print
def _print(self, msg, color=None, arrow=False, indent=None): """ Print the msg with the color provided. """ if color: msg = colored(msg, color) if arrow: msg = colored('===> ', 'blue') + msg if indent: msg = (' ' * indent) + msg print(msg) return msg
python
def _print(self, msg, color=None, arrow=False, indent=None): """ Print the msg with the color provided. """ if color: msg = colored(msg, color) if arrow: msg = colored('===> ', 'blue') + msg if indent: msg = (' ' * indent) + msg print(msg) return msg
[ "def", "_print", "(", "self", ",", "msg", ",", "color", "=", "None", ",", "arrow", "=", "False", ",", "indent", "=", "None", ")", ":", "if", "color", ":", "msg", "=", "colored", "(", "msg", ",", "color", ")", "if", "arrow", ":", "msg", "=", "co...
Print the msg with the color provided.
[ "Print", "the", "msg", "with", "the", "color", "provided", "." ]
92dc81771ddaa64a8a9124a89a6516b52485374b
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/mixins.py#L102-L115
train
208,942
tonysimpson/nanomsg-python
_nanomsg_ctypes/__init__.py
nn_symbols
def nn_symbols(): "query the names and values of nanomsg symbols" value = ctypes.c_int() name_value_pairs = [] i = 0 while True: name = _nn_symbol(i, ctypes.byref(value)) if name is None: break i += 1 name_value_pairs.append((name.decode('ascii'), value.value)) return name_value_pairs
python
def nn_symbols(): "query the names and values of nanomsg symbols" value = ctypes.c_int() name_value_pairs = [] i = 0 while True: name = _nn_symbol(i, ctypes.byref(value)) if name is None: break i += 1 name_value_pairs.append((name.decode('ascii'), value.value)) return name_value_pairs
[ "def", "nn_symbols", "(", ")", ":", "value", "=", "ctypes", ".", "c_int", "(", ")", "name_value_pairs", "=", "[", "]", "i", "=", "0", "while", "True", ":", "name", "=", "_nn_symbol", "(", "i", ",", "ctypes", ".", "byref", "(", "value", ")", ")", ...
query the names and values of nanomsg symbols
[ "query", "the", "names", "and", "values", "of", "nanomsg", "symbols" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/_nanomsg_ctypes/__init__.py#L98-L109
train
208,943
tonysimpson/nanomsg-python
_nanomsg_ctypes/__init__.py
nn_setsockopt
def nn_setsockopt(socket, level, option, value): """set a socket option socket - socket number level - option level option - option value - a readable byte buffer (not a Unicode string) containing the value returns - 0 on success or < 0 on error """ try: return _nn_setsockopt(socket, level, option, ctypes.addressof(value), len(value)) except (TypeError, AttributeError): buf_value = ctypes.create_string_buffer(value) return _nn_setsockopt(socket, level, option, ctypes.addressof(buf_value), len(value))
python
def nn_setsockopt(socket, level, option, value): """set a socket option socket - socket number level - option level option - option value - a readable byte buffer (not a Unicode string) containing the value returns - 0 on success or < 0 on error """ try: return _nn_setsockopt(socket, level, option, ctypes.addressof(value), len(value)) except (TypeError, AttributeError): buf_value = ctypes.create_string_buffer(value) return _nn_setsockopt(socket, level, option, ctypes.addressof(buf_value), len(value))
[ "def", "nn_setsockopt", "(", "socket", ",", "level", ",", "option", ",", "value", ")", ":", "try", ":", "return", "_nn_setsockopt", "(", "socket", ",", "level", ",", "option", ",", "ctypes", ".", "addressof", "(", "value", ")", ",", "len", "(", "value"...
set a socket option socket - socket number level - option level option - option value - a readable byte buffer (not a Unicode string) containing the value returns - 0 on success or < 0 on error
[ "set", "a", "socket", "option" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/_nanomsg_ctypes/__init__.py#L142-L158
train
208,944
tonysimpson/nanomsg-python
_nanomsg_ctypes/__init__.py
nn_getsockopt
def nn_getsockopt(socket, level, option, value): """retrieve a socket option socket - socket number level - option level option - option value - a writable byte buffer (e.g. a bytearray) which the option value will be copied to returns - number of bytes copied or on error nunber < 0 """ if memoryview(value).readonly: raise TypeError('Writable buffer is required') size_t_size = ctypes.c_size_t(len(value)) rtn = _nn_getsockopt(socket, level, option, ctypes.addressof(value), ctypes.byref(size_t_size)) return (rtn, size_t_size.value)
python
def nn_getsockopt(socket, level, option, value): """retrieve a socket option socket - socket number level - option level option - option value - a writable byte buffer (e.g. a bytearray) which the option value will be copied to returns - number of bytes copied or on error nunber < 0 """ if memoryview(value).readonly: raise TypeError('Writable buffer is required') size_t_size = ctypes.c_size_t(len(value)) rtn = _nn_getsockopt(socket, level, option, ctypes.addressof(value), ctypes.byref(size_t_size)) return (rtn, size_t_size.value)
[ "def", "nn_getsockopt", "(", "socket", ",", "level", ",", "option", ",", "value", ")", ":", "if", "memoryview", "(", "value", ")", ".", "readonly", ":", "raise", "TypeError", "(", "'Writable buffer is required'", ")", "size_t_size", "=", "ctypes", ".", "c_si...
retrieve a socket option socket - socket number level - option level option - option value - a writable byte buffer (e.g. a bytearray) which the option value will be copied to returns - number of bytes copied or on error nunber < 0
[ "retrieve", "a", "socket", "option" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/_nanomsg_ctypes/__init__.py#L161-L177
train
208,945
tonysimpson/nanomsg-python
_nanomsg_ctypes/__init__.py
nn_send
def nn_send(socket, msg, flags): "send a message" try: return _nn_send(socket, ctypes.addressof(msg), len(buffer(msg)), flags) except (TypeError, AttributeError): buf_msg = ctypes.create_string_buffer(msg) return _nn_send(socket, ctypes.addressof(buf_msg), len(msg), flags)
python
def nn_send(socket, msg, flags): "send a message" try: return _nn_send(socket, ctypes.addressof(msg), len(buffer(msg)), flags) except (TypeError, AttributeError): buf_msg = ctypes.create_string_buffer(msg) return _nn_send(socket, ctypes.addressof(buf_msg), len(msg), flags)
[ "def", "nn_send", "(", "socket", ",", "msg", ",", "flags", ")", ":", "try", ":", "return", "_nn_send", "(", "socket", ",", "ctypes", ".", "addressof", "(", "msg", ")", ",", "len", "(", "buffer", "(", "msg", ")", ")", ",", "flags", ")", "except", ...
send a message
[ "send", "a", "message" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/_nanomsg_ctypes/__init__.py#L180-L186
train
208,946
tonysimpson/nanomsg-python
_nanomsg_ctypes/__init__.py
nn_allocmsg
def nn_allocmsg(size, type): "allocate a message" pointer = _nn_allocmsg(size, type) if pointer is None: return None return _create_message(pointer, size)
python
def nn_allocmsg(size, type): "allocate a message" pointer = _nn_allocmsg(size, type) if pointer is None: return None return _create_message(pointer, size)
[ "def", "nn_allocmsg", "(", "size", ",", "type", ")", ":", "pointer", "=", "_nn_allocmsg", "(", "size", ",", "type", ")", "if", "pointer", "is", "None", ":", "return", "None", "return", "_create_message", "(", "pointer", ",", "size", ")" ]
allocate a message
[ "allocate", "a", "message" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/_nanomsg_ctypes/__init__.py#L212-L217
train
208,947
tonysimpson/nanomsg-python
_nanomsg_ctypes/__init__.py
nn_recv
def nn_recv(socket, *args): "receive a message" if len(args) == 1: flags, = args pointer = ctypes.c_void_p() rtn = _nn_recv(socket, ctypes.byref(pointer), ctypes.c_size_t(-1), flags) if rtn < 0: return rtn, None else: return rtn, _create_message(pointer.value, rtn) elif len(args) == 2: msg_buf, flags = args mv_buf = memoryview(msg_buf) if mv_buf.readonly: raise TypeError('Writable buffer is required') rtn = _nn_recv(socket, ctypes.addressof(msg_buf), len(mv_buf), flags) return rtn, msg_buf
python
def nn_recv(socket, *args): "receive a message" if len(args) == 1: flags, = args pointer = ctypes.c_void_p() rtn = _nn_recv(socket, ctypes.byref(pointer), ctypes.c_size_t(-1), flags) if rtn < 0: return rtn, None else: return rtn, _create_message(pointer.value, rtn) elif len(args) == 2: msg_buf, flags = args mv_buf = memoryview(msg_buf) if mv_buf.readonly: raise TypeError('Writable buffer is required') rtn = _nn_recv(socket, ctypes.addressof(msg_buf), len(mv_buf), flags) return rtn, msg_buf
[ "def", "nn_recv", "(", "socket", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "flags", ",", "=", "args", "pointer", "=", "ctypes", ".", "c_void_p", "(", ")", "rtn", "=", "_nn_recv", "(", "socket", ",", "ctypes", ".",...
receive a message
[ "receive", "a", "message" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/_nanomsg_ctypes/__init__.py#L247-L264
train
208,948
tonysimpson/nanomsg-python
nanomsg/__init__.py
create_message_buffer
def create_message_buffer(size, type): """Create a message buffer""" rtn = wrapper.nn_allocmsg(size, type) if rtn is None: raise NanoMsgAPIError() return rtn
python
def create_message_buffer(size, type): """Create a message buffer""" rtn = wrapper.nn_allocmsg(size, type) if rtn is None: raise NanoMsgAPIError() return rtn
[ "def", "create_message_buffer", "(", "size", ",", "type", ")", ":", "rtn", "=", "wrapper", ".", "nn_allocmsg", "(", "size", ",", "type", ")", "if", "rtn", "is", "None", ":", "raise", "NanoMsgAPIError", "(", ")", "return", "rtn" ]
Create a message buffer
[ "Create", "a", "message", "buffer" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/nanomsg/__init__.py#L31-L36
train
208,949
tonysimpson/nanomsg-python
nanomsg/__init__.py
Socket.bind
def bind(self, address): """Add a local endpoint to the socket""" if self.uses_nanoconfig: raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nn_bind(self._fd, address) ) ep = Socket.BindEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep
python
def bind(self, address): """Add a local endpoint to the socket""" if self.uses_nanoconfig: raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nn_bind(self._fd, address) ) ep = Socket.BindEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep
[ "def", "bind", "(", "self", ",", "address", ")", ":", "if", "self", ".", "uses_nanoconfig", ":", "raise", "ValueError", "(", "\"Nanoconfig address must be sole endpoint\"", ")", "endpoint_id", "=", "_nn_check_positive_rtn", "(", "wrapper", ".", "nn_bind", "(", "se...
Add a local endpoint to the socket
[ "Add", "a", "local", "endpoint", "to", "the", "socket" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/nanomsg/__init__.py#L304-L313
train
208,950
tonysimpson/nanomsg-python
nanomsg/__init__.py
Socket.connect
def connect(self, address): """Add a remote endpoint to the socket""" if self.uses_nanoconfig: raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nn_connect(self.fd, address) ) ep = Socket.ConnectEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep
python
def connect(self, address): """Add a remote endpoint to the socket""" if self.uses_nanoconfig: raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nn_connect(self.fd, address) ) ep = Socket.ConnectEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep
[ "def", "connect", "(", "self", ",", "address", ")", ":", "if", "self", ".", "uses_nanoconfig", ":", "raise", "ValueError", "(", "\"Nanoconfig address must be sole endpoint\"", ")", "endpoint_id", "=", "_nn_check_positive_rtn", "(", "wrapper", ".", "nn_connect", "(",...
Add a remote endpoint to the socket
[ "Add", "a", "remote", "endpoint", "to", "the", "socket" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/nanomsg/__init__.py#L315-L324
train
208,951
tonysimpson/nanomsg-python
nanomsg/__init__.py
Socket.configure
def configure(self, address): """Configure socket's addresses with nanoconfig""" global nanoconfig_started if len(self._endpoints): raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nc_configure(self.fd, address) ) if not nanoconfig_started: nanoconfig_started = True ep = Socket.NanoconfigEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep
python
def configure(self, address): """Configure socket's addresses with nanoconfig""" global nanoconfig_started if len(self._endpoints): raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nc_configure(self.fd, address) ) if not nanoconfig_started: nanoconfig_started = True ep = Socket.NanoconfigEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep
[ "def", "configure", "(", "self", ",", "address", ")", ":", "global", "nanoconfig_started", "if", "len", "(", "self", ".", "_endpoints", ")", ":", "raise", "ValueError", "(", "\"Nanoconfig address must be sole endpoint\"", ")", "endpoint_id", "=", "_nn_check_positive...
Configure socket's addresses with nanoconfig
[ "Configure", "socket", "s", "addresses", "with", "nanoconfig" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/nanomsg/__init__.py#L326-L338
train
208,952
tonysimpson/nanomsg-python
nanomsg/__init__.py
Socket.close
def close(self): """Close the socket""" if self.is_open(): fd = self._fd self._fd = -1 if self.uses_nanoconfig: wrapper.nc_close(fd) else: _nn_check_positive_rtn(wrapper.nn_close(fd))
python
def close(self): """Close the socket""" if self.is_open(): fd = self._fd self._fd = -1 if self.uses_nanoconfig: wrapper.nc_close(fd) else: _nn_check_positive_rtn(wrapper.nn_close(fd))
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "is_open", "(", ")", ":", "fd", "=", "self", ".", "_fd", "self", ".", "_fd", "=", "-", "1", "if", "self", ".", "uses_nanoconfig", ":", "wrapper", ".", "nc_close", "(", "fd", ")", "else", ...
Close the socket
[ "Close", "the", "socket" ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/nanomsg/__init__.py#L340-L348
train
208,953
tonysimpson/nanomsg-python
nanomsg/__init__.py
Socket.recv
def recv(self, buf=None, flags=0): """Recieve a message.""" if buf is None: rtn, out_buf = wrapper.nn_recv(self.fd, flags) else: rtn, out_buf = wrapper.nn_recv(self.fd, buf, flags) _nn_check_positive_rtn(rtn) return bytes(buffer(out_buf))[:rtn]
python
def recv(self, buf=None, flags=0): """Recieve a message.""" if buf is None: rtn, out_buf = wrapper.nn_recv(self.fd, flags) else: rtn, out_buf = wrapper.nn_recv(self.fd, buf, flags) _nn_check_positive_rtn(rtn) return bytes(buffer(out_buf))[:rtn]
[ "def", "recv", "(", "self", ",", "buf", "=", "None", ",", "flags", "=", "0", ")", ":", "if", "buf", "is", "None", ":", "rtn", ",", "out_buf", "=", "wrapper", ".", "nn_recv", "(", "self", ".", "fd", ",", "flags", ")", "else", ":", "rtn", ",", ...
Recieve a message.
[ "Recieve", "a", "message", "." ]
3acd9160f90f91034d4a43ce603aaa19fbaf1f2e
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/nanomsg/__init__.py#L359-L366
train
208,954
RaRe-Technologies/bounter
bounter/bounter.py
bounter
def bounter(size_mb=None, need_iteration=True, need_counts=True, log_counting=None): """Factory method for bounter implementation. Args: size_mb (int): Desired memory footprint of the counter. need_iteration (Bool): With `True`, create a `HashTable` implementation which can iterate over inserted key/value pairs. With `False`, create a `CountMinSketch` implementation which performs better in limited-memory scenarios, but does not support iteration over elements. need_counts (Bool): With `True`, construct the structure normally. With `False`, ignore all remaining parameters and create a minimalistic cardinality counter based on hyperloglog which only takes 64KB memory. log_counting (int): Counting to use with `CountMinSketch` implementation. Accepted values are `None` (default counting with 32-bit integers), 1024 (16-bit), 8 (8-bit). See `CountMinSketch` documentation for details. Raise ValueError if not `None `and `need_iteration` is `True`. """ if not need_counts: return CardinalityEstimator() if size_mb is None: raise ValueError("Max size in MB must be provided.") if need_iteration: if log_counting: raise ValueError("Log counting is only supported with CMS implementation (need_iteration=False).") return HashTable(size_mb=size_mb) else: return CountMinSketch(size_mb=size_mb, log_counting=log_counting)
python
def bounter(size_mb=None, need_iteration=True, need_counts=True, log_counting=None): """Factory method for bounter implementation. Args: size_mb (int): Desired memory footprint of the counter. need_iteration (Bool): With `True`, create a `HashTable` implementation which can iterate over inserted key/value pairs. With `False`, create a `CountMinSketch` implementation which performs better in limited-memory scenarios, but does not support iteration over elements. need_counts (Bool): With `True`, construct the structure normally. With `False`, ignore all remaining parameters and create a minimalistic cardinality counter based on hyperloglog which only takes 64KB memory. log_counting (int): Counting to use with `CountMinSketch` implementation. Accepted values are `None` (default counting with 32-bit integers), 1024 (16-bit), 8 (8-bit). See `CountMinSketch` documentation for details. Raise ValueError if not `None `and `need_iteration` is `True`. """ if not need_counts: return CardinalityEstimator() if size_mb is None: raise ValueError("Max size in MB must be provided.") if need_iteration: if log_counting: raise ValueError("Log counting is only supported with CMS implementation (need_iteration=False).") return HashTable(size_mb=size_mb) else: return CountMinSketch(size_mb=size_mb, log_counting=log_counting)
[ "def", "bounter", "(", "size_mb", "=", "None", ",", "need_iteration", "=", "True", ",", "need_counts", "=", "True", ",", "log_counting", "=", "None", ")", ":", "if", "not", "need_counts", ":", "return", "CardinalityEstimator", "(", ")", "if", "size_mb", "i...
Factory method for bounter implementation. Args: size_mb (int): Desired memory footprint of the counter. need_iteration (Bool): With `True`, create a `HashTable` implementation which can iterate over inserted key/value pairs. With `False`, create a `CountMinSketch` implementation which performs better in limited-memory scenarios, but does not support iteration over elements. need_counts (Bool): With `True`, construct the structure normally. With `False`, ignore all remaining parameters and create a minimalistic cardinality counter based on hyperloglog which only takes 64KB memory. log_counting (int): Counting to use with `CountMinSketch` implementation. Accepted values are `None` (default counting with 32-bit integers), 1024 (16-bit), 8 (8-bit). See `CountMinSketch` documentation for details. Raise ValueError if not `None `and `need_iteration` is `True`.
[ "Factory", "method", "for", "bounter", "implementation", "." ]
952a70ed6557391fc2d161bbf648184fa60e4240
https://github.com/RaRe-Technologies/bounter/blob/952a70ed6557391fc2d161bbf648184fa60e4240/bounter/bounter.py#L14-L39
train
208,955
sidecars/python-quickbooks
quickbooks/mixins.py
to_dict
def to_dict(obj, classkey=None): """ Recursively converts Python object into a dictionary """ if isinstance(obj, dict): data = {} for (k, v) in obj.items(): data[k] = to_dict(v, classkey) return data elif hasattr(obj, "_ast"): return to_dict(obj._ast()) elif hasattr(obj, "__iter__") and not isinstance(obj, str): return [to_dict(v, classkey) for v in obj] elif hasattr(obj, "__dict__"): if six.PY2: data = dict([(key, to_dict(value, classkey)) for key, value in obj.__dict__.iteritems() if not callable(value) and not key.startswith('_')]) else: data = dict([(key, to_dict(value, classkey)) for key, value in obj.__dict__.items() if not callable(value) and not key.startswith('_')]) if classkey is not None and hasattr(obj, "__class__"): data[classkey] = obj.__class__.__name__ return data else: return obj
python
def to_dict(obj, classkey=None): """ Recursively converts Python object into a dictionary """ if isinstance(obj, dict): data = {} for (k, v) in obj.items(): data[k] = to_dict(v, classkey) return data elif hasattr(obj, "_ast"): return to_dict(obj._ast()) elif hasattr(obj, "__iter__") and not isinstance(obj, str): return [to_dict(v, classkey) for v in obj] elif hasattr(obj, "__dict__"): if six.PY2: data = dict([(key, to_dict(value, classkey)) for key, value in obj.__dict__.iteritems() if not callable(value) and not key.startswith('_')]) else: data = dict([(key, to_dict(value, classkey)) for key, value in obj.__dict__.items() if not callable(value) and not key.startswith('_')]) if classkey is not None and hasattr(obj, "__class__"): data[classkey] = obj.__class__.__name__ return data else: return obj
[ "def", "to_dict", "(", "obj", ",", "classkey", "=", "None", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "data", "=", "{", "}", "for", "(", "k", ",", "v", ")", "in", "obj", ".", "items", "(", ")", ":", "data", "[", "k", ...
Recursively converts Python object into a dictionary
[ "Recursively", "converts", "Python", "object", "into", "a", "dictionary" ]
4cb2b6da46423bad8b32b85d87f9a97b698144fd
https://github.com/sidecars/python-quickbooks/blob/4cb2b6da46423bad8b32b85d87f9a97b698144fd/quickbooks/mixins.py#L55-L82
train
208,956
sidecars/python-quickbooks
quickbooks/mixins.py
ToJsonMixin.json_filter
def json_filter(self): """ filter out properties that have names starting with _ or properties that have a value of None """ return lambda obj: dict((k, v) for k, v in obj.__dict__.items() if not k.startswith('_') and getattr(obj, k) is not None)
python
def json_filter(self): """ filter out properties that have names starting with _ or properties that have a value of None """ return lambda obj: dict((k, v) for k, v in obj.__dict__.items() if not k.startswith('_') and getattr(obj, k) is not None)
[ "def", "json_filter", "(", "self", ")", ":", "return", "lambda", "obj", ":", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "obj", ".", "__dict__", ".", "items", "(", ")", "if", "not", "k", ".", "startswith", "(", "'_'", ")",...
filter out properties that have names starting with _ or properties that have a value of None
[ "filter", "out", "properties", "that", "have", "names", "starting", "with", "_", "or", "properties", "that", "have", "a", "value", "of", "None" ]
4cb2b6da46423bad8b32b85d87f9a97b698144fd
https://github.com/sidecars/python-quickbooks/blob/4cb2b6da46423bad8b32b85d87f9a97b698144fd/quickbooks/mixins.py#L12-L18
train
208,957
sidecars/python-quickbooks
quickbooks/client.py
QuickBooks.get_current_user
def get_current_user(self): """Get data from the current user endpoint""" url = self.current_user_url result = self.get(url) return result
python
def get_current_user(self): """Get data from the current user endpoint""" url = self.current_user_url result = self.get(url) return result
[ "def", "get_current_user", "(", "self", ")", ":", "url", "=", "self", ".", "current_user_url", "result", "=", "self", ".", "get", "(", "url", ")", "return", "result" ]
Get data from the current user endpoint
[ "Get", "data", "from", "the", "current", "user", "endpoint" ]
4cb2b6da46423bad8b32b85d87f9a97b698144fd
https://github.com/sidecars/python-quickbooks/blob/4cb2b6da46423bad8b32b85d87f9a97b698144fd/quickbooks/client.py#L123-L127
train
208,958
sidecars/python-quickbooks
quickbooks/client.py
QuickBooks.get_report
def get_report(self, report_type, qs=None): """Get data from the report endpoint""" if qs is None: qs = {} url = self.api_url + "/company/{0}/reports/{1}".format(self.company_id, report_type) result = self.get(url, params=qs) return result
python
def get_report(self, report_type, qs=None): """Get data from the report endpoint""" if qs is None: qs = {} url = self.api_url + "/company/{0}/reports/{1}".format(self.company_id, report_type) result = self.get(url, params=qs) return result
[ "def", "get_report", "(", "self", ",", "report_type", ",", "qs", "=", "None", ")", ":", "if", "qs", "is", "None", ":", "qs", "=", "{", "}", "url", "=", "self", ".", "api_url", "+", "\"/company/{0}/reports/{1}\"", ".", "format", "(", "self", ".", "com...
Get data from the report endpoint
[ "Get", "data", "from", "the", "report", "endpoint" ]
4cb2b6da46423bad8b32b85d87f9a97b698144fd
https://github.com/sidecars/python-quickbooks/blob/4cb2b6da46423bad8b32b85d87f9a97b698144fd/quickbooks/client.py#L129-L136
train
208,959
cogeotiff/rio-tiler
rio_tiler/mercator.py
_meters_per_pixel
def _meters_per_pixel(zoom, lat=0.0, tilesize=256): """ Return the pixel resolution for a given mercator tile zoom and lattitude. Parameters ---------- zoom: int Mercator zoom level lat: float, optional Latitude in decimal degree (default: 0) tilesize: int, optional Mercator tile size (default: 256). Returns ------- Pixel resolution in meters """ return (math.cos(lat * math.pi / 180.0) * 2 * math.pi * 6378137) / ( tilesize * 2 ** zoom )
python
def _meters_per_pixel(zoom, lat=0.0, tilesize=256): """ Return the pixel resolution for a given mercator tile zoom and lattitude. Parameters ---------- zoom: int Mercator zoom level lat: float, optional Latitude in decimal degree (default: 0) tilesize: int, optional Mercator tile size (default: 256). Returns ------- Pixel resolution in meters """ return (math.cos(lat * math.pi / 180.0) * 2 * math.pi * 6378137) / ( tilesize * 2 ** zoom )
[ "def", "_meters_per_pixel", "(", "zoom", ",", "lat", "=", "0.0", ",", "tilesize", "=", "256", ")", ":", "return", "(", "math", ".", "cos", "(", "lat", "*", "math", ".", "pi", "/", "180.0", ")", "*", "2", "*", "math", ".", "pi", "*", "6378137", ...
Return the pixel resolution for a given mercator tile zoom and lattitude. Parameters ---------- zoom: int Mercator zoom level lat: float, optional Latitude in decimal degree (default: 0) tilesize: int, optional Mercator tile size (default: 256). Returns ------- Pixel resolution in meters
[ "Return", "the", "pixel", "resolution", "for", "a", "given", "mercator", "tile", "zoom", "and", "lattitude", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/mercator.py#L7-L27
train
208,960
cogeotiff/rio-tiler
rio_tiler/mercator.py
zoom_for_pixelsize
def zoom_for_pixelsize(pixel_size, max_z=24, tilesize=256): """ Get mercator zoom level corresponding to a pixel resolution. Freely adapted from https://github.com/OSGeo/gdal/blob/b0dfc591929ebdbccd8a0557510c5efdb893b852/gdal/swig/python/scripts/gdal2tiles.py#L294 Parameters ---------- pixel_size: float Pixel size max_z: int, optional (default: 24) Max mercator zoom level allowed tilesize: int, optional Mercator tile size (default: 256). Returns ------- Mercator zoom level corresponding to the pixel resolution """ for z in range(max_z): if pixel_size > _meters_per_pixel(z, 0, tilesize=tilesize): return max(0, z - 1) # We don't want to scale up return max_z - 1
python
def zoom_for_pixelsize(pixel_size, max_z=24, tilesize=256): """ Get mercator zoom level corresponding to a pixel resolution. Freely adapted from https://github.com/OSGeo/gdal/blob/b0dfc591929ebdbccd8a0557510c5efdb893b852/gdal/swig/python/scripts/gdal2tiles.py#L294 Parameters ---------- pixel_size: float Pixel size max_z: int, optional (default: 24) Max mercator zoom level allowed tilesize: int, optional Mercator tile size (default: 256). Returns ------- Mercator zoom level corresponding to the pixel resolution """ for z in range(max_z): if pixel_size > _meters_per_pixel(z, 0, tilesize=tilesize): return max(0, z - 1) # We don't want to scale up return max_z - 1
[ "def", "zoom_for_pixelsize", "(", "pixel_size", ",", "max_z", "=", "24", ",", "tilesize", "=", "256", ")", ":", "for", "z", "in", "range", "(", "max_z", ")", ":", "if", "pixel_size", ">", "_meters_per_pixel", "(", "z", ",", "0", ",", "tilesize", "=", ...
Get mercator zoom level corresponding to a pixel resolution. Freely adapted from https://github.com/OSGeo/gdal/blob/b0dfc591929ebdbccd8a0557510c5efdb893b852/gdal/swig/python/scripts/gdal2tiles.py#L294 Parameters ---------- pixel_size: float Pixel size max_z: int, optional (default: 24) Max mercator zoom level allowed tilesize: int, optional Mercator tile size (default: 256). Returns ------- Mercator zoom level corresponding to the pixel resolution
[ "Get", "mercator", "zoom", "level", "corresponding", "to", "a", "pixel", "resolution", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/mercator.py#L30-L55
train
208,961
cogeotiff/rio-tiler
rio_tiler/main.py
metadata
def metadata(address, pmin=2, pmax=98, **kwargs): """ Return image bounds and band statistics. Attributes ---------- address : str or PathLike object A dataset path or URL. Will be opened in "r" mode. pmin : int, optional, (default: 2) Histogram minimum cut. pmax : int, optional, (default: 98) Histogram maximum cut. kwargs : optional These are passed to 'rio_tiler.utils.raster_get_stats' e.g: overview_level=2, dst_crs='epsg:4326' Returns ------- out : dict Dictionary with image bounds and bands statistics. """ info = {"address": address} info.update(utils.raster_get_stats(address, percentiles=(pmin, pmax), **kwargs)) return info
python
def metadata(address, pmin=2, pmax=98, **kwargs): """ Return image bounds and band statistics. Attributes ---------- address : str or PathLike object A dataset path or URL. Will be opened in "r" mode. pmin : int, optional, (default: 2) Histogram minimum cut. pmax : int, optional, (default: 98) Histogram maximum cut. kwargs : optional These are passed to 'rio_tiler.utils.raster_get_stats' e.g: overview_level=2, dst_crs='epsg:4326' Returns ------- out : dict Dictionary with image bounds and bands statistics. """ info = {"address": address} info.update(utils.raster_get_stats(address, percentiles=(pmin, pmax), **kwargs)) return info
[ "def", "metadata", "(", "address", ",", "pmin", "=", "2", ",", "pmax", "=", "98", ",", "*", "*", "kwargs", ")", ":", "info", "=", "{", "\"address\"", ":", "address", "}", "info", ".", "update", "(", "utils", ".", "raster_get_stats", "(", "address", ...
Return image bounds and band statistics. Attributes ---------- address : str or PathLike object A dataset path or URL. Will be opened in "r" mode. pmin : int, optional, (default: 2) Histogram minimum cut. pmax : int, optional, (default: 98) Histogram maximum cut. kwargs : optional These are passed to 'rio_tiler.utils.raster_get_stats' e.g: overview_level=2, dst_crs='epsg:4326' Returns ------- out : dict Dictionary with image bounds and bands statistics.
[ "Return", "image", "bounds", "and", "band", "statistics", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/main.py#L34-L58
train
208,962
cogeotiff/rio-tiler
rio_tiler/main.py
tile
def tile(address, tile_x, tile_y, tile_z, tilesize=256, **kwargs): """ Create mercator tile from any images. Attributes ---------- address : str file url. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. tilesize : int, optional (default: 256) Output image size. kwargs: dict, optional These will be passed to the 'rio_tiler.utils._tile_read' function. Returns ------- data : numpy ndarray mask: numpy array """ with rasterio.open(address) as src: wgs_bounds = transform_bounds( *[src.crs, "epsg:4326"] + list(src.bounds), densify_pts=21 ) if not utils.tile_exists(wgs_bounds, tile_z, tile_x, tile_y): raise TileOutsideBounds( "Tile {}/{}/{} is outside image bounds".format(tile_z, tile_x, tile_y) ) mercator_tile = mercantile.Tile(x=tile_x, y=tile_y, z=tile_z) tile_bounds = mercantile.xy_bounds(mercator_tile) return utils.tile_read(src, tile_bounds, tilesize, **kwargs)
python
def tile(address, tile_x, tile_y, tile_z, tilesize=256, **kwargs): """ Create mercator tile from any images. Attributes ---------- address : str file url. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. tilesize : int, optional (default: 256) Output image size. kwargs: dict, optional These will be passed to the 'rio_tiler.utils._tile_read' function. Returns ------- data : numpy ndarray mask: numpy array """ with rasterio.open(address) as src: wgs_bounds = transform_bounds( *[src.crs, "epsg:4326"] + list(src.bounds), densify_pts=21 ) if not utils.tile_exists(wgs_bounds, tile_z, tile_x, tile_y): raise TileOutsideBounds( "Tile {}/{}/{} is outside image bounds".format(tile_z, tile_x, tile_y) ) mercator_tile = mercantile.Tile(x=tile_x, y=tile_y, z=tile_z) tile_bounds = mercantile.xy_bounds(mercator_tile) return utils.tile_read(src, tile_bounds, tilesize, **kwargs)
[ "def", "tile", "(", "address", ",", "tile_x", ",", "tile_y", ",", "tile_z", ",", "tilesize", "=", "256", ",", "*", "*", "kwargs", ")", ":", "with", "rasterio", ".", "open", "(", "address", ")", "as", "src", ":", "wgs_bounds", "=", "transform_bounds", ...
Create mercator tile from any images. Attributes ---------- address : str file url. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. tilesize : int, optional (default: 256) Output image size. kwargs: dict, optional These will be passed to the 'rio_tiler.utils._tile_read' function. Returns ------- data : numpy ndarray mask: numpy array
[ "Create", "mercator", "tile", "from", "any", "images", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/main.py#L61-L98
train
208,963
cogeotiff/rio-tiler
rio_tiler/utils.py
_stats
def _stats(arr, percentiles=(2, 98), **kwargs): """ Calculate array statistics. Attributes ---------- arr: numpy ndarray Input array data to get the stats from. percentiles: tuple, optional Tuple of Min/Max percentiles to compute. kwargs: dict, optional These will be passed to the numpy.histogram function. Returns ------- dict numpy array statistics: percentiles, min, max, stdev, histogram e.g. { 'pc': [38, 147], 'min': 20, 'max': 180, 'std': 28.123562304138662, 'histogram': [ [1625, 219241, 28344, 15808, 12325, 10687, 8535, 7348, 4656, 1208], [20.0, 36.0, 52.0, 68.0, 84.0, 100.0, 116.0, 132.0, 148.0, 164.0, 180.0] ] } """ sample, edges = np.histogram(arr[~arr.mask], **kwargs) return { "pc": np.percentile(arr[~arr.mask], percentiles).astype(arr.dtype).tolist(), "min": arr.min().item(), "max": arr.max().item(), "std": arr.std().item(), "histogram": [sample.tolist(), edges.tolist()], }
python
def _stats(arr, percentiles=(2, 98), **kwargs): """ Calculate array statistics. Attributes ---------- arr: numpy ndarray Input array data to get the stats from. percentiles: tuple, optional Tuple of Min/Max percentiles to compute. kwargs: dict, optional These will be passed to the numpy.histogram function. Returns ------- dict numpy array statistics: percentiles, min, max, stdev, histogram e.g. { 'pc': [38, 147], 'min': 20, 'max': 180, 'std': 28.123562304138662, 'histogram': [ [1625, 219241, 28344, 15808, 12325, 10687, 8535, 7348, 4656, 1208], [20.0, 36.0, 52.0, 68.0, 84.0, 100.0, 116.0, 132.0, 148.0, 164.0, 180.0] ] } """ sample, edges = np.histogram(arr[~arr.mask], **kwargs) return { "pc": np.percentile(arr[~arr.mask], percentiles).astype(arr.dtype).tolist(), "min": arr.min().item(), "max": arr.max().item(), "std": arr.std().item(), "histogram": [sample.tolist(), edges.tolist()], }
[ "def", "_stats", "(", "arr", ",", "percentiles", "=", "(", "2", ",", "98", ")", ",", "*", "*", "kwargs", ")", ":", "sample", ",", "edges", "=", "np", ".", "histogram", "(", "arr", "[", "~", "arr", ".", "mask", "]", ",", "*", "*", "kwargs", ")...
Calculate array statistics. Attributes ---------- arr: numpy ndarray Input array data to get the stats from. percentiles: tuple, optional Tuple of Min/Max percentiles to compute. kwargs: dict, optional These will be passed to the numpy.histogram function. Returns ------- dict numpy array statistics: percentiles, min, max, stdev, histogram e.g. { 'pc': [38, 147], 'min': 20, 'max': 180, 'std': 28.123562304138662, 'histogram': [ [1625, 219241, 28344, 15808, 12325, 10687, 8535, 7348, 4656, 1208], [20.0, 36.0, 52.0, 68.0, 84.0, 100.0, 116.0, 132.0, 148.0, 164.0, 180.0] ] }
[ "Calculate", "array", "statistics", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L35-L72
train
208,964
cogeotiff/rio-tiler
rio_tiler/utils.py
raster_get_stats
def raster_get_stats( src_path, indexes=None, nodata=None, overview_level=None, max_size=1024, percentiles=(2, 98), dst_crs=CRS({"init": "EPSG:4326"}), histogram_bins=10, histogram_range=None, ): """ Retrieve dataset statistics. Attributes ---------- src_path : str or PathLike object A dataset path or URL. Will be opened in "r" mode. indexes : tuple, list, int, optional Dataset band indexes. nodata, int, optional Custom nodata value if not preset in dataset. overview_level : int, optional Overview (decimation) level to fetch. max_size: int, optional Maximum size of dataset to retrieve (will be used to calculate the overview level to fetch). percentiles : tulple, optional Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive (default: (2, 98)). dst_crs: CRS or dict Target coordinate reference system (default: EPSG:4326). histogram_bins: int, optional Defines the number of equal-width histogram bins (default: 10). histogram_range: tuple or list, optional The lower and upper range of the bins. If not provided, range is simply the min and max of the array. Returns ------- out : dict bounds, mercator zoom range, band descriptions and band statistics: (percentiles), min, max, stdev, histogram e.g. { 'bounds': { 'value': (145.72265625, 14.853515625, 145.810546875, 14.94140625), 'crs': '+init=EPSG:4326' }, 'minzoom': 8, 'maxzoom': 12, 'band_descriptions': [(1, 'red'), (2, 'green'), (3, 'blue'), (4, 'nir')] 'statistics': { 1: { 'pc': [38, 147], 'min': 20, 'max': 180, 'std': 28.123562304138662, 'histogram': [ [1625, 219241, 28344, 15808, 12325, 10687, 8535, 7348, 4656, 1208], [20.0, 36.0, 52.0, 68.0, 84.0, 100.0, 116.0, 132.0, 148.0, 164.0, 180.0] ] } ... 3: {...} 4: {...} } } """ if isinstance(indexes, int): indexes = [indexes] elif isinstance(indexes, tuple): indexes = list(indexes) with rasterio.open(src_path) as src_dst: levels = src_dst.overviews(1) width = src_dst.width height = src_dst.height indexes = indexes if indexes else src_dst.indexes nodata = nodata if nodata is not None else src_dst.nodata bounds = transform_bounds( *[src_dst.crs, dst_crs] + list(src_dst.bounds), densify_pts=21 ) minzoom, maxzoom = get_zooms(src_dst) def _get_descr(ix): """Return band description.""" name = src_dst.descriptions[ix - 1] if not name: name = "band{}".format(ix) return name band_descriptions = [(ix, _get_descr(ix)) for ix in indexes] if len(levels): if overview_level: decim = levels[overview_level] else: # determine which zoom level to read for ii, decim in enumerate(levels): if max(width // decim, height // decim) < max_size: break else: decim = 1 warnings.warn( "Dataset has no overviews, reading the full dataset", NoOverviewWarning ) out_shape = (len(indexes), height // decim, width // decim) vrt_params = dict(add_alpha=True, resampling=Resampling.bilinear) if has_alpha_band(src_dst): vrt_params.update(dict(add_alpha=False)) if nodata is not None: vrt_params.update(dict(nodata=nodata, add_alpha=False, src_nodata=nodata)) with WarpedVRT(src_dst, **vrt_params) as vrt: arr = vrt.read(out_shape=out_shape, indexes=indexes, masked=True) params = {} if histogram_bins: params.update(dict(bins=histogram_bins)) if histogram_range: params.update(dict(range=histogram_range)) stats = { indexes[b]: _stats(arr[b], percentiles=percentiles, **params) for b in range(arr.shape[0]) if vrt.colorinterp[b] != ColorInterp.alpha } return { "bounds": { "value": bounds, "crs": dst_crs.to_string() if isinstance(dst_crs, CRS) else dst_crs, }, "minzoom": minzoom, "maxzoom": maxzoom, "band_descriptions": band_descriptions, "statistics": stats, }
python
def raster_get_stats( src_path, indexes=None, nodata=None, overview_level=None, max_size=1024, percentiles=(2, 98), dst_crs=CRS({"init": "EPSG:4326"}), histogram_bins=10, histogram_range=None, ): """ Retrieve dataset statistics. Attributes ---------- src_path : str or PathLike object A dataset path or URL. Will be opened in "r" mode. indexes : tuple, list, int, optional Dataset band indexes. nodata, int, optional Custom nodata value if not preset in dataset. overview_level : int, optional Overview (decimation) level to fetch. max_size: int, optional Maximum size of dataset to retrieve (will be used to calculate the overview level to fetch). percentiles : tulple, optional Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive (default: (2, 98)). dst_crs: CRS or dict Target coordinate reference system (default: EPSG:4326). histogram_bins: int, optional Defines the number of equal-width histogram bins (default: 10). histogram_range: tuple or list, optional The lower and upper range of the bins. If not provided, range is simply the min and max of the array. Returns ------- out : dict bounds, mercator zoom range, band descriptions and band statistics: (percentiles), min, max, stdev, histogram e.g. { 'bounds': { 'value': (145.72265625, 14.853515625, 145.810546875, 14.94140625), 'crs': '+init=EPSG:4326' }, 'minzoom': 8, 'maxzoom': 12, 'band_descriptions': [(1, 'red'), (2, 'green'), (3, 'blue'), (4, 'nir')] 'statistics': { 1: { 'pc': [38, 147], 'min': 20, 'max': 180, 'std': 28.123562304138662, 'histogram': [ [1625, 219241, 28344, 15808, 12325, 10687, 8535, 7348, 4656, 1208], [20.0, 36.0, 52.0, 68.0, 84.0, 100.0, 116.0, 132.0, 148.0, 164.0, 180.0] ] } ... 3: {...} 4: {...} } } """ if isinstance(indexes, int): indexes = [indexes] elif isinstance(indexes, tuple): indexes = list(indexes) with rasterio.open(src_path) as src_dst: levels = src_dst.overviews(1) width = src_dst.width height = src_dst.height indexes = indexes if indexes else src_dst.indexes nodata = nodata if nodata is not None else src_dst.nodata bounds = transform_bounds( *[src_dst.crs, dst_crs] + list(src_dst.bounds), densify_pts=21 ) minzoom, maxzoom = get_zooms(src_dst) def _get_descr(ix): """Return band description.""" name = src_dst.descriptions[ix - 1] if not name: name = "band{}".format(ix) return name band_descriptions = [(ix, _get_descr(ix)) for ix in indexes] if len(levels): if overview_level: decim = levels[overview_level] else: # determine which zoom level to read for ii, decim in enumerate(levels): if max(width // decim, height // decim) < max_size: break else: decim = 1 warnings.warn( "Dataset has no overviews, reading the full dataset", NoOverviewWarning ) out_shape = (len(indexes), height // decim, width // decim) vrt_params = dict(add_alpha=True, resampling=Resampling.bilinear) if has_alpha_band(src_dst): vrt_params.update(dict(add_alpha=False)) if nodata is not None: vrt_params.update(dict(nodata=nodata, add_alpha=False, src_nodata=nodata)) with WarpedVRT(src_dst, **vrt_params) as vrt: arr = vrt.read(out_shape=out_shape, indexes=indexes, masked=True) params = {} if histogram_bins: params.update(dict(bins=histogram_bins)) if histogram_range: params.update(dict(range=histogram_range)) stats = { indexes[b]: _stats(arr[b], percentiles=percentiles, **params) for b in range(arr.shape[0]) if vrt.colorinterp[b] != ColorInterp.alpha } return { "bounds": { "value": bounds, "crs": dst_crs.to_string() if isinstance(dst_crs, CRS) else dst_crs, }, "minzoom": minzoom, "maxzoom": maxzoom, "band_descriptions": band_descriptions, "statistics": stats, }
[ "def", "raster_get_stats", "(", "src_path", ",", "indexes", "=", "None", ",", "nodata", "=", "None", ",", "overview_level", "=", "None", ",", "max_size", "=", "1024", ",", "percentiles", "=", "(", "2", ",", "98", ")", ",", "dst_crs", "=", "CRS", "(", ...
Retrieve dataset statistics. Attributes ---------- src_path : str or PathLike object A dataset path or URL. Will be opened in "r" mode. indexes : tuple, list, int, optional Dataset band indexes. nodata, int, optional Custom nodata value if not preset in dataset. overview_level : int, optional Overview (decimation) level to fetch. max_size: int, optional Maximum size of dataset to retrieve (will be used to calculate the overview level to fetch). percentiles : tulple, optional Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive (default: (2, 98)). dst_crs: CRS or dict Target coordinate reference system (default: EPSG:4326). histogram_bins: int, optional Defines the number of equal-width histogram bins (default: 10). histogram_range: tuple or list, optional The lower and upper range of the bins. If not provided, range is simply the min and max of the array. Returns ------- out : dict bounds, mercator zoom range, band descriptions and band statistics: (percentiles), min, max, stdev, histogram e.g. { 'bounds': { 'value': (145.72265625, 14.853515625, 145.810546875, 14.94140625), 'crs': '+init=EPSG:4326' }, 'minzoom': 8, 'maxzoom': 12, 'band_descriptions': [(1, 'red'), (2, 'green'), (3, 'blue'), (4, 'nir')] 'statistics': { 1: { 'pc': [38, 147], 'min': 20, 'max': 180, 'std': 28.123562304138662, 'histogram': [ [1625, 219241, 28344, 15808, 12325, 10687, 8535, 7348, 4656, 1208], [20.0, 36.0, 52.0, 68.0, 84.0, 100.0, 116.0, 132.0, 148.0, 164.0, 180.0] ] } ... 3: {...} 4: {...} } }
[ "Retrieve", "dataset", "statistics", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L75-L218
train
208,965
cogeotiff/rio-tiler
rio_tiler/utils.py
get_vrt_transform
def get_vrt_transform(src_dst, bounds, bounds_crs="epsg:3857"): """ Calculate VRT transform. Attributes ---------- src_dst : rasterio.io.DatasetReader Rasterio io.DatasetReader object bounds : list Bounds (left, bottom, right, top) bounds_crs : str Coordinate reference system string (default "epsg:3857") Returns ------- vrt_transform: Affine Output affine transformation matrix vrt_width, vrt_height: int Output dimensions """ dst_transform, _, _ = calculate_default_transform( src_dst.crs, bounds_crs, src_dst.width, src_dst.height, *src_dst.bounds ) w, s, e, n = bounds vrt_width = math.ceil((e - w) / dst_transform.a) vrt_height = math.ceil((s - n) / dst_transform.e) vrt_transform = transform.from_bounds(w, s, e, n, vrt_width, vrt_height) return vrt_transform, vrt_width, vrt_height
python
def get_vrt_transform(src_dst, bounds, bounds_crs="epsg:3857"): """ Calculate VRT transform. Attributes ---------- src_dst : rasterio.io.DatasetReader Rasterio io.DatasetReader object bounds : list Bounds (left, bottom, right, top) bounds_crs : str Coordinate reference system string (default "epsg:3857") Returns ------- vrt_transform: Affine Output affine transformation matrix vrt_width, vrt_height: int Output dimensions """ dst_transform, _, _ = calculate_default_transform( src_dst.crs, bounds_crs, src_dst.width, src_dst.height, *src_dst.bounds ) w, s, e, n = bounds vrt_width = math.ceil((e - w) / dst_transform.a) vrt_height = math.ceil((s - n) / dst_transform.e) vrt_transform = transform.from_bounds(w, s, e, n, vrt_width, vrt_height) return vrt_transform, vrt_width, vrt_height
[ "def", "get_vrt_transform", "(", "src_dst", ",", "bounds", ",", "bounds_crs", "=", "\"epsg:3857\"", ")", ":", "dst_transform", ",", "_", ",", "_", "=", "calculate_default_transform", "(", "src_dst", ".", "crs", ",", "bounds_crs", ",", "src_dst", ".", "width", ...
Calculate VRT transform. Attributes ---------- src_dst : rasterio.io.DatasetReader Rasterio io.DatasetReader object bounds : list Bounds (left, bottom, right, top) bounds_crs : str Coordinate reference system string (default "epsg:3857") Returns ------- vrt_transform: Affine Output affine transformation matrix vrt_width, vrt_height: int Output dimensions
[ "Calculate", "VRT", "transform", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L221-L251
train
208,966
cogeotiff/rio-tiler
rio_tiler/utils.py
has_alpha_band
def has_alpha_band(src_dst): """Check for alpha band or mask in source.""" if ( any([MaskFlags.alpha in flags for flags in src_dst.mask_flag_enums]) or ColorInterp.alpha in src_dst.colorinterp ): return True return False
python
def has_alpha_band(src_dst): """Check for alpha band or mask in source.""" if ( any([MaskFlags.alpha in flags for flags in src_dst.mask_flag_enums]) or ColorInterp.alpha in src_dst.colorinterp ): return True return False
[ "def", "has_alpha_band", "(", "src_dst", ")", ":", "if", "(", "any", "(", "[", "MaskFlags", ".", "alpha", "in", "flags", "for", "flags", "in", "src_dst", ".", "mask_flag_enums", "]", ")", "or", "ColorInterp", ".", "alpha", "in", "src_dst", ".", "colorint...
Check for alpha band or mask in source.
[ "Check", "for", "alpha", "band", "or", "mask", "in", "source", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L254-L261
train
208,967
cogeotiff/rio-tiler
rio_tiler/utils.py
linear_rescale
def linear_rescale(image, in_range=(0, 1), out_range=(1, 255)): """ Linear rescaling. Attributes ---------- image : numpy ndarray Image array to rescale. in_range : list, int, optional, (default: [0,1]) Image min/max value to rescale. out_range : list, int, optional, (default: [1,255]) output min/max bounds to rescale to. Returns ------- out : numpy ndarray returns rescaled image array. """ imin, imax = in_range omin, omax = out_range image = np.clip(image, imin, imax) - imin image = image / np.float(imax - imin) return image * (omax - omin) + omin
python
def linear_rescale(image, in_range=(0, 1), out_range=(1, 255)): """ Linear rescaling. Attributes ---------- image : numpy ndarray Image array to rescale. in_range : list, int, optional, (default: [0,1]) Image min/max value to rescale. out_range : list, int, optional, (default: [1,255]) output min/max bounds to rescale to. Returns ------- out : numpy ndarray returns rescaled image array. """ imin, imax = in_range omin, omax = out_range image = np.clip(image, imin, imax) - imin image = image / np.float(imax - imin) return image * (omax - omin) + omin
[ "def", "linear_rescale", "(", "image", ",", "in_range", "=", "(", "0", ",", "1", ")", ",", "out_range", "=", "(", "1", ",", "255", ")", ")", ":", "imin", ",", "imax", "=", "in_range", "omin", ",", "omax", "=", "out_range", "image", "=", "np", "."...
Linear rescaling. Attributes ---------- image : numpy ndarray Image array to rescale. in_range : list, int, optional, (default: [0,1]) Image min/max value to rescale. out_range : list, int, optional, (default: [1,255]) output min/max bounds to rescale to. Returns ------- out : numpy ndarray returns rescaled image array.
[ "Linear", "rescaling", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L352-L375
train
208,968
cogeotiff/rio-tiler
rio_tiler/utils.py
tile_exists
def tile_exists(bounds, tile_z, tile_x, tile_y): """ Check if a mercatile tile is inside a given bounds. Attributes ---------- bounds : list WGS84 bounds (left, bottom, right, top). x : int Mercator tile Y index. y : int Mercator tile Y index. z : int Mercator tile ZOOM level. Returns ------- out : boolean if True, the z-x-y mercator tile in inside the bounds. """ mintile = mercantile.tile(bounds[0], bounds[3], tile_z) maxtile = mercantile.tile(bounds[2], bounds[1], tile_z) return ( (tile_x <= maxtile.x + 1) and (tile_x >= mintile.x) and (tile_y <= maxtile.y + 1) and (tile_y >= mintile.y) )
python
def tile_exists(bounds, tile_z, tile_x, tile_y): """ Check if a mercatile tile is inside a given bounds. Attributes ---------- bounds : list WGS84 bounds (left, bottom, right, top). x : int Mercator tile Y index. y : int Mercator tile Y index. z : int Mercator tile ZOOM level. Returns ------- out : boolean if True, the z-x-y mercator tile in inside the bounds. """ mintile = mercantile.tile(bounds[0], bounds[3], tile_z) maxtile = mercantile.tile(bounds[2], bounds[1], tile_z) return ( (tile_x <= maxtile.x + 1) and (tile_x >= mintile.x) and (tile_y <= maxtile.y + 1) and (tile_y >= mintile.y) )
[ "def", "tile_exists", "(", "bounds", ",", "tile_z", ",", "tile_x", ",", "tile_y", ")", ":", "mintile", "=", "mercantile", ".", "tile", "(", "bounds", "[", "0", "]", ",", "bounds", "[", "3", "]", ",", "tile_z", ")", "maxtile", "=", "mercantile", ".", ...
Check if a mercatile tile is inside a given bounds. Attributes ---------- bounds : list WGS84 bounds (left, bottom, right, top). x : int Mercator tile Y index. y : int Mercator tile Y index. z : int Mercator tile ZOOM level. Returns ------- out : boolean if True, the z-x-y mercator tile in inside the bounds.
[ "Check", "if", "a", "mercatile", "tile", "is", "inside", "a", "given", "bounds", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L378-L407
train
208,969
cogeotiff/rio-tiler
rio_tiler/utils.py
_apply_discrete_colormap
def _apply_discrete_colormap(arr, cmap): """ Apply discrete colormap. Attributes ---------- arr : numpy.ndarray 1D image array to convert. color_map: dict Discrete ColorMap dictionary e.g: { 1: [255, 255, 255], 2: [255, 0, 0] } Returns ------- arr: numpy.ndarray """ res = np.zeros((arr.shape[1], arr.shape[2], 3), dtype=np.uint8) for k, v in cmap.items(): res[arr[0] == k] = v return np.transpose(res, [2, 0, 1])
python
def _apply_discrete_colormap(arr, cmap): """ Apply discrete colormap. Attributes ---------- arr : numpy.ndarray 1D image array to convert. color_map: dict Discrete ColorMap dictionary e.g: { 1: [255, 255, 255], 2: [255, 0, 0] } Returns ------- arr: numpy.ndarray """ res = np.zeros((arr.shape[1], arr.shape[2], 3), dtype=np.uint8) for k, v in cmap.items(): res[arr[0] == k] = v return np.transpose(res, [2, 0, 1])
[ "def", "_apply_discrete_colormap", "(", "arr", ",", "cmap", ")", ":", "res", "=", "np", ".", "zeros", "(", "(", "arr", ".", "shape", "[", "1", "]", ",", "arr", ".", "shape", "[", "2", "]", ",", "3", ")", ",", "dtype", "=", "np", ".", "uint8", ...
Apply discrete colormap. Attributes ---------- arr : numpy.ndarray 1D image array to convert. color_map: dict Discrete ColorMap dictionary e.g: { 1: [255, 255, 255], 2: [255, 0, 0] } Returns ------- arr: numpy.ndarray
[ "Apply", "discrete", "colormap", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L410-L434
train
208,970
cogeotiff/rio-tiler
rio_tiler/utils.py
array_to_image
def array_to_image( arr, mask=None, img_format="png", color_map=None, **creation_options ): """ Translate numpy ndarray to image buffer using GDAL. Usage ----- tile, mask = rio_tiler.utils.tile_read(......) with open('test.jpg', 'wb') as f: f.write(array_to_image(tile, mask, img_format="jpeg")) Attributes ---------- arr : numpy ndarray Image array to encode. mask: numpy ndarray, optional Mask array img_format: str, optional Image format to return (default: 'png'). List of supported format by GDAL: https://www.gdal.org/formats_list.html color_map: numpy.ndarray or dict, optional color_map can be either a (256, 3) array or RGB triplet (e.g. [[255, 255, 255],...]) mapping each 1D pixel value rescaled from 0 to 255 OR it can be a dictionary of discrete values (e.g. { 1.3: [255, 255, 255], 2.5: [255, 0, 0]}) mapping any pixel value to a triplet creation_options: dict, optional Image driver creation options to pass to GDAL Returns ------- bytes """ img_format = img_format.lower() if len(arr.shape) < 3: arr = np.expand_dims(arr, axis=0) if color_map is not None and isinstance(color_map, dict): arr = _apply_discrete_colormap(arr, color_map) elif color_map is not None: arr = np.transpose(color_map[arr][0], [2, 0, 1]).astype(np.uint8) # WEBP doesn't support 1band dataset so we must hack to create a RGB dataset if img_format == "webp" and arr.shape[0] == 1: arr = np.repeat(arr, 3, axis=0) if mask is not None and img_format != "jpeg": nbands = arr.shape[0] + 1 else: nbands = arr.shape[0] output_profile = dict( driver=img_format, dtype=arr.dtype, count=nbands, height=arr.shape[1], width=arr.shape[2], ) output_profile.update(creation_options) with MemoryFile() as memfile: with memfile.open(**output_profile) as dst: dst.write(arr, indexes=list(range(1, arr.shape[0] + 1))) # Use Mask as an alpha band if mask is not None and img_format != "jpeg": dst.write(mask.astype(arr.dtype), indexes=nbands) return memfile.read()
python
def array_to_image( arr, mask=None, img_format="png", color_map=None, **creation_options ): """ Translate numpy ndarray to image buffer using GDAL. Usage ----- tile, mask = rio_tiler.utils.tile_read(......) with open('test.jpg', 'wb') as f: f.write(array_to_image(tile, mask, img_format="jpeg")) Attributes ---------- arr : numpy ndarray Image array to encode. mask: numpy ndarray, optional Mask array img_format: str, optional Image format to return (default: 'png'). List of supported format by GDAL: https://www.gdal.org/formats_list.html color_map: numpy.ndarray or dict, optional color_map can be either a (256, 3) array or RGB triplet (e.g. [[255, 255, 255],...]) mapping each 1D pixel value rescaled from 0 to 255 OR it can be a dictionary of discrete values (e.g. { 1.3: [255, 255, 255], 2.5: [255, 0, 0]}) mapping any pixel value to a triplet creation_options: dict, optional Image driver creation options to pass to GDAL Returns ------- bytes """ img_format = img_format.lower() if len(arr.shape) < 3: arr = np.expand_dims(arr, axis=0) if color_map is not None and isinstance(color_map, dict): arr = _apply_discrete_colormap(arr, color_map) elif color_map is not None: arr = np.transpose(color_map[arr][0], [2, 0, 1]).astype(np.uint8) # WEBP doesn't support 1band dataset so we must hack to create a RGB dataset if img_format == "webp" and arr.shape[0] == 1: arr = np.repeat(arr, 3, axis=0) if mask is not None and img_format != "jpeg": nbands = arr.shape[0] + 1 else: nbands = arr.shape[0] output_profile = dict( driver=img_format, dtype=arr.dtype, count=nbands, height=arr.shape[1], width=arr.shape[2], ) output_profile.update(creation_options) with MemoryFile() as memfile: with memfile.open(**output_profile) as dst: dst.write(arr, indexes=list(range(1, arr.shape[0] + 1))) # Use Mask as an alpha band if mask is not None and img_format != "jpeg": dst.write(mask.astype(arr.dtype), indexes=nbands) return memfile.read()
[ "def", "array_to_image", "(", "arr", ",", "mask", "=", "None", ",", "img_format", "=", "\"png\"", ",", "color_map", "=", "None", ",", "*", "*", "creation_options", ")", ":", "img_format", "=", "img_format", ".", "lower", "(", ")", "if", "len", "(", "ar...
Translate numpy ndarray to image buffer using GDAL. Usage ----- tile, mask = rio_tiler.utils.tile_read(......) with open('test.jpg', 'wb') as f: f.write(array_to_image(tile, mask, img_format="jpeg")) Attributes ---------- arr : numpy ndarray Image array to encode. mask: numpy ndarray, optional Mask array img_format: str, optional Image format to return (default: 'png'). List of supported format by GDAL: https://www.gdal.org/formats_list.html color_map: numpy.ndarray or dict, optional color_map can be either a (256, 3) array or RGB triplet (e.g. [[255, 255, 255],...]) mapping each 1D pixel value rescaled from 0 to 255 OR it can be a dictionary of discrete values (e.g. { 1.3: [255, 255, 255], 2.5: [255, 0, 0]}) mapping any pixel value to a triplet creation_options: dict, optional Image driver creation options to pass to GDAL Returns ------- bytes
[ "Translate", "numpy", "ndarray", "to", "image", "buffer", "using", "GDAL", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L437-L509
train
208,971
cogeotiff/rio-tiler
rio_tiler/utils.py
get_colormap
def get_colormap(name="cfastie", format="pil"): """ Return Pillow or GDAL compatible colormap array. Attributes ---------- name : str, optional Colormap name (default: cfastie) format: str, optional Compatiblity library, should be "pil" or "gdal" (default: pil). Returns ------- colormap : list or numpy.array Color map list in a Pillow friendly format more info: http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#PIL.Image.Image.putpalette or Color map array in GDAL friendly format """ cmap_file = os.path.join(os.path.dirname(__file__), "cmap", "{0}.txt".format(name)) with open(cmap_file) as cmap: lines = cmap.read().splitlines() colormap = [ list(map(int, line.split())) for line in lines if not line.startswith("#") ][1:] cmap = list(np.array(colormap).flatten()) if format.lower() == "pil": return cmap elif format.lower() == "gdal": return np.array(list(_chunks(cmap, 3))) else: raise Exception("Unsupported {} colormap format".format(format))
python
def get_colormap(name="cfastie", format="pil"): """ Return Pillow or GDAL compatible colormap array. Attributes ---------- name : str, optional Colormap name (default: cfastie) format: str, optional Compatiblity library, should be "pil" or "gdal" (default: pil). Returns ------- colormap : list or numpy.array Color map list in a Pillow friendly format more info: http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#PIL.Image.Image.putpalette or Color map array in GDAL friendly format """ cmap_file = os.path.join(os.path.dirname(__file__), "cmap", "{0}.txt".format(name)) with open(cmap_file) as cmap: lines = cmap.read().splitlines() colormap = [ list(map(int, line.split())) for line in lines if not line.startswith("#") ][1:] cmap = list(np.array(colormap).flatten()) if format.lower() == "pil": return cmap elif format.lower() == "gdal": return np.array(list(_chunks(cmap, 3))) else: raise Exception("Unsupported {} colormap format".format(format))
[ "def", "get_colormap", "(", "name", "=", "\"cfastie\"", ",", "format", "=", "\"pil\"", ")", ":", "cmap_file", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"cmap\"", ",", "\"{0}.txt\"", ".", ...
Return Pillow or GDAL compatible colormap array. Attributes ---------- name : str, optional Colormap name (default: cfastie) format: str, optional Compatiblity library, should be "pil" or "gdal" (default: pil). Returns ------- colormap : list or numpy.array Color map list in a Pillow friendly format more info: http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#PIL.Image.Image.putpalette or Color map array in GDAL friendly format
[ "Return", "Pillow", "or", "GDAL", "compatible", "colormap", "array", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L512-L545
train
208,972
cogeotiff/rio-tiler
rio_tiler/utils.py
mapzen_elevation_rgb
def mapzen_elevation_rgb(arr): """ Encode elevation value to RGB values compatible with Mapzen tangram. Attributes ---------- arr : numpy ndarray Image array to encode. Returns ------- out : numpy ndarray RGB array (3, h, w) """ arr = np.clip(arr + 32768.0, 0.0, 65535.0) r = arr / 256 g = arr % 256 b = (arr * 256) % 256 return np.stack([r, g, b]).astype(np.uint8)
python
def mapzen_elevation_rgb(arr): """ Encode elevation value to RGB values compatible with Mapzen tangram. Attributes ---------- arr : numpy ndarray Image array to encode. Returns ------- out : numpy ndarray RGB array (3, h, w) """ arr = np.clip(arr + 32768.0, 0.0, 65535.0) r = arr / 256 g = arr % 256 b = (arr * 256) % 256 return np.stack([r, g, b]).astype(np.uint8)
[ "def", "mapzen_elevation_rgb", "(", "arr", ")", ":", "arr", "=", "np", ".", "clip", "(", "arr", "+", "32768.0", ",", "0.0", ",", "65535.0", ")", "r", "=", "arr", "/", "256", "g", "=", "arr", "%", "256", "b", "=", "(", "arr", "*", "256", ")", ...
Encode elevation value to RGB values compatible with Mapzen tangram. Attributes ---------- arr : numpy ndarray Image array to encode. Returns ------- out : numpy ndarray RGB array (3, h, w)
[ "Encode", "elevation", "value", "to", "RGB", "values", "compatible", "with", "Mapzen", "tangram", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L548-L567
train
208,973
cogeotiff/rio-tiler
rio_tiler/utils.py
expression
def expression(sceneid, tile_x, tile_y, tile_z, expr=None, **kwargs): """ Apply expression on data. Attributes ---------- sceneid : str Landsat id, Sentinel id, CBERS ids or file url. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. expr : str, required Expression to apply (e.g '(B5+B4)/(B5-B4)') Band name should start with 'B'. Returns ------- out : ndarray Returns processed pixel value. """ if not expr: raise Exception("Missing expression") bands_names = tuple(set(re.findall(r"b(?P<bands>[0-9A]{1,2})", expr))) rgb = expr.split(",") if sceneid.startswith("L"): from rio_tiler.landsat8 import tile as l8_tile arr, mask = l8_tile( sceneid, tile_x, tile_y, tile_z, bands=bands_names, **kwargs ) elif sceneid.startswith("S2"): from rio_tiler.sentinel2 import tile as s2_tile arr, mask = s2_tile( sceneid, tile_x, tile_y, tile_z, bands=bands_names, **kwargs ) elif sceneid.startswith("CBERS"): from rio_tiler.cbers import tile as cbers_tile arr, mask = cbers_tile( sceneid, tile_x, tile_y, tile_z, bands=bands_names, **kwargs ) else: from rio_tiler.main import tile as main_tile bands = tuple(map(int, bands_names)) arr, mask = main_tile(sceneid, tile_x, tile_y, tile_z, indexes=bands, **kwargs) ctx = {} for bdx, b in enumerate(bands_names): ctx["b{}".format(b)] = arr[bdx] return ( np.array( [np.nan_to_num(ne.evaluate(bloc.strip(), local_dict=ctx)) for bloc in rgb] ), mask, )
python
def expression(sceneid, tile_x, tile_y, tile_z, expr=None, **kwargs): """ Apply expression on data. Attributes ---------- sceneid : str Landsat id, Sentinel id, CBERS ids or file url. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. expr : str, required Expression to apply (e.g '(B5+B4)/(B5-B4)') Band name should start with 'B'. Returns ------- out : ndarray Returns processed pixel value. """ if not expr: raise Exception("Missing expression") bands_names = tuple(set(re.findall(r"b(?P<bands>[0-9A]{1,2})", expr))) rgb = expr.split(",") if sceneid.startswith("L"): from rio_tiler.landsat8 import tile as l8_tile arr, mask = l8_tile( sceneid, tile_x, tile_y, tile_z, bands=bands_names, **kwargs ) elif sceneid.startswith("S2"): from rio_tiler.sentinel2 import tile as s2_tile arr, mask = s2_tile( sceneid, tile_x, tile_y, tile_z, bands=bands_names, **kwargs ) elif sceneid.startswith("CBERS"): from rio_tiler.cbers import tile as cbers_tile arr, mask = cbers_tile( sceneid, tile_x, tile_y, tile_z, bands=bands_names, **kwargs ) else: from rio_tiler.main import tile as main_tile bands = tuple(map(int, bands_names)) arr, mask = main_tile(sceneid, tile_x, tile_y, tile_z, indexes=bands, **kwargs) ctx = {} for bdx, b in enumerate(bands_names): ctx["b{}".format(b)] = arr[bdx] return ( np.array( [np.nan_to_num(ne.evaluate(bloc.strip(), local_dict=ctx)) for bloc in rgb] ), mask, )
[ "def", "expression", "(", "sceneid", ",", "tile_x", ",", "tile_y", ",", "tile_z", ",", "expr", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "expr", ":", "raise", "Exception", "(", "\"Missing expression\"", ")", "bands_names", "=", "tuple"...
Apply expression on data. Attributes ---------- sceneid : str Landsat id, Sentinel id, CBERS ids or file url. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. expr : str, required Expression to apply (e.g '(B5+B4)/(B5-B4)') Band name should start with 'B'. Returns ------- out : ndarray Returns processed pixel value.
[ "Apply", "expression", "on", "data", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/utils.py#L570-L634
train
208,974
cogeotiff/rio-tiler
rio_tiler/sentinel2.py
_sentinel_parse_scene_id
def _sentinel_parse_scene_id(sceneid): """Parse Sentinel-2 scene id. Attributes ---------- sceneid : str Sentinel-2 sceneid. Returns ------- out : dict dictionary with metadata constructed from the sceneid. e.g: _sentinel_parse_scene_id('S2A_tile_20170323_07SNC_0') { "acquisitionDay": "23", "acquisitionMonth": "03", "acquisitionYear": "2017", "key": "tiles/7/S/NC/2017/3/23/0", "lat": "S", "num": "0", "satellite": "A", "scene": "S2A_tile_20170323_07SNC_0", "sensor": "2", "sq": "NC", "utm": "07", } """ if not re.match("^S2[AB]_tile_[0-9]{8}_[0-9]{2}[A-Z]{3}_[0-9]$", sceneid): raise InvalidSentinelSceneId("Could not match {}".format(sceneid)) sentinel_pattern = ( r"^S" r"(?P<sensor>\w{1})" r"(?P<satellite>[AB]{1})" r"_tile_" r"(?P<acquisitionYear>[0-9]{4})" r"(?P<acquisitionMonth>[0-9]{2})" r"(?P<acquisitionDay>[0-9]{2})" r"_" r"(?P<utm>[0-9]{2})" r"(?P<lat>\w{1})" r"(?P<sq>\w{2})" r"_" r"(?P<num>[0-9]{1})$" ) meta = None match = re.match(sentinel_pattern, sceneid, re.IGNORECASE) if match: meta = match.groupdict() utm_zone = meta["utm"].lstrip("0") grid_square = meta["sq"] latitude_band = meta["lat"] year = meta["acquisitionYear"] month = meta["acquisitionMonth"].lstrip("0") day = meta["acquisitionDay"].lstrip("0") img_num = meta["num"] meta["key"] = "tiles/{}/{}/{}/{}/{}/{}/{}".format( utm_zone, latitude_band, grid_square, year, month, day, img_num ) meta["scene"] = sceneid return meta
python
def _sentinel_parse_scene_id(sceneid): """Parse Sentinel-2 scene id. Attributes ---------- sceneid : str Sentinel-2 sceneid. Returns ------- out : dict dictionary with metadata constructed from the sceneid. e.g: _sentinel_parse_scene_id('S2A_tile_20170323_07SNC_0') { "acquisitionDay": "23", "acquisitionMonth": "03", "acquisitionYear": "2017", "key": "tiles/7/S/NC/2017/3/23/0", "lat": "S", "num": "0", "satellite": "A", "scene": "S2A_tile_20170323_07SNC_0", "sensor": "2", "sq": "NC", "utm": "07", } """ if not re.match("^S2[AB]_tile_[0-9]{8}_[0-9]{2}[A-Z]{3}_[0-9]$", sceneid): raise InvalidSentinelSceneId("Could not match {}".format(sceneid)) sentinel_pattern = ( r"^S" r"(?P<sensor>\w{1})" r"(?P<satellite>[AB]{1})" r"_tile_" r"(?P<acquisitionYear>[0-9]{4})" r"(?P<acquisitionMonth>[0-9]{2})" r"(?P<acquisitionDay>[0-9]{2})" r"_" r"(?P<utm>[0-9]{2})" r"(?P<lat>\w{1})" r"(?P<sq>\w{2})" r"_" r"(?P<num>[0-9]{1})$" ) meta = None match = re.match(sentinel_pattern, sceneid, re.IGNORECASE) if match: meta = match.groupdict() utm_zone = meta["utm"].lstrip("0") grid_square = meta["sq"] latitude_band = meta["lat"] year = meta["acquisitionYear"] month = meta["acquisitionMonth"].lstrip("0") day = meta["acquisitionDay"].lstrip("0") img_num = meta["num"] meta["key"] = "tiles/{}/{}/{}/{}/{}/{}/{}".format( utm_zone, latitude_band, grid_square, year, month, day, img_num ) meta["scene"] = sceneid return meta
[ "def", "_sentinel_parse_scene_id", "(", "sceneid", ")", ":", "if", "not", "re", ".", "match", "(", "\"^S2[AB]_tile_[0-9]{8}_[0-9]{2}[A-Z]{3}_[0-9]$\"", ",", "sceneid", ")", ":", "raise", "InvalidSentinelSceneId", "(", "\"Could not match {}\"", ".", "format", "(", "sce...
Parse Sentinel-2 scene id. Attributes ---------- sceneid : str Sentinel-2 sceneid. Returns ------- out : dict dictionary with metadata constructed from the sceneid. e.g: _sentinel_parse_scene_id('S2A_tile_20170323_07SNC_0') { "acquisitionDay": "23", "acquisitionMonth": "03", "acquisitionYear": "2017", "key": "tiles/7/S/NC/2017/3/23/0", "lat": "S", "num": "0", "satellite": "A", "scene": "S2A_tile_20170323_07SNC_0", "sensor": "2", "sq": "NC", "utm": "07", }
[ "Parse", "Sentinel", "-", "2", "scene", "id", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/sentinel2.py#L40-L109
train
208,975
cogeotiff/rio-tiler
rio_tiler/sentinel2.py
tile
def tile(sceneid, tile_x, tile_y, tile_z, bands=("04", "03", "02"), tilesize=256): """ Create mercator tile from Sentinel-2 data. Attributes ---------- sceneid : str Sentinel-2 sceneid. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. bands : tuple, str, optional (default: ('04', '03', '02')) Bands index for the RGB combination. tilesize : int, optional (default: 256) Output image size. Returns ------- data : numpy ndarray mask: numpy array """ if not isinstance(bands, tuple): bands = tuple((bands,)) for band in bands: if band not in SENTINEL_BANDS: raise InvalidBandName("{} is not a valid Sentinel band name".format(band)) scene_params = _sentinel_parse_scene_id(sceneid) sentinel_address = "{}/{}".format(SENTINEL_BUCKET, scene_params["key"]) sentinel_preview = "{}/preview.jp2".format(sentinel_address) with rasterio.open(sentinel_preview) as src: wgs_bounds = transform_bounds( *[src.crs, "epsg:4326"] + list(src.bounds), densify_pts=21 ) if not utils.tile_exists(wgs_bounds, tile_z, tile_x, tile_y): raise TileOutsideBounds( "Tile {}/{}/{} is outside image bounds".format(tile_z, tile_x, tile_y) ) mercator_tile = mercantile.Tile(x=tile_x, y=tile_y, z=tile_z) tile_bounds = mercantile.xy_bounds(mercator_tile) addresses = ["{}/B{}.jp2".format(sentinel_address, band) for band in bands] _tiler = partial(utils.tile_read, bounds=tile_bounds, tilesize=tilesize, nodata=0) with futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor: data, masks = zip(*list(executor.map(_tiler, addresses))) mask = np.all(masks, axis=0).astype(np.uint8) * 255 return np.concatenate(data), mask
python
def tile(sceneid, tile_x, tile_y, tile_z, bands=("04", "03", "02"), tilesize=256): """ Create mercator tile from Sentinel-2 data. Attributes ---------- sceneid : str Sentinel-2 sceneid. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. bands : tuple, str, optional (default: ('04', '03', '02')) Bands index for the RGB combination. tilesize : int, optional (default: 256) Output image size. Returns ------- data : numpy ndarray mask: numpy array """ if not isinstance(bands, tuple): bands = tuple((bands,)) for band in bands: if band not in SENTINEL_BANDS: raise InvalidBandName("{} is not a valid Sentinel band name".format(band)) scene_params = _sentinel_parse_scene_id(sceneid) sentinel_address = "{}/{}".format(SENTINEL_BUCKET, scene_params["key"]) sentinel_preview = "{}/preview.jp2".format(sentinel_address) with rasterio.open(sentinel_preview) as src: wgs_bounds = transform_bounds( *[src.crs, "epsg:4326"] + list(src.bounds), densify_pts=21 ) if not utils.tile_exists(wgs_bounds, tile_z, tile_x, tile_y): raise TileOutsideBounds( "Tile {}/{}/{} is outside image bounds".format(tile_z, tile_x, tile_y) ) mercator_tile = mercantile.Tile(x=tile_x, y=tile_y, z=tile_z) tile_bounds = mercantile.xy_bounds(mercator_tile) addresses = ["{}/B{}.jp2".format(sentinel_address, band) for band in bands] _tiler = partial(utils.tile_read, bounds=tile_bounds, tilesize=tilesize, nodata=0) with futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor: data, masks = zip(*list(executor.map(_tiler, addresses))) mask = np.all(masks, axis=0).astype(np.uint8) * 255 return np.concatenate(data), mask
[ "def", "tile", "(", "sceneid", ",", "tile_x", ",", "tile_y", ",", "tile_z", ",", "bands", "=", "(", "\"04\"", ",", "\"03\"", ",", "\"02\"", ")", ",", "tilesize", "=", "256", ")", ":", "if", "not", "isinstance", "(", "bands", ",", "tuple", ")", ":",...
Create mercator tile from Sentinel-2 data. Attributes ---------- sceneid : str Sentinel-2 sceneid. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. bands : tuple, str, optional (default: ('04', '03', '02')) Bands index for the RGB combination. tilesize : int, optional (default: 256) Output image size. Returns ------- data : numpy ndarray mask: numpy array
[ "Create", "mercator", "tile", "from", "Sentinel", "-", "2", "data", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/sentinel2.py#L209-L265
train
208,976
cogeotiff/rio-tiler
rio_tiler/landsat8.py
_landsat_get_mtl
def _landsat_get_mtl(sceneid): """ Get Landsat-8 MTL metadata. Attributes ---------- sceneid : str Landsat sceneid. For scenes after May 2017, sceneid have to be LANDSAT_PRODUCT_ID. Returns ------- out : dict returns a JSON like object with the metadata. """ scene_params = _landsat_parse_scene_id(sceneid) meta_file = "http://landsat-pds.s3.amazonaws.com/{}_MTL.txt".format( scene_params["key"] ) metadata = str(urlopen(meta_file).read().decode()) return toa_utils._parse_mtl_txt(metadata)
python
def _landsat_get_mtl(sceneid): """ Get Landsat-8 MTL metadata. Attributes ---------- sceneid : str Landsat sceneid. For scenes after May 2017, sceneid have to be LANDSAT_PRODUCT_ID. Returns ------- out : dict returns a JSON like object with the metadata. """ scene_params = _landsat_parse_scene_id(sceneid) meta_file = "http://landsat-pds.s3.amazonaws.com/{}_MTL.txt".format( scene_params["key"] ) metadata = str(urlopen(meta_file).read().decode()) return toa_utils._parse_mtl_txt(metadata)
[ "def", "_landsat_get_mtl", "(", "sceneid", ")", ":", "scene_params", "=", "_landsat_parse_scene_id", "(", "sceneid", ")", "meta_file", "=", "\"http://landsat-pds.s3.amazonaws.com/{}_MTL.txt\"", ".", "format", "(", "scene_params", "[", "\"key\"", "]", ")", "metadata", ...
Get Landsat-8 MTL metadata. Attributes ---------- sceneid : str Landsat sceneid. For scenes after May 2017, sceneid have to be LANDSAT_PRODUCT_ID. Returns ------- out : dict returns a JSON like object with the metadata.
[ "Get", "Landsat", "-", "8", "MTL", "metadata", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/landsat8.py#L43-L64
train
208,977
cogeotiff/rio-tiler
rio_tiler/landsat8.py
_landsat_parse_scene_id
def _landsat_parse_scene_id(sceneid): """ Parse Landsat-8 scene id. Author @perrygeo - http://www.perrygeo.com """ pre_collection = r"(L[COTEM]8\d{6}\d{7}[A-Z]{3}\d{2})" collection_1 = r"(L[COTEM]08_L\d{1}[A-Z]{2}_\d{6}_\d{8}_\d{8}_\d{2}_(T1|T2|RT))" if not re.match("^{}|{}$".format(pre_collection, collection_1), sceneid): raise InvalidLandsatSceneId("Could not match {}".format(sceneid)) precollection_pattern = ( r"^L" r"(?P<sensor>\w{1})" r"(?P<satellite>\w{1})" r"(?P<path>[0-9]{3})" r"(?P<row>[0-9]{3})" r"(?P<acquisitionYear>[0-9]{4})" r"(?P<acquisitionJulianDay>[0-9]{3})" r"(?P<groundStationIdentifier>\w{3})" r"(?P<archiveVersion>[0-9]{2})$" ) collection_pattern = ( r"^L" r"(?P<sensor>\w{1})" r"(?P<satellite>\w{2})" r"_" r"(?P<processingCorrectionLevel>\w{4})" r"_" r"(?P<path>[0-9]{3})" r"(?P<row>[0-9]{3})" r"_" r"(?P<acquisitionYear>[0-9]{4})" r"(?P<acquisitionMonth>[0-9]{2})" r"(?P<acquisitionDay>[0-9]{2})" r"_" r"(?P<processingYear>[0-9]{4})" r"(?P<processingMonth>[0-9]{2})" r"(?P<processingDay>[0-9]{2})" r"_" r"(?P<collectionNumber>\w{2})" r"_" r"(?P<collectionCategory>\w{2})$" ) meta = None for pattern in [collection_pattern, precollection_pattern]: match = re.match(pattern, sceneid, re.IGNORECASE) if match: meta = match.groupdict() break if meta.get("acquisitionJulianDay"): date = datetime.datetime( int(meta["acquisitionYear"]), 1, 1 ) + datetime.timedelta(int(meta["acquisitionJulianDay"]) - 1) meta["date"] = date.strftime("%Y-%m-%d") else: meta["date"] = "{}-{}-{}".format( meta["acquisitionYear"], meta["acquisitionMonth"], meta["acquisitionDay"] ) collection = meta.get("collectionNumber", "") if collection != "": collection = "c{}".format(int(collection)) meta["key"] = os.path.join( collection, "L8", meta["path"], meta["row"], sceneid, sceneid ) meta["scene"] = sceneid return meta
python
def _landsat_parse_scene_id(sceneid): """ Parse Landsat-8 scene id. Author @perrygeo - http://www.perrygeo.com """ pre_collection = r"(L[COTEM]8\d{6}\d{7}[A-Z]{3}\d{2})" collection_1 = r"(L[COTEM]08_L\d{1}[A-Z]{2}_\d{6}_\d{8}_\d{8}_\d{2}_(T1|T2|RT))" if not re.match("^{}|{}$".format(pre_collection, collection_1), sceneid): raise InvalidLandsatSceneId("Could not match {}".format(sceneid)) precollection_pattern = ( r"^L" r"(?P<sensor>\w{1})" r"(?P<satellite>\w{1})" r"(?P<path>[0-9]{3})" r"(?P<row>[0-9]{3})" r"(?P<acquisitionYear>[0-9]{4})" r"(?P<acquisitionJulianDay>[0-9]{3})" r"(?P<groundStationIdentifier>\w{3})" r"(?P<archiveVersion>[0-9]{2})$" ) collection_pattern = ( r"^L" r"(?P<sensor>\w{1})" r"(?P<satellite>\w{2})" r"_" r"(?P<processingCorrectionLevel>\w{4})" r"_" r"(?P<path>[0-9]{3})" r"(?P<row>[0-9]{3})" r"_" r"(?P<acquisitionYear>[0-9]{4})" r"(?P<acquisitionMonth>[0-9]{2})" r"(?P<acquisitionDay>[0-9]{2})" r"_" r"(?P<processingYear>[0-9]{4})" r"(?P<processingMonth>[0-9]{2})" r"(?P<processingDay>[0-9]{2})" r"_" r"(?P<collectionNumber>\w{2})" r"_" r"(?P<collectionCategory>\w{2})$" ) meta = None for pattern in [collection_pattern, precollection_pattern]: match = re.match(pattern, sceneid, re.IGNORECASE) if match: meta = match.groupdict() break if meta.get("acquisitionJulianDay"): date = datetime.datetime( int(meta["acquisitionYear"]), 1, 1 ) + datetime.timedelta(int(meta["acquisitionJulianDay"]) - 1) meta["date"] = date.strftime("%Y-%m-%d") else: meta["date"] = "{}-{}-{}".format( meta["acquisitionYear"], meta["acquisitionMonth"], meta["acquisitionDay"] ) collection = meta.get("collectionNumber", "") if collection != "": collection = "c{}".format(int(collection)) meta["key"] = os.path.join( collection, "L8", meta["path"], meta["row"], sceneid, sceneid ) meta["scene"] = sceneid return meta
[ "def", "_landsat_parse_scene_id", "(", "sceneid", ")", ":", "pre_collection", "=", "r\"(L[COTEM]8\\d{6}\\d{7}[A-Z]{3}\\d{2})\"", "collection_1", "=", "r\"(L[COTEM]08_L\\d{1}[A-Z]{2}_\\d{6}_\\d{8}_\\d{8}_\\d{2}_(T1|T2|RT))\"", "if", "not", "re", ".", "match", "(", "\"^{}|{}$\"", ...
Parse Landsat-8 scene id. Author @perrygeo - http://www.perrygeo.com
[ "Parse", "Landsat", "-", "8", "scene", "id", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/landsat8.py#L67-L142
train
208,978
cogeotiff/rio-tiler
rio_tiler/landsat8.py
_landsat_stats
def _landsat_stats( band, address_prefix, metadata, overview_level=None, max_size=1024, percentiles=(2, 98), dst_crs=CRS({"init": "EPSG:4326"}), histogram_bins=10, histogram_range=None, ): """ Retrieve landsat dataset statistics. Attributes ---------- band : str Landsat band number address_prefix : str A Landsat AWS S3 dataset prefix. metadata : dict Landsat metadata overview_level : int, optional Overview (decimation) level to fetch. max_size: int, optional Maximum size of dataset to retrieve (will be used to calculate the overview level to fetch). percentiles : tulple, optional Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive (default: (2, 98)). dst_crs: CRS or dict Target coordinate reference system (default: EPSG:4326). histogram_bins: int, optional Defines the number of equal-width histogram bins (default: 10). histogram_range: tuple or list, optional The lower and upper range of the bins. If not provided, range is simply the min and max of the array. Returns ------- out : dict (percentiles), min, max, stdev, histogram for each band, e.g. { "4": { 'pc': [15, 121], 'min': 1, 'max': 162, 'std': 27.22067722127997, 'histogram': [ [102934, 135489, 20981, 13548, 11406, 8799, 7351, 5622, 2985, 662] [1., 17.1, 33.2, 49.3, 65.4, 81.5, 97.6, 113.7, 129.8, 145.9, 162.] ] } } """ src_path = "{}_B{}.TIF".format(address_prefix, band) with rasterio.open(src_path) as src: levels = src.overviews(1) width = src.width height = src.height bounds = transform_bounds( *[src.crs, dst_crs] + list(src.bounds), densify_pts=21 ) if len(levels): if overview_level: decim = levels[overview_level] else: # determine which zoom level to read for ii, decim in enumerate(levels): if max(width // decim, height // decim) < max_size: break else: decim = 1 warnings.warn( "Dataset has no overviews, reading the full dataset", NoOverviewWarning ) out_shape = (height // decim, width // decim) vrt_params = dict( nodata=0, add_alpha=False, src_nodata=0, init_dest_nodata=False ) with WarpedVRT(src, **vrt_params) as vrt: arr = vrt.read(out_shape=out_shape, indexes=[1], masked=True) if band in ["10", "11"]: # TIRS multi_rad = metadata["RADIOMETRIC_RESCALING"].get( "RADIANCE_MULT_BAND_{}".format(band) ) add_rad = metadata["RADIOMETRIC_RESCALING"].get( "RADIANCE_ADD_BAND_{}".format(band) ) k1 = metadata["TIRS_THERMAL_CONSTANTS"].get("K1_CONSTANT_BAND_{}".format(band)) k2 = metadata["TIRS_THERMAL_CONSTANTS"].get("K2_CONSTANT_BAND_{}".format(band)) arr = brightness_temp.brightness_temp(arr, multi_rad, add_rad, k1, k2) else: multi_reflect = metadata["RADIOMETRIC_RESCALING"].get( "REFLECTANCE_MULT_BAND_{}".format(band) ) add_reflect = metadata["RADIOMETRIC_RESCALING"].get( "REFLECTANCE_ADD_BAND_{}".format(band) ) sun_elev = metadata["IMAGE_ATTRIBUTES"]["SUN_ELEVATION"] arr = 10000 * reflectance.reflectance( arr, multi_reflect, add_reflect, sun_elev, src_nodata=0 ) params = {} if histogram_bins: params.update(dict(bins=histogram_bins)) if histogram_range: params.update(dict(range=histogram_range)) stats = {band: utils._stats(arr, percentiles=percentiles, **params)} return { "bounds": { "value": bounds, "crs": dst_crs.to_string() if isinstance(dst_crs, CRS) else dst_crs, }, "statistics": stats, }
python
def _landsat_stats( band, address_prefix, metadata, overview_level=None, max_size=1024, percentiles=(2, 98), dst_crs=CRS({"init": "EPSG:4326"}), histogram_bins=10, histogram_range=None, ): """ Retrieve landsat dataset statistics. Attributes ---------- band : str Landsat band number address_prefix : str A Landsat AWS S3 dataset prefix. metadata : dict Landsat metadata overview_level : int, optional Overview (decimation) level to fetch. max_size: int, optional Maximum size of dataset to retrieve (will be used to calculate the overview level to fetch). percentiles : tulple, optional Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive (default: (2, 98)). dst_crs: CRS or dict Target coordinate reference system (default: EPSG:4326). histogram_bins: int, optional Defines the number of equal-width histogram bins (default: 10). histogram_range: tuple or list, optional The lower and upper range of the bins. If not provided, range is simply the min and max of the array. Returns ------- out : dict (percentiles), min, max, stdev, histogram for each band, e.g. { "4": { 'pc': [15, 121], 'min': 1, 'max': 162, 'std': 27.22067722127997, 'histogram': [ [102934, 135489, 20981, 13548, 11406, 8799, 7351, 5622, 2985, 662] [1., 17.1, 33.2, 49.3, 65.4, 81.5, 97.6, 113.7, 129.8, 145.9, 162.] ] } } """ src_path = "{}_B{}.TIF".format(address_prefix, band) with rasterio.open(src_path) as src: levels = src.overviews(1) width = src.width height = src.height bounds = transform_bounds( *[src.crs, dst_crs] + list(src.bounds), densify_pts=21 ) if len(levels): if overview_level: decim = levels[overview_level] else: # determine which zoom level to read for ii, decim in enumerate(levels): if max(width // decim, height // decim) < max_size: break else: decim = 1 warnings.warn( "Dataset has no overviews, reading the full dataset", NoOverviewWarning ) out_shape = (height // decim, width // decim) vrt_params = dict( nodata=0, add_alpha=False, src_nodata=0, init_dest_nodata=False ) with WarpedVRT(src, **vrt_params) as vrt: arr = vrt.read(out_shape=out_shape, indexes=[1], masked=True) if band in ["10", "11"]: # TIRS multi_rad = metadata["RADIOMETRIC_RESCALING"].get( "RADIANCE_MULT_BAND_{}".format(band) ) add_rad = metadata["RADIOMETRIC_RESCALING"].get( "RADIANCE_ADD_BAND_{}".format(band) ) k1 = metadata["TIRS_THERMAL_CONSTANTS"].get("K1_CONSTANT_BAND_{}".format(band)) k2 = metadata["TIRS_THERMAL_CONSTANTS"].get("K2_CONSTANT_BAND_{}".format(band)) arr = brightness_temp.brightness_temp(arr, multi_rad, add_rad, k1, k2) else: multi_reflect = metadata["RADIOMETRIC_RESCALING"].get( "REFLECTANCE_MULT_BAND_{}".format(band) ) add_reflect = metadata["RADIOMETRIC_RESCALING"].get( "REFLECTANCE_ADD_BAND_{}".format(band) ) sun_elev = metadata["IMAGE_ATTRIBUTES"]["SUN_ELEVATION"] arr = 10000 * reflectance.reflectance( arr, multi_reflect, add_reflect, sun_elev, src_nodata=0 ) params = {} if histogram_bins: params.update(dict(bins=histogram_bins)) if histogram_range: params.update(dict(range=histogram_range)) stats = {band: utils._stats(arr, percentiles=percentiles, **params)} return { "bounds": { "value": bounds, "crs": dst_crs.to_string() if isinstance(dst_crs, CRS) else dst_crs, }, "statistics": stats, }
[ "def", "_landsat_stats", "(", "band", ",", "address_prefix", ",", "metadata", ",", "overview_level", "=", "None", ",", "max_size", "=", "1024", ",", "percentiles", "=", "(", "2", ",", "98", ")", ",", "dst_crs", "=", "CRS", "(", "{", "\"init\"", ":", "\...
Retrieve landsat dataset statistics. Attributes ---------- band : str Landsat band number address_prefix : str A Landsat AWS S3 dataset prefix. metadata : dict Landsat metadata overview_level : int, optional Overview (decimation) level to fetch. max_size: int, optional Maximum size of dataset to retrieve (will be used to calculate the overview level to fetch). percentiles : tulple, optional Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive (default: (2, 98)). dst_crs: CRS or dict Target coordinate reference system (default: EPSG:4326). histogram_bins: int, optional Defines the number of equal-width histogram bins (default: 10). histogram_range: tuple or list, optional The lower and upper range of the bins. If not provided, range is simply the min and max of the array. Returns ------- out : dict (percentiles), min, max, stdev, histogram for each band, e.g. { "4": { 'pc': [15, 121], 'min': 1, 'max': 162, 'std': 27.22067722127997, 'histogram': [ [102934, 135489, 20981, 13548, 11406, 8799, 7351, 5622, 2985, 662] [1., 17.1, 33.2, 49.3, 65.4, 81.5, 97.6, 113.7, 129.8, 145.9, 162.] ] } }
[ "Retrieve", "landsat", "dataset", "statistics", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/landsat8.py#L145-L269
train
208,979
cogeotiff/rio-tiler
rio_tiler/landsat8.py
tile
def tile( sceneid, tile_x, tile_y, tile_z, bands=("4", "3", "2"), tilesize=256, pan=False ): """ Create mercator tile from Landsat-8 data. Attributes ---------- sceneid : str Landsat sceneid. For scenes after May 2017, sceneid have to be LANDSAT_PRODUCT_ID. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. bands : tuple, str, optional (default: ("4", "3", "2")) Bands index for the RGB combination. tilesize : int, optional (default: 256) Output image size. pan : boolean, optional (default: False) If True, apply pan-sharpening. Returns ------- data : numpy ndarray mask: numpy array """ if not isinstance(bands, tuple): bands = tuple((bands,)) for band in bands: if band not in LANDSAT_BANDS: raise InvalidBandName("{} is not a valid Landsat band name".format(band)) scene_params = _landsat_parse_scene_id(sceneid) meta_data = _landsat_get_mtl(sceneid).get("L1_METADATA_FILE") landsat_address = "{}/{}".format(LANDSAT_BUCKET, scene_params["key"]) wgs_bounds = toa_utils._get_bounds_from_metadata(meta_data["PRODUCT_METADATA"]) if not utils.tile_exists(wgs_bounds, tile_z, tile_x, tile_y): raise TileOutsideBounds( "Tile {}/{}/{} is outside image bounds".format(tile_z, tile_x, tile_y) ) mercator_tile = mercantile.Tile(x=tile_x, y=tile_y, z=tile_z) tile_bounds = mercantile.xy_bounds(mercator_tile) addresses = ["{}_B{}.TIF".format(landsat_address, band) for band in bands] _tiler = partial(utils.tile_read, bounds=tile_bounds, tilesize=tilesize, nodata=0) with futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor: data, masks = zip(*list(executor.map(_tiler, addresses))) data = np.concatenate(data) mask = np.all(masks, axis=0).astype(np.uint8) * 255 if pan: pan_address = "{}_B8.TIF".format(landsat_address) matrix_pan, mask = utils.tile_read( pan_address, tile_bounds, tilesize, nodata=0 ) data = utils.pansharpening_brovey(data, matrix_pan, 0.2, matrix_pan.dtype) sun_elev = meta_data["IMAGE_ATTRIBUTES"]["SUN_ELEVATION"] for bdx, band in enumerate(bands): if int(band) > 9: # TIRS multi_rad = meta_data["RADIOMETRIC_RESCALING"].get( "RADIANCE_MULT_BAND_{}".format(band) ) add_rad = meta_data["RADIOMETRIC_RESCALING"].get( "RADIANCE_ADD_BAND_{}".format(band) ) k1 = meta_data["TIRS_THERMAL_CONSTANTS"].get( "K1_CONSTANT_BAND_{}".format(band) ) k2 = meta_data["TIRS_THERMAL_CONSTANTS"].get( "K2_CONSTANT_BAND_{}".format(band) ) data[bdx] = brightness_temp.brightness_temp( data[bdx], multi_rad, add_rad, k1, k2 ) else: multi_reflect = meta_data["RADIOMETRIC_RESCALING"].get( "REFLECTANCE_MULT_BAND_{}".format(band) ) add_reflect = meta_data["RADIOMETRIC_RESCALING"].get( "REFLECTANCE_ADD_BAND_{}".format(band) ) data[bdx] = 10000 * reflectance.reflectance( data[bdx], multi_reflect, add_reflect, sun_elev ) return data, mask
python
def tile( sceneid, tile_x, tile_y, tile_z, bands=("4", "3", "2"), tilesize=256, pan=False ): """ Create mercator tile from Landsat-8 data. Attributes ---------- sceneid : str Landsat sceneid. For scenes after May 2017, sceneid have to be LANDSAT_PRODUCT_ID. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. bands : tuple, str, optional (default: ("4", "3", "2")) Bands index for the RGB combination. tilesize : int, optional (default: 256) Output image size. pan : boolean, optional (default: False) If True, apply pan-sharpening. Returns ------- data : numpy ndarray mask: numpy array """ if not isinstance(bands, tuple): bands = tuple((bands,)) for band in bands: if band not in LANDSAT_BANDS: raise InvalidBandName("{} is not a valid Landsat band name".format(band)) scene_params = _landsat_parse_scene_id(sceneid) meta_data = _landsat_get_mtl(sceneid).get("L1_METADATA_FILE") landsat_address = "{}/{}".format(LANDSAT_BUCKET, scene_params["key"]) wgs_bounds = toa_utils._get_bounds_from_metadata(meta_data["PRODUCT_METADATA"]) if not utils.tile_exists(wgs_bounds, tile_z, tile_x, tile_y): raise TileOutsideBounds( "Tile {}/{}/{} is outside image bounds".format(tile_z, tile_x, tile_y) ) mercator_tile = mercantile.Tile(x=tile_x, y=tile_y, z=tile_z) tile_bounds = mercantile.xy_bounds(mercator_tile) addresses = ["{}_B{}.TIF".format(landsat_address, band) for band in bands] _tiler = partial(utils.tile_read, bounds=tile_bounds, tilesize=tilesize, nodata=0) with futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor: data, masks = zip(*list(executor.map(_tiler, addresses))) data = np.concatenate(data) mask = np.all(masks, axis=0).astype(np.uint8) * 255 if pan: pan_address = "{}_B8.TIF".format(landsat_address) matrix_pan, mask = utils.tile_read( pan_address, tile_bounds, tilesize, nodata=0 ) data = utils.pansharpening_brovey(data, matrix_pan, 0.2, matrix_pan.dtype) sun_elev = meta_data["IMAGE_ATTRIBUTES"]["SUN_ELEVATION"] for bdx, band in enumerate(bands): if int(band) > 9: # TIRS multi_rad = meta_data["RADIOMETRIC_RESCALING"].get( "RADIANCE_MULT_BAND_{}".format(band) ) add_rad = meta_data["RADIOMETRIC_RESCALING"].get( "RADIANCE_ADD_BAND_{}".format(band) ) k1 = meta_data["TIRS_THERMAL_CONSTANTS"].get( "K1_CONSTANT_BAND_{}".format(band) ) k2 = meta_data["TIRS_THERMAL_CONSTANTS"].get( "K2_CONSTANT_BAND_{}".format(band) ) data[bdx] = brightness_temp.brightness_temp( data[bdx], multi_rad, add_rad, k1, k2 ) else: multi_reflect = meta_data["RADIOMETRIC_RESCALING"].get( "REFLECTANCE_MULT_BAND_{}".format(band) ) add_reflect = meta_data["RADIOMETRIC_RESCALING"].get( "REFLECTANCE_ADD_BAND_{}".format(band) ) data[bdx] = 10000 * reflectance.reflectance( data[bdx], multi_reflect, add_reflect, sun_elev ) return data, mask
[ "def", "tile", "(", "sceneid", ",", "tile_x", ",", "tile_y", ",", "tile_z", ",", "bands", "=", "(", "\"4\"", ",", "\"3\"", ",", "\"2\"", ")", ",", "tilesize", "=", "256", ",", "pan", "=", "False", ")", ":", "if", "not", "isinstance", "(", "bands", ...
Create mercator tile from Landsat-8 data. Attributes ---------- sceneid : str Landsat sceneid. For scenes after May 2017, sceneid have to be LANDSAT_PRODUCT_ID. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile ZOOM level. bands : tuple, str, optional (default: ("4", "3", "2")) Bands index for the RGB combination. tilesize : int, optional (default: 256) Output image size. pan : boolean, optional (default: False) If True, apply pan-sharpening. Returns ------- data : numpy ndarray mask: numpy array
[ "Create", "mercator", "tile", "from", "Landsat", "-", "8", "data", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/landsat8.py#L349-L452
train
208,980
cogeotiff/rio-tiler
rio_tiler/cbers.py
_cbers_parse_scene_id
def _cbers_parse_scene_id(sceneid): """Parse CBERS scene id. Attributes ---------- sceneid : str CBERS sceneid. Returns ------- out : dict dictionary with metadata constructed from the sceneid. e.g: _cbers_parse_scene_id('CBERS_4_PAN5M_20171121_057_094_L2') { "acquisitionDay": "21", "acquisitionMonth": "11", "acquisitionYear": "2017", "instrument": "PAN5M", "key": "CBERS4/PAN5M/057/094/CBERS_4_PAN5M_20171121_057_094_L2", "path": "057", "processingCorrectionLevel": "L2", "row": "094", "mission": "4", "scene": "CBERS_4_PAN5M_20171121_057_094_L2", "reference_band": "1", "bands": ["1"], "rgb": ("1", "1", "1"), "satellite": "CBERS", } """ if not re.match(r"^CBERS_4_\w+_[0-9]{8}_[0-9]{3}_[0-9]{3}_L[0-9]$", sceneid): raise InvalidCBERSSceneId("Could not match {}".format(sceneid)) cbers_pattern = ( r"(?P<satellite>\w+)_" r"(?P<mission>[0-9]{1})" r"_" r"(?P<instrument>\w+)" r"_" r"(?P<acquisitionYear>[0-9]{4})" r"(?P<acquisitionMonth>[0-9]{2})" r"(?P<acquisitionDay>[0-9]{2})" r"_" r"(?P<path>[0-9]{3})" r"_" r"(?P<row>[0-9]{3})" r"_" r"(?P<processingCorrectionLevel>L[0-9]{1})$" ) meta = None match = re.match(cbers_pattern, sceneid, re.IGNORECASE) if match: meta = match.groupdict() path = meta["path"] row = meta["row"] instrument = meta["instrument"] meta["key"] = "CBERS4/{}/{}/{}/{}".format(instrument, path, row, sceneid) meta["scene"] = sceneid instrument_params = { "MUX": { "reference_band": "6", "bands": ["5", "6", "7", "8"], "rgb": ("7", "6", "5"), }, "AWFI": { "reference_band": "14", "bands": ["13", "14", "15", "16"], "rgb": ("15", "14", "13"), }, "PAN10M": { "reference_band": "4", "bands": ["2", "3", "4"], "rgb": ("3", "4", "2"), }, "PAN5M": {"reference_band": "1", "bands": ["1"], "rgb": ("1", "1", "1")}, } meta["reference_band"] = instrument_params[instrument]["reference_band"] meta["bands"] = instrument_params[instrument]["bands"] meta["rgb"] = instrument_params[instrument]["rgb"] return meta
python
def _cbers_parse_scene_id(sceneid): """Parse CBERS scene id. Attributes ---------- sceneid : str CBERS sceneid. Returns ------- out : dict dictionary with metadata constructed from the sceneid. e.g: _cbers_parse_scene_id('CBERS_4_PAN5M_20171121_057_094_L2') { "acquisitionDay": "21", "acquisitionMonth": "11", "acquisitionYear": "2017", "instrument": "PAN5M", "key": "CBERS4/PAN5M/057/094/CBERS_4_PAN5M_20171121_057_094_L2", "path": "057", "processingCorrectionLevel": "L2", "row": "094", "mission": "4", "scene": "CBERS_4_PAN5M_20171121_057_094_L2", "reference_band": "1", "bands": ["1"], "rgb": ("1", "1", "1"), "satellite": "CBERS", } """ if not re.match(r"^CBERS_4_\w+_[0-9]{8}_[0-9]{3}_[0-9]{3}_L[0-9]$", sceneid): raise InvalidCBERSSceneId("Could not match {}".format(sceneid)) cbers_pattern = ( r"(?P<satellite>\w+)_" r"(?P<mission>[0-9]{1})" r"_" r"(?P<instrument>\w+)" r"_" r"(?P<acquisitionYear>[0-9]{4})" r"(?P<acquisitionMonth>[0-9]{2})" r"(?P<acquisitionDay>[0-9]{2})" r"_" r"(?P<path>[0-9]{3})" r"_" r"(?P<row>[0-9]{3})" r"_" r"(?P<processingCorrectionLevel>L[0-9]{1})$" ) meta = None match = re.match(cbers_pattern, sceneid, re.IGNORECASE) if match: meta = match.groupdict() path = meta["path"] row = meta["row"] instrument = meta["instrument"] meta["key"] = "CBERS4/{}/{}/{}/{}".format(instrument, path, row, sceneid) meta["scene"] = sceneid instrument_params = { "MUX": { "reference_band": "6", "bands": ["5", "6", "7", "8"], "rgb": ("7", "6", "5"), }, "AWFI": { "reference_band": "14", "bands": ["13", "14", "15", "16"], "rgb": ("15", "14", "13"), }, "PAN10M": { "reference_band": "4", "bands": ["2", "3", "4"], "rgb": ("3", "4", "2"), }, "PAN5M": {"reference_band": "1", "bands": ["1"], "rgb": ("1", "1", "1")}, } meta["reference_band"] = instrument_params[instrument]["reference_band"] meta["bands"] = instrument_params[instrument]["bands"] meta["rgb"] = instrument_params[instrument]["rgb"] return meta
[ "def", "_cbers_parse_scene_id", "(", "sceneid", ")", ":", "if", "not", "re", ".", "match", "(", "r\"^CBERS_4_\\w+_[0-9]{8}_[0-9]{3}_[0-9]{3}_L[0-9]$\"", ",", "sceneid", ")", ":", "raise", "InvalidCBERSSceneId", "(", "\"Could not match {}\"", ".", "format", "(", "scene...
Parse CBERS scene id. Attributes ---------- sceneid : str CBERS sceneid. Returns ------- out : dict dictionary with metadata constructed from the sceneid. e.g: _cbers_parse_scene_id('CBERS_4_PAN5M_20171121_057_094_L2') { "acquisitionDay": "21", "acquisitionMonth": "11", "acquisitionYear": "2017", "instrument": "PAN5M", "key": "CBERS4/PAN5M/057/094/CBERS_4_PAN5M_20171121_057_094_L2", "path": "057", "processingCorrectionLevel": "L2", "row": "094", "mission": "4", "scene": "CBERS_4_PAN5M_20171121_057_094_L2", "reference_band": "1", "bands": ["1"], "rgb": ("1", "1", "1"), "satellite": "CBERS", }
[ "Parse", "CBERS", "scene", "id", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/cbers.py#L25-L112
train
208,981
cogeotiff/rio-tiler
rio_tiler/cbers.py
metadata
def metadata(sceneid, pmin=2, pmax=98, **kwargs): """ Return band bounds and statistics. Attributes ---------- sceneid : str CBERS sceneid. pmin : int, optional, (default: 2) Histogram minimum cut. pmax : int, optional, (default: 98) Histogram maximum cut. kwargs : optional These are passed to 'rio_tiler.utils.raster_get_stats' e.g: histogram_bins=20, dst_crs='epsg:4326' Returns ------- out : dict Dictionary with bounds and bands statistics. """ scene_params = _cbers_parse_scene_id(sceneid) cbers_address = "{}/{}".format(CBERS_BUCKET, scene_params["key"]) bands = scene_params["bands"] ref_band = scene_params["reference_band"] info = {"sceneid": sceneid} addresses = [ "{}/{}_BAND{}.tif".format(cbers_address, sceneid, band) for band in bands ] _stats_worker = partial( utils.raster_get_stats, indexes=[1], nodata=0, overview_level=2, percentiles=(pmin, pmax), **kwargs ) with futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor: responses = list(executor.map(_stats_worker, addresses)) info["bounds"] = [r["bounds"] for b, r in zip(bands, responses) if b == ref_band][0] info["statistics"] = { b: v for b, d in zip(bands, responses) for k, v in d["statistics"].items() } return info
python
def metadata(sceneid, pmin=2, pmax=98, **kwargs): """ Return band bounds and statistics. Attributes ---------- sceneid : str CBERS sceneid. pmin : int, optional, (default: 2) Histogram minimum cut. pmax : int, optional, (default: 98) Histogram maximum cut. kwargs : optional These are passed to 'rio_tiler.utils.raster_get_stats' e.g: histogram_bins=20, dst_crs='epsg:4326' Returns ------- out : dict Dictionary with bounds and bands statistics. """ scene_params = _cbers_parse_scene_id(sceneid) cbers_address = "{}/{}".format(CBERS_BUCKET, scene_params["key"]) bands = scene_params["bands"] ref_band = scene_params["reference_band"] info = {"sceneid": sceneid} addresses = [ "{}/{}_BAND{}.tif".format(cbers_address, sceneid, band) for band in bands ] _stats_worker = partial( utils.raster_get_stats, indexes=[1], nodata=0, overview_level=2, percentiles=(pmin, pmax), **kwargs ) with futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor: responses = list(executor.map(_stats_worker, addresses)) info["bounds"] = [r["bounds"] for b, r in zip(bands, responses) if b == ref_band][0] info["statistics"] = { b: v for b, d in zip(bands, responses) for k, v in d["statistics"].items() } return info
[ "def", "metadata", "(", "sceneid", ",", "pmin", "=", "2", ",", "pmax", "=", "98", ",", "*", "*", "kwargs", ")", ":", "scene_params", "=", "_cbers_parse_scene_id", "(", "sceneid", ")", "cbers_address", "=", "\"{}/{}\"", ".", "format", "(", "CBERS_BUCKET", ...
Return band bounds and statistics. Attributes ---------- sceneid : str CBERS sceneid. pmin : int, optional, (default: 2) Histogram minimum cut. pmax : int, optional, (default: 98) Histogram maximum cut. kwargs : optional These are passed to 'rio_tiler.utils.raster_get_stats' e.g: histogram_bins=20, dst_crs='epsg:4326' Returns ------- out : dict Dictionary with bounds and bands statistics.
[ "Return", "band", "bounds", "and", "statistics", "." ]
09bb0fc6cee556410477f016abbae172b12c46a6
https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/cbers.py#L148-L195
train
208,982
iamaziz/PyDataset
pydataset/datasets_handler.py
__datasets_desc
def __datasets_desc(): """return a df of the available datasets with description""" datasets = __get_data_folder_path() + 'datasets.csv' df = pd.read_csv(datasets) df = df[['Item', 'Title']] df.columns = ['dataset_id', 'title'] # print('a list of the available datasets:') return df
python
def __datasets_desc(): """return a df of the available datasets with description""" datasets = __get_data_folder_path() + 'datasets.csv' df = pd.read_csv(datasets) df = df[['Item', 'Title']] df.columns = ['dataset_id', 'title'] # print('a list of the available datasets:') return df
[ "def", "__datasets_desc", "(", ")", ":", "datasets", "=", "__get_data_folder_path", "(", ")", "+", "'datasets.csv'", "df", "=", "pd", ".", "read_csv", "(", "datasets", ")", "df", "=", "df", "[", "[", "'Item'", ",", "'Title'", "]", "]", "df", ".", "colu...
return a df of the available datasets with description
[ "return", "a", "df", "of", "the", "available", "datasets", "with", "description" ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/datasets_handler.py#L65-L72
train
208,983
iamaziz/PyDataset
pydataset/utils/html2text.py
dumb_property_dict
def dumb_property_dict(style): """returns a hash of css attributes""" return dict([(x.strip(), y.strip()) for x, y in [z.split(':', 1) for z in style.split(';') if ':' in z]]);
python
def dumb_property_dict(style): """returns a hash of css attributes""" return dict([(x.strip(), y.strip()) for x, y in [z.split(':', 1) for z in style.split(';') if ':' in z]]);
[ "def", "dumb_property_dict", "(", "style", ")", ":", "return", "dict", "(", "[", "(", "x", ".", "strip", "(", ")", ",", "y", ".", "strip", "(", ")", ")", "for", "x", ",", "y", "in", "[", "z", ".", "split", "(", "':'", ",", "1", ")", "for", ...
returns a hash of css attributes
[ "returns", "a", "hash", "of", "css", "attributes" ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/utils/html2text.py#L106-L108
train
208,984
iamaziz/PyDataset
pydataset/utils/html2text.py
dumb_css_parser
def dumb_css_parser(data): """returns a hash of css selectors, each of which contains a hash of css attributes""" # remove @import sentences data += ';' importIndex = data.find('@import') while importIndex != -1: data = data[0:importIndex] + data[data.find(';', importIndex) + 1:] importIndex = data.find('@import') # parse the css. reverted from dictionary compehension in order to support older pythons elements = [x.split('{') for x in data.split('}') if '{' in x.strip()] try: elements = dict([(a.strip(), dumb_property_dict(b)) for a, b in elements]) except ValueError: elements = {} # not that important return elements
python
def dumb_css_parser(data): """returns a hash of css selectors, each of which contains a hash of css attributes""" # remove @import sentences data += ';' importIndex = data.find('@import') while importIndex != -1: data = data[0:importIndex] + data[data.find(';', importIndex) + 1:] importIndex = data.find('@import') # parse the css. reverted from dictionary compehension in order to support older pythons elements = [x.split('{') for x in data.split('}') if '{' in x.strip()] try: elements = dict([(a.strip(), dumb_property_dict(b)) for a, b in elements]) except ValueError: elements = {} # not that important return elements
[ "def", "dumb_css_parser", "(", "data", ")", ":", "# remove @import sentences", "data", "+=", "';'", "importIndex", "=", "data", ".", "find", "(", "'@import'", ")", "while", "importIndex", "!=", "-", "1", ":", "data", "=", "data", "[", "0", ":", "importInde...
returns a hash of css selectors, each of which contains a hash of css attributes
[ "returns", "a", "hash", "of", "css", "selectors", "each", "of", "which", "contains", "a", "hash", "of", "css", "attributes" ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/utils/html2text.py#L110-L126
train
208,985
iamaziz/PyDataset
pydataset/utils/html2text.py
element_style
def element_style(attrs, style_def, parent_style): """returns a hash of the 'final' style attributes of the element""" style = parent_style.copy() if 'class' in attrs: for css_class in attrs['class'].split(): css_style = style_def['.' + css_class] style.update(css_style) if 'style' in attrs: immediate_style = dumb_property_dict(attrs['style']) style.update(immediate_style) return style
python
def element_style(attrs, style_def, parent_style): """returns a hash of the 'final' style attributes of the element""" style = parent_style.copy() if 'class' in attrs: for css_class in attrs['class'].split(): css_style = style_def['.' + css_class] style.update(css_style) if 'style' in attrs: immediate_style = dumb_property_dict(attrs['style']) style.update(immediate_style) return style
[ "def", "element_style", "(", "attrs", ",", "style_def", ",", "parent_style", ")", ":", "style", "=", "parent_style", ".", "copy", "(", ")", "if", "'class'", "in", "attrs", ":", "for", "css_class", "in", "attrs", "[", "'class'", "]", ".", "split", "(", ...
returns a hash of the 'final' style attributes of the element
[ "returns", "a", "hash", "of", "the", "final", "style", "attributes", "of", "the", "element" ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/utils/html2text.py#L128-L138
train
208,986
iamaziz/PyDataset
pydataset/utils/html2text.py
google_text_emphasis
def google_text_emphasis(style): """return a list of all emphasis modifiers of the element""" emphasis = [] if 'text-decoration' in style: emphasis.append(style['text-decoration']) if 'font-style' in style: emphasis.append(style['font-style']) if 'font-weight' in style: emphasis.append(style['font-weight']) return emphasis
python
def google_text_emphasis(style): """return a list of all emphasis modifiers of the element""" emphasis = [] if 'text-decoration' in style: emphasis.append(style['text-decoration']) if 'font-style' in style: emphasis.append(style['font-style']) if 'font-weight' in style: emphasis.append(style['font-weight']) return emphasis
[ "def", "google_text_emphasis", "(", "style", ")", ":", "emphasis", "=", "[", "]", "if", "'text-decoration'", "in", "style", ":", "emphasis", ".", "append", "(", "style", "[", "'text-decoration'", "]", ")", "if", "'font-style'", "in", "style", ":", "emphasis"...
return a list of all emphasis modifiers of the element
[ "return", "a", "list", "of", "all", "emphasis", "modifiers", "of", "the", "element" ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/utils/html2text.py#L154-L163
train
208,987
iamaziz/PyDataset
pydataset/utils/html2text.py
google_fixed_width_font
def google_fixed_width_font(style): """check if the css of the current element defines a fixed width font""" font_family = '' if 'font-family' in style: font_family = style['font-family'] if 'Courier New' == font_family or 'Consolas' == font_family: return True return False
python
def google_fixed_width_font(style): """check if the css of the current element defines a fixed width font""" font_family = '' if 'font-family' in style: font_family = style['font-family'] if 'Courier New' == font_family or 'Consolas' == font_family: return True return False
[ "def", "google_fixed_width_font", "(", "style", ")", ":", "font_family", "=", "''", "if", "'font-family'", "in", "style", ":", "font_family", "=", "style", "[", "'font-family'", "]", "if", "'Courier New'", "==", "font_family", "or", "'Consolas'", "==", "font_fam...
check if the css of the current element defines a fixed width font
[ "check", "if", "the", "css", "of", "the", "current", "element", "defines", "a", "fixed", "width", "font" ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/utils/html2text.py#L165-L172
train
208,988
iamaziz/PyDataset
pydataset/utils/html2text.py
escape_md_section
def escape_md_section(text, snob=False): """Escapes markdown-sensitive characters across whole document sections.""" text = md_backslash_matcher.sub(r"\\\1", text) if snob: text = md_chars_matcher_all.sub(r"\\\1", text) text = md_dot_matcher.sub(r"\1\\\2", text) text = md_plus_matcher.sub(r"\1\\\2", text) text = md_dash_matcher.sub(r"\1\\\2", text) return text
python
def escape_md_section(text, snob=False): """Escapes markdown-sensitive characters across whole document sections.""" text = md_backslash_matcher.sub(r"\\\1", text) if snob: text = md_chars_matcher_all.sub(r"\\\1", text) text = md_dot_matcher.sub(r"\1\\\2", text) text = md_plus_matcher.sub(r"\1\\\2", text) text = md_dash_matcher.sub(r"\1\\\2", text) return text
[ "def", "escape_md_section", "(", "text", ",", "snob", "=", "False", ")", ":", "text", "=", "md_backslash_matcher", ".", "sub", "(", "r\"\\\\\\1\"", ",", "text", ")", "if", "snob", ":", "text", "=", "md_chars_matcher_all", ".", "sub", "(", "r\"\\\\\\1\"", "...
Escapes markdown-sensitive characters across whole document sections.
[ "Escapes", "markdown", "-", "sensitive", "characters", "across", "whole", "document", "sections", "." ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/utils/html2text.py#L824-L832
train
208,989
iamaziz/PyDataset
pydataset/utils/html2text.py
HTML2Text.handle_emphasis
def handle_emphasis(self, start, tag_style, parent_style): """handles various text emphases""" tag_emphasis = google_text_emphasis(tag_style) parent_emphasis = google_text_emphasis(parent_style) # handle Google's text emphasis strikethrough = 'line-through' in tag_emphasis and self.hide_strikethrough bold = 'bold' in tag_emphasis and not 'bold' in parent_emphasis italic = 'italic' in tag_emphasis and not 'italic' in parent_emphasis fixed = google_fixed_width_font(tag_style) and not \ google_fixed_width_font(parent_style) and not self.pre if start: # crossed-out text must be handled before other attributes # in order not to output qualifiers unnecessarily if bold or italic or fixed: self.emphasis += 1 if strikethrough: self.quiet += 1 if italic: self.o(self.emphasis_mark) self.drop_white_space += 1 if bold: self.o(self.strong_mark) self.drop_white_space += 1 if fixed: self.o('`') self.drop_white_space += 1 self.code = True else: if bold or italic or fixed: # there must not be whitespace before closing emphasis mark self.emphasis -= 1 self.space = 0 self.outtext = self.outtext.rstrip() if fixed: if self.drop_white_space: # empty emphasis, drop it self.drop_last(1) self.drop_white_space -= 1 else: self.o('`') self.code = False if bold: if self.drop_white_space: # empty emphasis, drop it self.drop_last(2) self.drop_white_space -= 1 else: self.o(self.strong_mark) if italic: if self.drop_white_space: # empty emphasis, drop it self.drop_last(1) self.drop_white_space -= 1 else: self.o(self.emphasis_mark) # space is only allowed after *all* emphasis marks if (bold or italic) and not self.emphasis: self.o(" ") if strikethrough: self.quiet -= 1
python
def handle_emphasis(self, start, tag_style, parent_style): """handles various text emphases""" tag_emphasis = google_text_emphasis(tag_style) parent_emphasis = google_text_emphasis(parent_style) # handle Google's text emphasis strikethrough = 'line-through' in tag_emphasis and self.hide_strikethrough bold = 'bold' in tag_emphasis and not 'bold' in parent_emphasis italic = 'italic' in tag_emphasis and not 'italic' in parent_emphasis fixed = google_fixed_width_font(tag_style) and not \ google_fixed_width_font(parent_style) and not self.pre if start: # crossed-out text must be handled before other attributes # in order not to output qualifiers unnecessarily if bold or italic or fixed: self.emphasis += 1 if strikethrough: self.quiet += 1 if italic: self.o(self.emphasis_mark) self.drop_white_space += 1 if bold: self.o(self.strong_mark) self.drop_white_space += 1 if fixed: self.o('`') self.drop_white_space += 1 self.code = True else: if bold or italic or fixed: # there must not be whitespace before closing emphasis mark self.emphasis -= 1 self.space = 0 self.outtext = self.outtext.rstrip() if fixed: if self.drop_white_space: # empty emphasis, drop it self.drop_last(1) self.drop_white_space -= 1 else: self.o('`') self.code = False if bold: if self.drop_white_space: # empty emphasis, drop it self.drop_last(2) self.drop_white_space -= 1 else: self.o(self.strong_mark) if italic: if self.drop_white_space: # empty emphasis, drop it self.drop_last(1) self.drop_white_space -= 1 else: self.o(self.emphasis_mark) # space is only allowed after *all* emphasis marks if (bold or italic) and not self.emphasis: self.o(" ") if strikethrough: self.quiet -= 1
[ "def", "handle_emphasis", "(", "self", ",", "start", ",", "tag_style", ",", "parent_style", ")", ":", "tag_emphasis", "=", "google_text_emphasis", "(", "tag_style", ")", "parent_emphasis", "=", "google_text_emphasis", "(", "parent_style", ")", "# handle Google's text ...
handles various text emphases
[ "handles", "various", "text", "emphases" ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/utils/html2text.py#L314-L375
train
208,990
iamaziz/PyDataset
pydataset/utils/html2text.py
HTML2Text.google_nest_count
def google_nest_count(self, style): """calculate the nesting count of google doc lists""" nest_count = 0 if 'margin-left' in style: nest_count = int(style['margin-left'][:-2]) / self.google_list_indent return nest_count
python
def google_nest_count(self, style): """calculate the nesting count of google doc lists""" nest_count = 0 if 'margin-left' in style: nest_count = int(style['margin-left'][:-2]) / self.google_list_indent return nest_count
[ "def", "google_nest_count", "(", "self", ",", "style", ")", ":", "nest_count", "=", "0", "if", "'margin-left'", "in", "style", ":", "nest_count", "=", "int", "(", "style", "[", "'margin-left'", "]", "[", ":", "-", "2", "]", ")", "/", "self", ".", "go...
calculate the nesting count of google doc lists
[ "calculate", "the", "nesting", "count", "of", "google", "doc", "lists" ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/utils/html2text.py#L718-L723
train
208,991
iamaziz/PyDataset
pydataset/utils/html2text.py
HTML2Text.optwrap
def optwrap(self, text): """Wrap all paragraphs in the provided text.""" if not self.body_width: return text assert wrap, "Requires Python 2.3." result = '' newlines = 0 for para in text.split("\n"): if len(para) > 0: if not skipwrap(para): result += "\n".join(wrap(para, self.body_width)) if para.endswith(' '): result += " \n" newlines = 1 else: result += "\n\n" newlines = 2 else: if not onlywhite(para): result += para + "\n" newlines = 1 else: if newlines < 2: result += "\n" newlines += 1 return result
python
def optwrap(self, text): """Wrap all paragraphs in the provided text.""" if not self.body_width: return text assert wrap, "Requires Python 2.3." result = '' newlines = 0 for para in text.split("\n"): if len(para) > 0: if not skipwrap(para): result += "\n".join(wrap(para, self.body_width)) if para.endswith(' '): result += " \n" newlines = 1 else: result += "\n\n" newlines = 2 else: if not onlywhite(para): result += para + "\n" newlines = 1 else: if newlines < 2: result += "\n" newlines += 1 return result
[ "def", "optwrap", "(", "self", ",", "text", ")", ":", "if", "not", "self", ".", "body_width", ":", "return", "text", "assert", "wrap", ",", "\"Requires Python 2.3.\"", "result", "=", "''", "newlines", "=", "0", "for", "para", "in", "text", ".", "split", ...
Wrap all paragraphs in the provided text.
[ "Wrap", "all", "paragraphs", "in", "the", "provided", "text", "." ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/utils/html2text.py#L726-L752
train
208,992
iamaziz/PyDataset
pydataset/support.py
similarity
def similarity(w1, w2, threshold=0.5): """compare two strings 'words', and return ratio of smiliarity, be it larger than the threshold, or 0 otherwise. NOTE: if the result more like junk, increase the threshold value. """ ratio = SM(None, str(w1).lower(), str(w2).lower()).ratio() return ratio if ratio > threshold else 0
python
def similarity(w1, w2, threshold=0.5): """compare two strings 'words', and return ratio of smiliarity, be it larger than the threshold, or 0 otherwise. NOTE: if the result more like junk, increase the threshold value. """ ratio = SM(None, str(w1).lower(), str(w2).lower()).ratio() return ratio if ratio > threshold else 0
[ "def", "similarity", "(", "w1", ",", "w2", ",", "threshold", "=", "0.5", ")", ":", "ratio", "=", "SM", "(", "None", ",", "str", "(", "w1", ")", ".", "lower", "(", ")", ",", "str", "(", "w2", ")", ".", "lower", "(", ")", ")", ".", "ratio", "...
compare two strings 'words', and return ratio of smiliarity, be it larger than the threshold, or 0 otherwise. NOTE: if the result more like junk, increase the threshold value.
[ "compare", "two", "strings", "words", "and", "return", "ratio", "of", "smiliarity", "be", "it", "larger", "than", "the", "threshold", "or", "0", "otherwise", "." ]
789c0ca7587b86343f636b132dcf1f475ee6b90b
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/support.py#L12-L20
train
208,993
MouseLand/rastermap
rastermap/roi.py
triangle_area
def triangle_area(p0, p1, p2): if p2.ndim < 2: p2 = p2[np.newaxis, :] '''p2 can be a vector''' area = 0.5 * np.abs(p0[0] * p1[1] - p0[0] * p2[:,1] + p1[0] * p2[:,1] - p1[0] * p0[1] + p2[:,0] * p0[1] - p2[:,0] * p1[1]) return area
python
def triangle_area(p0, p1, p2): if p2.ndim < 2: p2 = p2[np.newaxis, :] '''p2 can be a vector''' area = 0.5 * np.abs(p0[0] * p1[1] - p0[0] * p2[:,1] + p1[0] * p2[:,1] - p1[0] * p0[1] + p2[:,0] * p0[1] - p2[:,0] * p1[1]) return area
[ "def", "triangle_area", "(", "p0", ",", "p1", ",", "p2", ")", ":", "if", "p2", ".", "ndim", "<", "2", ":", "p2", "=", "p2", "[", "np", ".", "newaxis", ",", ":", "]", "area", "=", "0.5", "*", "np", ".", "abs", "(", "p0", "[", "0", "]", "*"...
p2 can be a vector
[ "p2", "can", "be", "a", "vector" ]
eee7a46db80b6e33207543778e11618d0fed08a6
https://github.com/MouseLand/rastermap/blob/eee7a46db80b6e33207543778e11618d0fed08a6/rastermap/roi.py#L5-L12
train
208,994
MouseLand/rastermap
rastermap/roi.py
gROI.inROI
def inROI(self, Y): '''which points are inside ROI''' if Y.ndim > 1: area = np.zeros((Y.shape[0],4)) else: area = np.zeros((1,4)) pts = np.zeros((0,), int) pdist = np.zeros((0,), int) dist0 = 0 for k in range(len(self.prect)): self.square_area = (triangle_area(self.prect[k][0,:], self.prect[k][1,:], self.prect[k][2,:]) + triangle_area(self.prect[k][2,:], self.prect[k][3,:], self.prect[k][4,:])) for n in range(4): area[:,n] = triangle_area(self.prect[k][0+n,:], self.prect[k][1+n,:], Y) # points inside prect newpts = np.array((area.sum(axis=1) <= self.square_area+1e-5).nonzero()).flatten().astype(int) if newpts.size > 0: pts = np.concatenate((pts, newpts)) newdists = self.orthproj(Y[newpts, :], k) + dist0 pdist = np.concatenate((pdist, newdists)) dist0 += (np.diff(self.pos[k], axis=0)[0,:]**2).sum() # check if in radius of circle if k < len(self.prect)-1: pcent = self.pos[k][1,:] dist = ((Y - pcent[np.newaxis,:])**2).sum(axis=1)**0.5 newpts = np.array((dist<=self.d).nonzero()[0].astype(int)) if newpts.size > 0: pts = np.concatenate((pts, newpts)) newdists = dist0 * np.ones(newpts.shape) pdist = np.concatenate((pdist, newdists)) pts, inds = np.unique(pts, return_index=True) pdist = pdist[inds] return pts, pdist
python
def inROI(self, Y): '''which points are inside ROI''' if Y.ndim > 1: area = np.zeros((Y.shape[0],4)) else: area = np.zeros((1,4)) pts = np.zeros((0,), int) pdist = np.zeros((0,), int) dist0 = 0 for k in range(len(self.prect)): self.square_area = (triangle_area(self.prect[k][0,:], self.prect[k][1,:], self.prect[k][2,:]) + triangle_area(self.prect[k][2,:], self.prect[k][3,:], self.prect[k][4,:])) for n in range(4): area[:,n] = triangle_area(self.prect[k][0+n,:], self.prect[k][1+n,:], Y) # points inside prect newpts = np.array((area.sum(axis=1) <= self.square_area+1e-5).nonzero()).flatten().astype(int) if newpts.size > 0: pts = np.concatenate((pts, newpts)) newdists = self.orthproj(Y[newpts, :], k) + dist0 pdist = np.concatenate((pdist, newdists)) dist0 += (np.diff(self.pos[k], axis=0)[0,:]**2).sum() # check if in radius of circle if k < len(self.prect)-1: pcent = self.pos[k][1,:] dist = ((Y - pcent[np.newaxis,:])**2).sum(axis=1)**0.5 newpts = np.array((dist<=self.d).nonzero()[0].astype(int)) if newpts.size > 0: pts = np.concatenate((pts, newpts)) newdists = dist0 * np.ones(newpts.shape) pdist = np.concatenate((pdist, newdists)) pts, inds = np.unique(pts, return_index=True) pdist = pdist[inds] return pts, pdist
[ "def", "inROI", "(", "self", ",", "Y", ")", ":", "if", "Y", ".", "ndim", ">", "1", ":", "area", "=", "np", ".", "zeros", "(", "(", "Y", ".", "shape", "[", "0", "]", ",", "4", ")", ")", "else", ":", "area", "=", "np", ".", "zeros", "(", ...
which points are inside ROI
[ "which", "points", "are", "inside", "ROI" ]
eee7a46db80b6e33207543778e11618d0fed08a6
https://github.com/MouseLand/rastermap/blob/eee7a46db80b6e33207543778e11618d0fed08a6/rastermap/roi.py#L100-L133
train
208,995
MouseLand/rastermap
rastermap/isorec.py
dwrap
def dwrap(kx,nc): '''compute a wrapped distance''' q1 = np.mod(kx, nc) q2 = np.minimum(q1, nc-q1) return q2
python
def dwrap(kx,nc): '''compute a wrapped distance''' q1 = np.mod(kx, nc) q2 = np.minimum(q1, nc-q1) return q2
[ "def", "dwrap", "(", "kx", ",", "nc", ")", ":", "q1", "=", "np", ".", "mod", "(", "kx", ",", "nc", ")", "q2", "=", "np", ".", "minimum", "(", "q1", ",", "nc", "-", "q1", ")", "return", "q2" ]
compute a wrapped distance
[ "compute", "a", "wrapped", "distance" ]
eee7a46db80b6e33207543778e11618d0fed08a6
https://github.com/MouseLand/rastermap/blob/eee7a46db80b6e33207543778e11618d0fed08a6/rastermap/isorec.py#L226-L230
train
208,996
MouseLand/rastermap
rastermap/isorec.py
Rastermap.transform
def transform(self, X): """ if already fit, can add new points and see where they fall""" iclustup = [] dims = self.n_components if hasattr(self, 'isort1'): if X.shape[1] == self.v.shape[0]: # reduce dimensionality of X X = X @ self.v nclust = self.n_X AtS = self.A.T @ self.S vnorm = np.sum(self.S * (self.A @ AtS), axis=0)[np.newaxis,:] cv = X @ AtS cmap = np.maximum(0., cv)**2 / vnorm iclustup, cmax = upsample(np.sqrt(cmap), dims, nclust, 10) else: print('ERROR: new points do not have as many features as original data') else: print('ERROR: need to fit model first before you can embed new points') if iclustup.ndim > 1: iclustup = iclustup.T else: iclustup = iclustup.flatten() return iclustup
python
def transform(self, X): """ if already fit, can add new points and see where they fall""" iclustup = [] dims = self.n_components if hasattr(self, 'isort1'): if X.shape[1] == self.v.shape[0]: # reduce dimensionality of X X = X @ self.v nclust = self.n_X AtS = self.A.T @ self.S vnorm = np.sum(self.S * (self.A @ AtS), axis=0)[np.newaxis,:] cv = X @ AtS cmap = np.maximum(0., cv)**2 / vnorm iclustup, cmax = upsample(np.sqrt(cmap), dims, nclust, 10) else: print('ERROR: new points do not have as many features as original data') else: print('ERROR: need to fit model first before you can embed new points') if iclustup.ndim > 1: iclustup = iclustup.T else: iclustup = iclustup.flatten() return iclustup
[ "def", "transform", "(", "self", ",", "X", ")", ":", "iclustup", "=", "[", "]", "dims", "=", "self", ".", "n_components", "if", "hasattr", "(", "self", ",", "'isort1'", ")", ":", "if", "X", ".", "shape", "[", "1", "]", "==", "self", ".", "v", "...
if already fit, can add new points and see where they fall
[ "if", "already", "fit", "can", "add", "new", "points", "and", "see", "where", "they", "fall" ]
eee7a46db80b6e33207543778e11618d0fed08a6
https://github.com/MouseLand/rastermap/blob/eee7a46db80b6e33207543778e11618d0fed08a6/rastermap/isorec.py#L325-L347
train
208,997
meejah/txtorcon
examples/webui_server.py
TorPage.goingLive
def goingLive(self, ctx, client): ''' Overrides nevow method; not really safe to just save ctx, client in self for multiple clients, but nice and simple. ''' self.ctx = ctx self.client = client
python
def goingLive(self, ctx, client): ''' Overrides nevow method; not really safe to just save ctx, client in self for multiple clients, but nice and simple. ''' self.ctx = ctx self.client = client
[ "def", "goingLive", "(", "self", ",", "ctx", ",", "client", ")", ":", "self", ".", "ctx", "=", "ctx", "self", ".", "client", "=", "client" ]
Overrides nevow method; not really safe to just save ctx, client in self for multiple clients, but nice and simple.
[ "Overrides", "nevow", "method", ";", "not", "really", "safe", "to", "just", "save", "ctx", "client", "in", "self", "for", "multiple", "clients", "but", "nice", "and", "simple", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/examples/webui_server.py#L40-L47
train
208,998
meejah/txtorcon
txtorcon/_microdesc_parser.py
MicrodescriptorParser._router_address
def _router_address(self, data): """only for IPv6 addresses""" args = data.split()[1:] try: self._relay_attrs['ip_v6'].extend(args) except KeyError: self._relay_attrs['ip_v6'] = list(args)
python
def _router_address(self, data): """only for IPv6 addresses""" args = data.split()[1:] try: self._relay_attrs['ip_v6'].extend(args) except KeyError: self._relay_attrs['ip_v6'] = list(args)
[ "def", "_router_address", "(", "self", ",", "data", ")", ":", "args", "=", "data", ".", "split", "(", ")", "[", "1", ":", "]", "try", ":", "self", ".", "_relay_attrs", "[", "'ip_v6'", "]", ".", "extend", "(", "args", ")", "except", "KeyError", ":",...
only for IPv6 addresses
[ "only", "for", "IPv6", "addresses" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/_microdesc_parser.py#L98-L104
train
208,999