INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Add custom args to the email globaly or to a specific Personalization :param value: A CustomArg object or a dict of custom arg key/values :type value: CustomArg, dict
def add_custom_arg(self, custom_arg): """Add custom args to the email globaly or to a specific Personalization :param value: A CustomArg object or a dict of custom arg key/values :type value: CustomArg, dict """ if custom_arg.personalization is not None: try: ...
Add custom args to the email :param value: A list of CustomArg objects or a dict of custom arg key/values :type value: CustomArg, list(CustomArg), dict
def custom_arg(self, custom_arg): """Add custom args to the email :param value: A list of CustomArg objects or a dict of custom arg key/values :type value: CustomArg, list(CustomArg), dict """ if isinstance(custom_arg, list): for c in custom_arg...
A unix timestamp specifying when your email should be delivered. :param value: A unix timestamp specifying when your email should be delivered. :type value: SendAt, int
def send_at(self, value): """A unix timestamp specifying when your email should be delivered. :param value: A unix timestamp specifying when your email should be delivered. :type value: SendAt, int """ if isinstance(value, SendAt): if value.personaliz...
The email address of the sender :param value: The email address of the sender :type value: From, str, tuple
def from_email(self, value): """The email address of the sender :param value: The email address of the sender :type value: From, str, tuple """ if isinstance(value, str): value = From(value, None) if isinstance(value, tuple): value = From(value[0]...
The reply to email address :param value: The reply to email address :type value: ReplyTo, str, tuple
def reply_to(self, value): """The reply to email address :param value: The reply to email address :type value: ReplyTo, str, tuple """ if isinstance(value, str): value = ReplyTo(value, None) if isinstance(value, tuple): value = ReplyTo(value[0], v...
The content(s) of the email :param contents: The content(s) of the email :type contents: Content, list(Content)
def content(self, contents): """The content(s) of the email :param contents: The content(s) of the email :type contents: Content, list(Content) """ if isinstance(contents, list): for c in contents: self.add_content(c) else: self.ad...
Add content to the email :param contents: Content to be added to the email :type contents: Content :param mime_type: Override the mime type :type mime_type: MimeType, str
def add_content(self, content, mime_type=None): """Add content to the email :param contents: Content to be added to the email :type contents: Content :param mime_type: Override the mime type :type mime_type: MimeType, str """ if isinstance(content, str): ...
Add attachment(s) to this email :param attachment: Add attachment(s) to this email :type attachment: Attachment, list(Attachment)
def attachment(self, attachment): """Add attachment(s) to this email :param attachment: Add attachment(s) to this email :type attachment: Attachment, list(Attachment) """ if isinstance(attachment, list): for a in attachment: self.add_attachment(a) ...
Add an attachment to this email :param attachment: Add an attachment to this email :type attachment: Attachment
def add_attachment(self, attachment): """Add an attachment to this email :param attachment: Add an attachment to this email :type attachment: Attachment """ self._attachments = self._ensure_append(attachment, self._attachments)
The transactional template id for this email :param value: The transactional template id for this email :type value: TemplateId
def template_id(self, value): """The transactional template id for this email :param value: The transactional template id for this email :type value: TemplateId """ if isinstance(value, TemplateId): self._template_id = value else: self._template_i...
The block sections of code to be used as substitutions :rtype: Section, list(Section)
def section(self, section): """The block sections of code to be used as substitutions :rtype: Section, list(Section) """ if isinstance(section, list): for h in section: self.add_section(h) else: self.add_section(section)
A block section of code to be used as substitutions :param section: A block section of code to be used as substitutions :type section: Section
def add_section(self, section): """A block section of code to be used as substitutions :param section: A block section of code to be used as substitutions :type section: Section """ self._sections = self._ensure_append(section, self._sections)
Add categories assigned to this message :rtype: list(Category)
def category(self, categories): """Add categories assigned to this message :rtype: list(Category) """ if isinstance(categories, list): for c in categories: self.add_category(c) else: self.add_category(categories)
Add a category assigned to this message :rtype: Category
def add_category(self, category): """Add a category assigned to this message :rtype: Category """ self._categories = self._ensure_append(category, self._categories)
Get a JSON-ready representation of this Mail object. :returns: This Mail object, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this Mail object. :returns: This Mail object, ready for use in a request body. :rtype: dict """ mail = { 'from': self._get_or_none(self.from_email), 'subject': self._get_or_none(self.subject), ...
Create a Mail object from an instance of email.message.EmailMessage. :type message: email.message.EmailMessage :rtype: Mail
def from_EmailMessage(cls, message): """Create a Mail object from an instance of email.message.EmailMessage. :type message: email.message.EmailMessage :rtype: Mail """ mail = cls( from_email=Email(message.get('From')), subject=message.get('Subject...
Get a JSON-ready representation of this Ganalytics. :returns: This Ganalytics, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this Ganalytics. :returns: This Ganalytics, ready for use in a request body. :rtype: dict """ keys = ["enable", "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign"] ganalytic...
Get a JSON-ready representation of this FooterSettings. :returns: This FooterSettings, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this FooterSettings. :returns: This FooterSettings, ready for use in a request body. :rtype: dict """ footer_settings = {} if self.enable is not None: footer_settings["enable"] = self.enable ...
Name associated with this email. :param value: Name associated with this email. :type value: string
def name(self, value): """Name associated with this email. :param value: Name associated with this email. :type value: string """ if not (value is None or isinstance(value, str)): raise TypeError('name must be of type string.') # Escape common CSV delimiters...
Allows passing emails as "Example Name <example@example.com>" :param email_info: Allows passing emails as "Example Name <example@example.com>" :type email_info: string
def parse_email(self, email_info): """Allows passing emails as "Example Name <example@example.com>" :param email_info: Allows passing emails as "Example Name <example@example.com>" :type email_info: string """ name, email = rfc822.parseaddr(email_info)...
Get a JSON-ready representation of this Email. :returns: This Email, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this Email. :returns: This Email, ready for use in a request body. :rtype: dict """ email = {} if self.name is not None: email["name"] = self.name if self.email is not None: em...
An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. :param value: An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. :type...
def groups_to_display(self, value): """An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. :param value: An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe ...
The unsubscribe group to associate with this email. :param value: ID of an unsubscribe group :type value: GroupId, int, required
def group_id(self, value): """The unsubscribe group to associate with this email. :param value: ID of an unsubscribe group :type value: GroupId, int, required """ if isinstance(value, GroupId): self._group_id = value else: self._group_id = GroupId...
An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. Max of 25 groups. :param groups_to_display: Unsubscribe groups to display :type groups_to_display: GroupsToDisplay, list(int), optional
def groups_to_display(self, value): """An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. Max of 25 groups. :param groups_to_display: Unsubscribe groups to display :type groups_to_display: GroupsToDisplay, list(int), optio...
Get a JSON-ready representation of this ASM object. :returns: This ASM object, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this ASM object. :returns: This ASM object, ready for use in a request body. :rtype: dict """ asm = {} if self.group_id is not None: asm["group_id"] = self.group_id.get() if self.groups_to...
With the JSON dict that will be sent to SendGrid's API, check the content for SendGrid API keys - throw exception if found. :param request_body: The JSON dict that will be sent to SendGrid's API. :type request_body: JSON serializable structure ...
def validate_message_dict(self, request_body): """With the JSON dict that will be sent to SendGrid's API, check the content for SendGrid API keys - throw exception if found. :param request_body: The JSON dict that will be sent to SendGrid's API. ...
With a message string, check to see if it contains a SendGrid API Key If a key is found, throw an exception :param message_string: message that will be sent :type message_string: string :raises ApiKeyIncludedException: If message_string matches a regex ...
def validate_message_text(self, message_string): """With a message string, check to see if it contains a SendGrid API Key If a key is found, throw an exception :param message_string: message that will be sent :type message_string: string :raises ApiKeyIncludedExcept...
Get a dict of personalization mock.
def get_mock_personalization_dict(): """Get a dict of personalization mock.""" mock_pers = dict() mock_pers['to_list'] = [To("test1@example.com", "Example User"), To("test2@example.com", "Example User")] mo...
Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content. Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md
def build_attachment1(): """Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content. Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md""" attachment = Attachment() attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3I...
Build attachment mock.
def build_attachment2(): """Build attachment mock.""" attachment = Attachment() attachment.content = "BwdW" attachment.type = "image/png" attachment.filename = "banner.png" attachment.disposition = "inline" attachment.content_id = "Banner" return attachment
All settings set
def build_kitchen_sink(): """All settings set""" from sendgrid.helpers.mail import ( Mail, From, To, Cc, Bcc, Subject, PlainTextContent, HtmlContent, SendGridException, Substitution, Header, CustomArg, SendAt, Content, MimeType, Attachment, FileName, FileContent, FileType, Disp...
Allow variables assigned in .env available using os.environ.get('VAR_NAME')
def init_environment(): """Allow variables assigned in .env available using os.environ.get('VAR_NAME')""" base_path = os.path.abspath(os.path.dirname(__file__)) env_path = '{0}/.env'.format(base_path) if os.path.exists(env_path): with open(env_path) as f: ...
Get a JSON-ready representation of this MailSettings. :returns: This MailSettings, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this MailSettings. :returns: This MailSettings, ready for use in a request body. :rtype: dict """ mail_settings = {} if self.bcc_settings is not None: mail_settings["bcc"] = self.bcc_settings.get()...
Get a JSON-ready representation of this Substitution. :returns: This Substitution, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this Substitution. :returns: This Substitution, ready for use in a request body. :rtype: dict """ substitution = {} if self.key is not None and self.value is not None: substitution[self.key] = self...
Get a JSON-ready representation of this Header. :returns: This Header, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this Header. :returns: This Header, ready for use in a request body. :rtype: dict """ header = {} if self.key is not None and self.value is not None: header[self.key] = self.value return he...
Return a dictionary of key/values in the payload received from the webhook
def key_values(self): """ Return a dictionary of key/values in the payload received from the webhook """ key_values = {} for key in self.keys: if key in self.payload: key_values[key] = self.payload[key] return key_values
This only applies to raw payloads: https://sendgrid.com/docs/Classroom/Basics/Inbound_Parse_Webhook/setting_up_the_inbound_parse_webhook.html#-Raw-Parameters
def get_raw_email(self): """ This only applies to raw payloads: https://sendgrid.com/docs/Classroom/Basics/Inbound_Parse_Webhook/setting_up_the_inbound_parse_webhook.html#-Raw-Parameters """ if 'email' in self.payload: raw_email = email.message_from_string(self.payloa...
Returns an object with: type = file content type file_name = the name of the file contents = base64 encoded file contents
def attachments(self): """Returns an object with: type = file content type file_name = the name of the file contents = base64 encoded file contents""" attachments = None if 'attachment-info' in self.payload: attachments = self._get_attachments(self.request) ...
decouple, allow for modifications to return type returns a list of ip addresses in object or json form
def format_ret(return_set, as_json=False): """ decouple, allow for modifications to return type returns a list of ip addresses in object or json form """ ret_list = list() for item in return_set: d = {"ip": item} ret_list.append(d) if as_json: return json.dumps(ret_list)...
https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses The /ips rest endpoint returns information about the IP addresses and the usernames assigned to an IP unassigned returns a listing of the IP addresses that are allocated but have 0 users assigned data (response.b...
def unassigned(data, as_json=False): """ https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses The /ips rest endpoint returns information about the IP addresses and the usernames assigned to an IP unassigned returns a listing of the IP addresses that are allocated but hav...
Add a single recipient to this Personalization. :type email: Email
def add_to(self, email): """Add a single recipient to this Personalization. :type email: Email """ if email.substitutions: if isinstance(email.substitutions, list): for substitution in email.substitutions: self.add_substitution(substitutio...
Add a new Substitution to this Personalization. :type substitution: Substitution
def add_substitution(self, substitution): """Add a new Substitution to this Personalization. :type substitution: Substitution """ if isinstance(substitution, dict): self._substitutions.append(substitution) else: self._substitutions.append(substitution.get...
Get a JSON-ready representation of this Personalization. :returns: This Personalization, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this Personalization. :returns: This Personalization, ready for use in a request body. :rtype: dict """ personalization = {} for key in ['tos', 'ccs', 'bccs']: value = getattr(self, key) ...
Get a JSON-ready representation of this CustomArg. :returns: This CustomArg, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this CustomArg. :returns: This CustomArg, ready for use in a request body. :rtype: dict """ custom_arg = {} if self.key is not None and self.value is not None: custom_arg[self.key] = self.value ...
Get a JSON-ready representation of this Section. :returns: This Section, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this Section. :returns: This Section, ready for use in a request body. :rtype: dict """ section = {} if self.key is not None and self.value is not None: section[self.key] = self.value retur...
Get a JSON-ready representation of this ClickTracking. :returns: This ClickTracking, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this ClickTracking. :returns: This ClickTracking, ready for use in a request body. :rtype: dict """ click_tracking = {} if self.enable is not None: click_tracking["enable"] = self.enable i...
Get a JSON-ready representation of this SubscriptionTracking. :returns: This SubscriptionTracking, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this SubscriptionTracking. :returns: This SubscriptionTracking, ready for use in a request body. :rtype: dict """ subscription_tracking = {} if self.enable is not None: subscription_tracking["enabl...
Get a JSON-ready representation of this TrackingSettings. :returns: This TrackingSettings, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this TrackingSettings. :returns: This TrackingSettings, ready for use in a request body. :rtype: dict """ tracking_settings = {} if self.click_tracking is not None: tracking_settings["click_trackin...
Get a JSON-ready representation of this OpenTracking. :returns: This OpenTracking, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this OpenTracking. :returns: This OpenTracking, ready for use in a request body. :rtype: dict """ open_tracking = {} if self.enable is not None: open_tracking["enable"] = self.enable if se...
:return: response stats dict
def get(self): """ :return: response stats dict """ stats = {} if self.start_date is not None: stats["start_date"] = self.start_date if self.end_date is not None: stats["end_date"] = self.end_date if self.aggregated_by is not None: ...
The Base64 encoded content of the attachment :param value: The Base64 encoded content of the attachment :type value: FileContent, string
def file_content(self, value): """The Base64 encoded content of the attachment :param value: The Base64 encoded content of the attachment :type value: FileContent, string """ if isinstance(value, FileContent): self._file_content = value else: self...
The filename of the attachment :param file_name: The filename of the attachment :type file_name: FileName, string
def file_name(self, value): """The filename of the attachment :param file_name: The filename of the attachment :type file_name: FileName, string """ if isinstance(value, FileName): self._file_name = value else: self._file_name = FileName(value)
The MIME type of the content you are attaching :param file_type: The MIME type of the content you are attaching :type file_type FileType, string, optional
def file_type(self, value): """The MIME type of the content you are attaching :param file_type: The MIME type of the content you are attaching :type file_type FileType, string, optional """ if isinstance(value, FileType): self._file_type = value else: ...
The content-disposition of the attachment, specifying display style. Specifies how you would like the attachment to be displayed. - "inline" results in the attached file being displayed automatically within the message. - "attachment" results in the attached file requiring some ac...
def disposition(self, value): """The content-disposition of the attachment, specifying display style. Specifies how you would like the attachment to be displayed. - "inline" results in the attached file being displayed automatically within the message. - "attachment" resul...
The content id for the attachment. This is used when the disposition is set to "inline" and the attachment is an image, allowing the file to be displayed within the email body. :param content_id: The content id for the attachment. This is used when the Disposition is...
def content_id(self, value): """The content id for the attachment. This is used when the disposition is set to "inline" and the attachment is an image, allowing the file to be displayed within the email body. :param content_id: The content id for the attachment. ...
Get a JSON-ready representation of this Attachment. :returns: This Attachment, ready for use in a request body. :rtype: dict
def get(self): """ Get a JSON-ready representation of this Attachment. :returns: This Attachment, ready for use in a request body. :rtype: dict """ attachment = {} if self.file_content is not None: attachment["content"] = self.file_content.get() ...
Execute computation of blobs on input eopatch :param eopatch: Input eopatch :type eopatch: eolearn.core.EOPatch :return: EOPatch instance with new key holding the blob image. :rtype: eolearn.core.EOPatch
def execute(self, eopatch): """ Execute computation of blobs on input eopatch :param eopatch: Input eopatch :type eopatch: eolearn.core.EOPatch :return: EOPatch instance with new key holding the blob image. :rtype: eolearn.core.EOPatch """ for feature_type, featu...
Check if the classifier implements predict and predict_proba methods.
def _check_classifier(classifier): """ Check if the classifier implements predict and predict_proba methods. """ predict = getattr(classifier, "predict", None) if not callable(predict): raise ValueError('Classifier does not have predict method!') pred...
Checks the image size and its compatibility with classifier's receptive field. At this moment it is required that image size = K * receptive_field. This will be relaxed in future with the introduction of padding.
def _check_image(self, X): """ Checks the image size and its compatibility with classifier's receptive field. At this moment it is required that image size = K * receptive_field. This will be relaxed in future with the introduction of padding. """ if (len(X.shap...
Predicts class label for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_pixels_x] Target labels or masks.
def image_predict(self, X): """ Predicts class label for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_p...
Predicts class probabilities for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_x, n_pixels_y, n_classes] Target pr...
def image_predict_proba(self, X): """ Predicts class probabilities for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n...
Reshapes input to patches of the size of classifier's receptive field. For example: input X shape: [n_samples, n_pixels_y, n_pixels_x, n_bands] output: [n_samples * n_pixels_y/receptive_field_y * n_pixels_x/receptive_field_x, receptive_field_y, receptive_field_x, n_ban...
def _to_patches(self, X): """ Reshapes input to patches of the size of classifier's receptive field. For example: input X shape: [n_samples, n_pixels_y, n_pixels_x, n_bands] output: [n_samples * n_pixels_y/receptive_field_y * n_pixels_x/receptive_field_x, ...
Predicts class label for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_pixels_x] Target labels or masks.
def image_predict(self, X): """ Predicts class label for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_p...
Predicts class probabilities for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_x, n_pixels_y, n_classes] Target pr...
def image_predict_proba(self, X): """ Predicts class probabilities for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n...
Reshapes input to patches of the size of classifier's receptive field. For example: input X shape: [n_samples, n_pixels_y, n_pixels_x, n_bands] output: [n_samples * n_pixels_y/receptive_field_y * n_pixels_x/receptive_field_x, receptive_field_y, receptive_field_x, n_ban...
def _to_patches(self, X): """ Reshapes input to patches of the size of classifier's receptive field. For example: input X shape: [n_samples, n_pixels_y, n_pixels_x, n_bands] output: [n_samples * n_pixels_y/receptive_field_y * n_pixels_x/receptive_field_x, ...
Predicts class label for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_pixels_x] Target labels or masks.
def image_predict(self, X): """ Predicts class label for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_p...
Predicts class probabilities for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_x, n_pixels_y, n_classes] Target pr...
def image_predict_proba(self, X): """ Predicts class probabilities for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n...
Transforms [n, w, h, d] eopatch into a [n, w, h, 1] eopatch, adding it the classification mask. :param eopatch: An input EOPatch :type eopatch: EOPatch :return: Outputs EOPatch with n classification masks appended to out_feature_type with out_feature_name key :rtype...
def execute(self, eopatch): """ Transforms [n, w, h, d] eopatch into a [n, w, h, 1] eopatch, adding it the classification mask. :param eopatch: An input EOPatch :type eopatch: EOPatch :return: Outputs EOPatch with n classification masks appended to out_feature_type with...
Parses execution arguments provided by user and raises an error if something is wrong
def _parse_execution_args(execution_args): """ Parses execution arguments provided by user and raises an error if something is wrong """ if not isinstance(execution_args, (list, tuple)): raise ValueError("Parameter 'execution_args' should be a list") return [EOWorkflow.parse...
Runs the executor with n workers. :param workers: Number of parallel processes used in the execution. Default is a single process. If set to `None` the number of workers will be the number of processors of the system. :type workers: int or None
def run(self, workers=1): """ Runs the executor with n workers. :param workers: Number of parallel processes used in the execution. Default is a single process. If set to `None` the number of workers will be the number of processors of the system. :type workers: int or None ...
Handles a single execution of a workflow
def _execute_workflow(cls, process_args): """ Handles a single execution of a workflow """ workflow, input_args, log_path = process_args if log_path: logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = cls._get_log_handler(log_path) ...
Makes a html report and saves it into the same folder where logs are stored.
def make_report(self): """ Makes a html report and saves it into the same folder where logs are stored. """ if self.execution_stats is None: raise RuntimeError('Cannot produce a report without running the executor first, check EOExecutor.run ' 'method')...
Action to be taken when an event is triggered. Event is scroll of the mouse's wheel. This leads to changing the temporal frame displayed. :param event: Scroll of mouse wheel
def onscroll(self, event): """Action to be taken when an event is triggered. Event is scroll of the mouse's wheel. This leads to changing the temporal frame displayed. :param event: Scroll of mouse wheel """ if event.button == 'up': self.ind = (self.ind + 1)...
Updates image to be displayed with new time frame.
def update(self): """Updates image to be displayed with new time frame.""" if self.single_channel: self.im.set_data(self.data[self.ind, :, :]) else: self.im.set_data(self.data[self.ind, :, :, :]) self.ax.set_ylabel('time frame %s' % self.ind) self.i...
Performs checks on dimensionality of data to makes it suitable for display. :param eopatch: Input eopatch :return: Array to display and whether it is single channel or not
def _get_data_to_display(self, eopatch): """Performs checks on dimensionality of data to makes it suitable for display. :param eopatch: Input eopatch :return: Array to display and whether it is single channel or not """ feature_type, feature_name = next(self.feature(eopatc...
Shows data and scrolls through. Currently not working from Jupyter notebooks. :param eopatch: Image sequence to display. Can be single channel, RGB or multi-channel. If multi-channel, indices must be specified. :type eopatch: numpy array :param title: String to be d...
def execute(self, eopatch, title=None, colorbar=False): """Shows data and scrolls through. Currently not working from Jupyter notebooks. :param eopatch: Image sequence to display. Can be single channel, RGB or multi-channel. If multi-channel, indices must be specified. ...
Compute spatio-temporal features for input eopatch :param eopatch: Input eopatch :return: eopatch with computed spatio-temporal features
def execute(self, eopatch): """ Compute spatio-temporal features for input eopatch :param eopatch: Input eopatch :return: eopatch with computed spatio-temporal features """ # pylint: disable=invalid-name amax_ndvi, amin_ndvi = eopatch.data_timeless[self.argmax_ndvi], eop...
Compute argmax/argmin of specified `data_feature` and `data_index` :param eopatch: Input eopatch :return: eopatch with added argmax/argmin features
def execute(self, eopatch): """ Compute argmax/argmin of specified `data_feature` and `data_index` :param eopatch: Input eopatch :return: eopatch with added argmax/argmin features """ if self.mask_data: valid_data_mask = eopatch.mask['VALID_DATA'] else: ...
Computation of NDVI slope using finite central differences This implementation loops through every spatial location, considers the valid NDVI values and approximates their first order derivative using central differences. The argument of min and max is added to the eopatch. The NDVI slope at d...
def execute(self, eopatch): """ Computation of NDVI slope using finite central differences This implementation loops through every spatial location, considers the valid NDVI values and approximates their first order derivative using central differences. The argument of min and max is added to t...
Returns WMS request.
def _get_wms_request(self, bbox, size_x, size_y): """ Returns WMS request. """ bbox_3857 = transform_bbox(bbox, CRS.POP_WEB) return GeopediaWmsRequest(layer=self.layer, theme=self.theme, bbox=bbox_3857, ...
Each request represents a binary class which will be mapped to the scalar `raster_value`
def _map_from_binaries(self, eopatch, dst_shape, request_data): """ Each request represents a binary class which will be mapped to the scalar `raster_value` """ if self.feature_name in eopatch[self.feature_type]: raster = eopatch[self.feature_type][self.feature_name].squeeze(...
`raster_value` is a dictionary specifying the intensity values for each class and the corresponding label value. A dictionary example for GLC30 LULC mapping is: raster_value = {'no_data': (0,[0,0,0,0]), 'cultivated land': (1,[193, 243, 249, 255]), 'forest...
def _map_from_multiclass(self, eopatch, dst_shape, request_data): """ `raster_value` is a dictionary specifying the intensity values for each class and the corresponding label value. A dictionary example for GLC30 LULC mapping is: raster_value = {'no_data': (0,[0,0,0,0]), ...
Add requested feature to this existing EOPatch.
def execute(self, eopatch): """ Add requested feature to this existing EOPatch. """ data_arr = eopatch[FeatureType.MASK]['IS_DATA'] _, height, width, _ = data_arr.shape request = self._get_wms_request(eopatch.bbox, width, height) request_data, = np.asarray(reque...
Collects the parameter either from initialization parameters or from EOPatch
def _get_parameter(self, name, eopatch): """ Collects the parameter either from initialization parameters or from EOPatch """ if hasattr(self, name) and getattr(self, name) is not None: return getattr(self, name) if name == 'bbox' and eopatch.bbox: return eopatch....
Collects all parameters used for DataRequest, each one is taken either from initialization parameters or from EOPatch
def _prepare_request_data(self, eopatch, bbox, time_interval): """ Collects all parameters used for DataRequest, each one is taken either from initialization parameters or from EOPatch """ service_type = ServiceType(self._get_parameter('service_type', eopatch)) if time_interval ...
Adds any missing metadata info to EOPatch
def _add_meta_info(self, eopatch, request_params, service_type): """ Adds any missing metadata info to EOPatch """ for param, eoparam in zip(['time', 'time_difference', 'maxcc'], ['time_interval', 'time_difference', 'maxcc']): if eoparam not in eopatch.meta_info: eopatch.met...
Adds downloaded data to EOPatch
def _add_data(self, eopatch, data): """ Adds downloaded data to EOPatch """ valid_mask = data[..., -1] data = data[..., :-1] if data.ndim == 3: data = data.reshape(data.shape + (1,)) if not self.feature_type.is_time_dependent(): if data.shape[0] > 1: ...
Creates OGC (WMS or WCS) request, downloads requested data and stores it together with valid data mask in newly created EOPatch. Returns the EOPatch. :param eopatch: :type eopatch: EOPatch or None :param bbox: specifies the bounding box of the requested image. Coordinates must be in ...
def execute(self, eopatch=None, bbox=None, time_interval=None): """ Creates OGC (WMS or WCS) request, downloads requested data and stores it together with valid data mask in newly created EOPatch. Returns the EOPatch. :param eopatch: :type eopatch: EOPatch or None :param...
Wrapper function for pixel-based S2 cloud detector `S2PixelCloudDetector`
def get_s2_pixel_cloud_detector(threshold=0.4, average_over=4, dilation_size=2, all_bands=True): """ Wrapper function for pixel-based S2 cloud detector `S2PixelCloudDetector` """ return S2PixelCloudDetector(threshold=threshold, average_over=average_over, ...
Returns WMS request.
def _get_wms_request(self, bbox, time_interval, size_x, size_y, maxcc, time_difference, custom_url_params): """ Returns WMS request. """ return WmsRequest(layer=self.data_feature, bbox=bbox, time=time_interval, ...
Returns WCS request.
def _get_wcs_request(self, bbox, time_interval, size_x, size_y, maxcc, time_difference, custom_url_params): """ Returns WCS request. """ return WcsRequest(layer=self.data_feature, bbox=bbox, time=time_interval, ...
Compute the resampling factor for height and width of the input array :param reference_shape: Tuple specifying height and width in pixels of high-resolution array :type reference_shape: tuple of ints :param meta_info: Meta-info dictionary of input eopatch. Defines OGC request and parameters use...
def _get_rescale_factors(self, reference_shape, meta_info): """ Compute the resampling factor for height and width of the input array :param reference_shape: Tuple specifying height and width in pixels of high-resolution array :type reference_shape: tuple of ints :param meta_info: Meta-...
Downscale existing array to resolution requested by cloud detector :param hr_array: High-resolution data array to be downscaled :param meta_info: Meta-info of eopatch :param interp: Interpolation method to be used in downscaling. Default is `'linear'` :param smooth: Apply Gaussian smoot...
def _downscaling(self, hr_array, meta_info, interp='linear', smooth=True): """ Downscale existing array to resolution requested by cloud detector :param hr_array: High-resolution data array to be downscaled :param meta_info: Meta-info of eopatch :param interp: Interpolation method to be...
Upsample the low-resolution array to the original high-resolution grid :param lr_array: Low-resolution array to be upsampled :param rescale: Rescale factor for rows/columns :param reference_shape: Original size of high-resolution eopatch. Tuple with dimension for time, height and ...
def _upsampling(lr_array, rescale, reference_shape, interp='linear'): """ Upsample the low-resolution array to the original high-resolution grid :param lr_array: Low-resolution array to be upsampled :param rescale: Rescale factor for rows/columns :param reference_shape: Original size of...
Make OGC request to create input for cloud detector classifier :param bbox: Bounding box :param meta_info: Meta-info dictionary of input eopatch :return: Requested data
def _make_request(self, bbox, meta_info, timestamps): """ Make OGC request to create input for cloud detector classifier :param bbox: Bounding box :param meta_info: Meta-info dictionary of input eopatch :return: Requested data """ service_type = ServiceType(meta_info['se...
Add cloud binary mask and (optionally) cloud probability map to input eopatch :param eopatch: Input `EOPatch` instance :return: `EOPatch` with additional cloud maps
def execute(self, eopatch): """ Add cloud binary mask and (optionally) cloud probability map to input eopatch :param eopatch: Input `EOPatch` instance :return: `EOPatch` with additional cloud maps """ # Downsample or make request if not eopatch.data: raise Va...
Handles measuring execution time and error propagation
def _execute_handling(self, *eopatches, **kwargs): """ Handles measuring execution time and error propagation """ self.private_task_config.start_time = datetime.datetime.now() caught_exception = None try: return_value = self.execute(*eopatches, **kwargs) ...
See eolearn.core.utilities.FeatureParser class.
def _parse_features(features, new_names=False, rename_function=None, default_feature_type=None, allowed_feature_types=None): """ See eolearn.core.utilities.FeatureParser class. """ return FeatureParser(features, new_names=new_names, rename_function=rename_function, ...
Function which will process README.md file and divide it into INTRO.md and INSTALL.md, which will be used in documentation
def process_readme(): """ Function which will process README.md file and divide it into INTRO.md and INSTALL.md, which will be used in documentation """ with open('../../README.md', 'r') as file: readme = file.read() readme = readme.replace('# eo-learn', '# Introduction').replace('docs/sour...
Return indices of timestamps from source that are also found in target. :param source: timestamps from source :type source: list of datetime objects :param target: timestamps from target :type target: list of datetime objects :return: indices of timestamps from source that are also found in t...
def get_common_timestamps(source, target): """Return indices of timestamps from source that are also found in target. :param source: timestamps from source :type source: list of datetime objects :param target: timestamps from target :type target: list of datetime objects :return: indices...