text:
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import forms
from horizon.utils import memoized
from horizon import tabs

from openstack_dashboard.api import cinder

from horizon_hpe_storage.storage_panel.config import forms as config_forms
from horizon_hpe_storage.storage_panel import tabs as storage_tabs

import uuid
import base64
import re
import time
from urlparse import urlparse

import horizon_hpe_storage.api.hp_ssmc_api as hpssmc
import horizon_hpe_storage.api.keystone_api as keystone
import horizon_hpe_storage.api.barbican_api as barbican

import logging

LOG = logging.getLogger(__name__)

class IndexView(tabs.TabbedTableView):
    tab_group_class = storage_tabs.StorageTabs
    template_name = 'config/index.html'

class CreateEndpointView(forms.ModalFormView):
    form_class = config_forms.CreateEndpoint

    modal_header = _("Create Link")
    modal_id = "create_endpoint_modal"
    template_name = 'config/create_endpoint.html'
    submit_label = _("Create Link")
    submit_url = reverse_lazy(
        "horizon:admin:hpe_storage:config:create_endpoint")
    success_url = reverse_lazy('horizon:admin:hpe_storage:index')
    page_title = _("Create SSMC Link")

class EditEndpointView(forms.ModalFormView):
    form_class = config_forms.EditEndpoint
    modal_header = _("Edit Link")
    modal_id = "edit_endpoint_modal"
    template_name = 'config/edit_endpoint.html'
    submit_label = _("Edit Link")
    submit_url = "horizon:admin:hpe_storage:config:edit_endpoint"
    success_url = reverse_lazy('horizon:admin:hpe_storage:index')
    page_title = _("Edit SSMC Link")

    def get_context_data(self, **kwargs):
        context = super(EditEndpointView, self).get_context_data(**kwargs)
        args = (self.kwargs['service_id'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        return context

    def get_initial(self):
        service_id = self.kwargs['service_id']
        return {'service_id': service_id}

class BaseLinkView(forms.ModalFormView):
    form_class = config_forms.LinkToSSMC
    modal_header = _("Link to SSMC")
    modal_id = "link_to_SSMC_modal"
    template_name = 'config/link_and_launch.html'
    submit_label = _("Link")
    success_url = 'horizon:admin:volumes:volumes_tab'
    page_title = _("Linking to SSMC...")
    host = None
    keystone_api = keystone.KeystoneAPI()
    barbican_api = barbican.BarbicanAPI()
    ssmc_api = None

    tokens = {}

    def get_cache_value(self, key):
        if key in self.tokens:
            return self.tokens[key]
        else:
            return None

    def get_SSMC_endpoint(self, volume, snapshot=None, getCGroup=False):
        self.keystone_api.do_setup(self.request)
        self.barbican_api.do_setup(self.keystone_api.get_session())

        host_name = getattr(volume, 'os-vol-host-attr:host', None)
        # pull out host from host name (comes between @ and #)
        found = re.search('@(.+?)#', host_name)
        if found:
            self.host = found.group(1)
        else:
            return None
        endpt = self.keystone_api.get_ssmc_endpoint_for_host(self.host)
        uname, pwd = self.barbican_api.get_ssmc_credentials(self.host)

        if endpt:
            # attempt to use previous token for the SSMC endpoint, if it exists
            ssmc_instance = urlparse(endpt).netloc
            ssmc_token = self.get_cache_value(
                'ssmc-link-' + ssmc_instance)
            ssmc_token_last_access_time = self.get_cache_value(
                'ssmc-link-timer-' + ssmc_instance)

            if ssmc_token:
                # SSMC tokens last for 15 minutes (default)
                # throw away token if older than 15 minutes since last access
                cur_time = time.time()
                session_timeout = 14 * 60 + 30     # 15 mins with fudge factor
                if (cur_time - ssmc_token_last_access_time) > session_timeout:
                    ssmc_token = None

            self.ssmc_api = hpssmc.HPSSMC(endpt, uname, pwd, ssmc_token)
            self.ssmc_api.do_setup(None)
            # this call is the bottle neck. Note that SSMC must attempt to
            # login to each of the arrays it manages. And if one of those is
            # down, the timeouts makes this call even longer to complete
            self.ssmc_api.client_login()

            if self.ssmc_api.get_session_key():
                if snapshot:
                    if volume.consistencygroup_id:
                        cgroup_id = volume.consistencygroup_id
                        self.ssmc_api.get_cgroup_info(cgroup_id)
                    else:
                        snapshot_id = getattr(snapshot, "id")
                        self.ssmc_api.get_snapshot_info(snapshot_id)
                elif getCGroup:
                    cgroup_id = volume.consistencygroup_id
                    self.ssmc_api.get_cgroup_info(cgroup_id)
                else:
                    volume_id = getattr(volume, "id")
                    self.ssmc_api.get_volume_info(volume_id)

                if not ssmc_token:
                    self.tokens['ssmc-link-' + ssmc_instance] = \
                        self.ssmc_api.get_session_key()
                    self.tokens['ssmc-link-timer-' + ssmc_instance] = \
                        time.time()

                return endpt
            else:
                cache.delete('ssmc-link-' + self.host)
                raise ValueError("Unable to login to HPE 3PAR SSMC")
        else:
            raise ValueError(
                "SSMC Endpoint does not exist for this backend host")

        return None

    def logout_SSMC_session(self):
        # logout of session
        self.ssmc_api.client_logout()
        cache.delete('ssmc-link-' + self.host)

class LinkVolumeView(BaseLinkView):
    submit_url = 'horizon:admin:hpe_storage:config:link_to_volume'

    def get_context_data(self, **kwargs):
        context = super(LinkVolumeView, self).get_context_data(**kwargs)
        args = (self.kwargs['volume_id'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        context['link_url'] = kwargs['form'].initial['link_url']
        return context

    @memoized.memoized_method
    def get_data(self):
        try:
            # from openstack_dashboard import policy
            # allowed = policy.check((("volume","volume:create"),),
            # self.request)
            volume_id = self.kwargs['volume_id']
            volume = cinder.volume_get(self.request, volume_id)

            # volume_name = self.get_3par_vol_name(volume_id)
            # LOG.info(("deep link - get keystone token for vol = %s") %
            # volume_name)
            # formatted_vol_name = format(volume_name)
            LOG.info(("deep link - get keystone token for vol = %s") %
                     volume.name)

            # get volume data to build URI to SSMC
            endpoint = self.get_SSMC_endpoint(volume)
            LOG.info(("deep-link - Session Token = %s") %
                     self.ssmc_api.get_session_key())

            if endpoint:
                # "0:url=" is needed for redirect tag for page
                # url = "0;url=" + endpoint + '#/virtual-volumes/show/'\
                #         'capacity/r/provisioning/REST/volumeviewservice/' \
                #         'systems/' + self.ssmc_api.get_system_wwn() + \
                #         '/volumes/' + self.ssmc_api.get_volume_id() + \
                #         '?sessionToken=' + self.ssmc_api.get_session_key()
                ref = urlparse(self.ssmc_api.get_volume_ref())
                url = "0;url=" + endpoint + \
                      '#/virtual-volumes/show/capacity/r' + \
                      ref.path + '?sessionToken=' + \
                      self.ssmc_api.get_session_key()

                # USE if we want user to log in every time
                # self.logout_SSMC_session()
                LOG.info(("deep-link - SSMC URL = %s") % url)
                return volume, url

        except ValueError as err:
            url = reverse('horizon:admin:volumes:volumes_tab')
            exceptions.handle(self.request,
                              err.message,
                              redirect=url)
        except Exception as err:
            LOG.info(("deep-link error = %s") % err.message)
            exceptions.handle(self.request,
                              _('Unable to retrieve volume details.'),
                              redirect=self.success_url)

    def get_initial(self):
        volume, link_url = self.get_data()
        return {'volume_id': self.kwargs["volume_id"],
                'name': volume.name,
                'link_url': link_url}

class LinkVolumeCPGView(BaseLinkView):
    submit_url = 'horizon:admin:hpe_storage:config:link_to_volume_cpg'

    def get_context_data(self, **kwargs):
        context = super(LinkVolumeCPGView, self).get_context_data(**kwargs)
        args = (self.kwargs['volume_id'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        context['link_url'] = kwargs['form'].initial['link_url']
        return context

    @memoized.memoized_method
    def get_data(self):
        try:
            # from openstack_dashboard import policy
            # allowed = policy.check((("volume","volume:create"),),
            # self.request)
            volume_id = self.kwargs['volume_id']
            volume = cinder.volume_get(self.request, volume_id)

            LOG.info(("deep link - get keystone token for vol = %s") %
                     volume.name)

            # get volume data to build URI to SSMC
            endpoint = self.get_SSMC_endpoint(volume)
            LOG.info(("deep-link - Session Token = %s") %
                     self.ssmc_api.get_session_key())
            if endpoint:
                # "0:url=" is needed for redirect tag for page
                url = "0;url=" + endpoint + '#/cpgs/show/'\
                      'overview/r/provisioning/REST/cpgviewservice/' \
                      'systems/' + self.ssmc_api.get_system_wwn() + \
                      '/cpgs/' + self.ssmc_api.get_volume_cpg() + \
                      '?sessionToken=' + self.ssmc_api.get_session_key()

                # USE if we want user to log in every time
                # self.logout_SSMC_session()
                LOG.info(("deep-link - SSMC URL = %s") % url)
                return volume, url

        except ValueError as err:
            url = reverse('horizon:admin:volumes:volumes_tab')
            exceptions.handle(self.request,
                              err.message,
                              redirect=url)
        except Exception as err:
            LOG.info(("deep-link error = %s") % err.message)
            exceptions.handle(self.request,
                              _('Unable to retrieve volume details.'),
                              redirect=self.success_url)

    def get_initial(self):
        volume, link_url = self.get_data()
        return {'volume_id': self.kwargs["volume_id"],
                'name': volume.name,
                'link_url': link_url}

class LinkVolumeDomainView(BaseLinkView):
    submit_url = 'horizon:admin:hpe_storage:config:link_to_volume_domain'

    def get_context_data(self, **kwargs):
        context = super(LinkVolumeDomainView, self).get_context_data(**kwargs)
        args = (self.kwargs['volume_id'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        context['link_url'] = kwargs['form'].initial['link_url']
        return context

    @memoized.memoized_method
    def get_data(self):
        try:
            # from openstack_dashboard import policy
            # allowed = policy.check((("volume","volume:create"),),
            # self.request)
            volume_id = self.kwargs['volume_id']
            volume = cinder.volume_get(self.request, volume_id)

            LOG.info(("deep link - get keystone token for vol = %s") %
                     volume.name)

            # get volume data to build URI to SSMC
            endpoint = self.get_SSMC_endpoint(volume)
            LOG.info(("deep-link - Session Token = %s") %
                     self.ssmc_api.get_session_key())
            if endpoint:
                # "0:url=" is needed for redirect tag for page
                url = "0;url=" + endpoint + '#/domains/show/' \
                      'overview/r/security/REST/domainviewservice/' \
                      'systems/' + self.ssmc_api.get_system_wwn() + \
                      '/domains/' + self.ssmc_api.get_volume_domain() + \
                      '?sessionToken=' + self.ssmc_api.get_session_key()

                # USE if we want user to log in every time
                # self.logout_SSMC_session()
                LOG.info(("deep-link - SSMC URL = %s") % url)
                return volume, url

        except ValueError as err:
            url = reverse('horizon:admin:volumes:volumes_tab')
            exceptions.handle(self.request,
                              err.message,
                              redirect=url)
        except Exception as err:
            LOG.info(("deep-link error = %s") % err.message)
            exceptions.handle(self.request,
                              _('Unable to retrieve volume details.'),
                              redirect=self.success_url)

    def get_initial(self):
        volume, link_url = self.get_data()
        return {'volume_id': self.kwargs["volume_id"],
                'name': volume.name,
                'link_url': link_url}

class LinkVolumeCGroupView(BaseLinkView):
    submit_url = 'horizon:admin:hpe_storage:config:link_to_volume_cgroup'

    def get_context_data(self, **kwargs):
        context = super(LinkVolumeCGroupView, self).get_context_data(**kwargs)
        args = (self.kwargs['volume_id'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        context['link_url'] = kwargs['form'].initial['link_url']
        return context

    @memoized.memoized_method
    def get_data(self):
        try:
            # from openstack_dashboard import policy
            # allowed = policy.check((("volume","volume:create"),),
            # self.request)
            volume_id = self.kwargs['volume_id']
            volume = cinder.volume_get(self.request, volume_id)

            LOG.info(("deep link - get keystone token for vol = %s") %
                     volume.name)

            # get volume data to build URI to SSMC
            endpoint = self.get_SSMC_endpoint(volume, getCGroup=True)
            LOG.info(("deep-link - Session Token = %s") %
                     self.ssmc_api.get_session_key())

            if endpoint:
                ref = urlparse(self.ssmc_api.get_volume_ref())

                # show vvset for cgroup
                url = "0;url=" + endpoint + \
                      '#/vv-sets/show/overview/r' + \
                      ref.path + '?sessionToken=' + \
                      self.ssmc_api.get_session_key()

                # USE if we want user to log in every time
                # self.logout_SSMC_session()
                LOG.info(("deep-link - SSMC URL = %s") % url)
                return volume, url

        except ValueError as err:
            url = reverse('horizon:admin:volumes:volumes_tab')
            exceptions.handle(self.request,
                              err.message,
                              redirect=url)
        except Exception as err:
            LOG.info(("deep-link error = %s") % err.message)
            exceptions.handle(self.request,
                              _('Unable to retrieve volume details.'),
                              redirect=self.success_url)

    def get_initial(self):
        volume, link_url = self.get_data()
        return {'volume_id': self.kwargs["volume_id"],
                'name': volume.name,
                'link_url': link_url}

class LinkSnapshotView(BaseLinkView):
    submit_url = 'horizon:admin:hpe_storage:config:link_to_snapshot'

    def get_context_data(self, **kwargs):
        context = super(LinkSnapshotView, self).get_context_data(**kwargs)
        args = (self.kwargs['snapshot_id'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        context['link_url'] = kwargs['form'].initial['link_url']
        return context

    @memoized.memoized_method
    def get_data(self):
        try:
            # from openstack_dashboard import policy
            # allowed = policy.check((("volume","volume:create"),),
            # self.request)
            snapshot_id = self.kwargs['snapshot_id']
            snapshot = cinder.volume_snapshot_get(self.request, snapshot_id)

            volume_id = snapshot.volume_id
            volume = cinder.volume_get(self.request, volume_id)

            LOG.info(("deep link - get keystone token for snapshot = %s") %
                     snapshot.name)

            # get volume data to build URI to SSMC
            endpoint = self.get_SSMC_endpoint(volume, snapshot)
            LOG.info(("deep-link - Session Token = %s") %
                     self.ssmc_api.get_session_key())

            if endpoint:
                ref = urlparse(self.ssmc_api.get_volume_ref())

                if volume.consistencygroup_id:
                    # show vvset for cgroup and let user navigate to snapshot
                    url = "0;url=" + endpoint + \
                          '#/vv-sets/show/overview/r' + \
                          ref.path + '?sessionToken=' + \
                          self.ssmc_api.get_session_key()
                else:
                    # show snapshot view
                    url = "0;url=" + endpoint + \
                          '#/virtual-volumes/show/capacity/r' + \
                          ref.path + '?sessionToken=' + \
                          self.ssmc_api.get_session_key()

                # USE if we want user to log in every time
                # self.logout_SSMC_session()
                LOG.info(("deep-link - SSMC URL = %s") % url)
                return snapshot, url

        except ValueError as err:
            url = reverse('horizon:admin:volumes:volumes_tab')
            exceptions.handle(self.request,
                              err.message,
                              redirect=url)
        except Exception as err:
            LOG.info(("deep-link error = %s") % err.message)
            exceptions.handle(self.request,
                              _('Unable to retrieve volume details.'),
                              redirect=self.success_url)

    def get_initial(self):
        snapshot, link_url = self.get_data()
        return {'snapshot_id': self.kwargs["snapshot_id"],
                'name': snapshot.name,
                'link_url': link_url}

class ValidateCinderView(forms.ModalFormView):
    form_class = config_forms.ValidateCinderNode
    modal_header = _("Validate SSH Credentials")
    modal_id = "validate_cinder_modal"
    template_name = 'config/validate_node.html'
    submit_label = _("Validate SSH Credentials")
    submit_url = "horizon:admin:hpe_storage:config:validate_cinder_node"
    success_url = reverse_lazy('horizon:admin:hpe_storage:index')
    page_title = _("Validate SSH Credentials")

    def get_context_data(self, **kwargs):
        context = super(ValidateCinderView, self).get_context_data(**kwargs)
        context["node_name"] = self.kwargs['node_name']
        args = (self.kwargs['node_name'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        return context

    def get_initial(self):
        node_name = self.kwargs['node_name']
        return {'node_name': node_name}

class ValidateAllCinderView(forms.ModalFormView):
    form_class = config_forms.ValidateAllCinderNodes
    modal_header = _("Validate SSH Credentials on All Cinder Nodes")
    modal_id = "validate_all_cinder_modal"
    template_name = 'config/validate_all_nodes.html'
    submit_label = _("Validate SSH Credentials")
    submit_url = reverse_lazy(
        "horizon:admin:hpe_storage:config:validate_all_cinder_nodes")
    success_url = 'horizon:admin:hpe_storage:index'
    page_title = _("Validate SSH Credentials")

    def get_success_url(self):
        return reverse(self.success_url)

class RegisterCinderView(forms.ModalFormView):
    form_class = config_forms.RegisterCinderNode
    modal_header = _("Register Cinder Node")
    modal_id = "register_cinder_modal"
    template_name = 'config/register_cinder.html'
    submit_label = _("Register Cinder Node")
    submit_url = reverse_lazy(
        "horizon:admin:hpe_storage:config:register_cinder_node")
    success_url = 'horizon:admin:hpe_storage:index'
    page_title = _("Register Cinder Node")

    def get_success_url(self):
        return reverse(self.success_url)

class EditCinderView(forms.ModalFormView):
    form_class = config_forms.EditCinderNode
    modal_header = _("Edit Cinder Node")
    modal_id = "edit_cinder_modal"
    template_name = 'config/edit_cinder.html'
    submit_label = _("Edit Cinder Node")
    submit_url = "horizon:admin:hpe_storage:config:edit_cinder_node"
    success_url = reverse_lazy('horizon:admin:hpe_storage:index')
    page_title = _("Edit Cinder Node")

    def get_context_data(self, **kwargs):
        context = super(EditCinderView, self).get_context_data(**kwargs)
        args = (self.kwargs['node_name'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        return context

    def get_initial(self):
        node_name = self.kwargs['node_name']
        return {'node_name': node_name}

class ValidateNovaView(forms.ModalFormView):
    form_class = config_forms.ValidateNovaNode
    modal_header = _("Validate SSH Credentials")
    modal_id = "validate_nova_modal"
    template_name = 'config/validate_node.html'
    submit_label = _("Validate SSH Credentials")
    submit_url = "horizon:admin:hpe_storage:config:validate_nova_node"
    success_url = reverse_lazy('horizon:admin:hpe_storage:index')
    page_title = _("Validate SSH Credentials")

    def get_context_data(self, **kwargs):
        context = super(ValidateNovaView, self).get_context_data(**kwargs)
        context["node_name"] = self.kwargs['node_name']
        args = (self.kwargs['node_name'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        return context

    def get_initial(self):
        node_name = self.kwargs['node_name']
        return {'node_name': node_name}

class ValidateAllNovaView(forms.ModalFormView):
    form_class = config_forms.ValidateAllNovaNodes
    modal_header = _("Validate SSH Credentials on All Nova Nodes")
    modal_id = "validate_all_nova_modal"
    template_name = 'config/validate_all_nodes.html'
    submit_label = _("Validate SSH Credentials")
    submit_url = reverse_lazy(
        "horizon:admin:hpe_storage:config:validate_all_nova_nodes")
    success_url = 'horizon:admin:hpe_storage:index'
    page_title = _("Validate SSH Credentials")

    def get_success_url(self):
        return reverse(self.success_url)

class RegisterNovaView(forms.ModalFormView):
    form_class = config_forms.RegisterNovaNode
    modal_header = _("Register Nova Node")
    modal_id = "create_nova_modal"
    template_name = 'config/register_nova.html'
    submit_label = _("Register Nova Node")
    submit_url = reverse_lazy(
        "horizon:admin:hpe_storage:config:register_nova_node")
    success_url = 'horizon:admin:hpe_storage:index'
    page_title = _("Register Nova Node")

    def get_success_url(self):
        return reverse(self.success_url)

class EditNovaView(forms.ModalFormView):
    form_class = config_forms.EditNovaNode
    modal_header = _("Edit Nova Node")
    modal_id = "edit_nova_modal"
    template_name = 'config/edit_nova.html'
    submit_label = _("Edit Nova Node")
    submit_url = "horizon:admin:hpe_storage:config:edit_nova_node"
    success_url = reverse_lazy('horizon:admin:hpe_storage:index')
    page_title = _("Edit Nova Node")

    def get_context_data(self, **kwargs):
        context = super(EditNovaView, self).get_context_data(**kwargs)
        args = (self.kwargs['node_name'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        return context

    def get_initial(self):
        node_name = self.kwargs['node_name']
        return {'node_name': node_name}

class ManageOSVarsView(forms.ModalFormView):
    form_class = config_forms.ManageOSVars
    modal_header = _("Manage OpenStack Environment Variables")
    modal_id = "manage_os_vars_modal"
    template_name = 'config/manage_os_vars.html'
    submit_label = _("Submit")
    submit_url = "horizon:admin:hpe_storage:config:manage_os_vars"
    success_url = reverse_lazy('horizon:admin:hpe_storage:index')

    def get_context_data(self, **kwargs):
        context = super(ManageOSVarsView, self).get_context_data(**kwargs)
        args = (self.kwargs['node_name'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        return context

    def get_initial(self):
        node_name = self.kwargs['node_name']
        return {'node_name': node_name}


text:
<!DOCTYPE html>
<html>
  <head>
    <title>Simple example</title>
  </head>
  <body>
    <canvas id="sheet" style="background-color:#cdcdcd;"></canvas>
    <script type='text/javascript'>
"use strict";
var context = document.getElementById('sheet').getContext("2d");
var canvas = document.getElementById('sheet');
context = canvas.getContext("2d");
context.strokeStyle = "#ff0000";
context.lineJoin = "round";
context.lineWidth = 1;

var clickX = [];
var clickY = [];
var clickDrag = [];
var paint;

/**
 * Add information where the user clicked at.
 * @param {number} x
 * @param {number} y
 * @return {boolean} dragging
 */
function addClick(x, y, dragging) {
    clickX.push(x);
    clickY.push(y);
    clickDrag.push(dragging);
}

/**
 * Redraw the complete canvas.
 */
function redraw() {
    // Clears the canvas
    context.clearRect(0, 0, context.canvas.width, context.canvas.height);

    for (var i = 0; i < clickX.length; i += 1) {
        if (!clickDrag[i] && i == 0) {
            context.beginPath();
            context.moveTo(clickX[i], clickY[i]);
            context.stroke();
        } else if (!clickDrag[i] && i > 0) {
            context.closePath();

            context.beginPath();
            context.moveTo(clickX[i], clickY[i]);
            context.stroke();
        } else {
            context.lineTo(clickX[i], clickY[i]);
            context.stroke();
        }
    }
}

/**
 * Draw the newly added point.
 * @return {void}
 */
function drawNew() {
    var i = clickX.length - 1
    if (!clickDrag[i]) {
        if (clickX.length == 0) {
            context.beginPath();
            context.moveTo(clickX[i], clickY[i]);
            context.stroke();
        } else {
            context.closePath();

            context.beginPath();
            context.moveTo(clickX[i], clickY[i]);
            context.stroke();
        }
    } else {
        context.lineTo(clickX[i], clickY[i]);
        context.stroke();
    }
}

function mouseDownEventHandler(e) {
    paint = true;
    var x = e.pageX - canvas.offsetLeft;
    var y = e.pageY - canvas.offsetTop;
    if (paint) {
        addClick(x, y, false);
        drawNew();
    }
}

function touchstartEventHandler(e) {
    paint = true;
    if (paint) {
        addClick(e.touches[0].pageX - canvas.offsetLeft, e.touches[0].pageY - canvas.offsetTop, false);
        drawNew();
    }
}

function mouseUpEventHandler(e) {
    context.closePath();
    paint = false;
}

function mouseMoveEventHandler(e) {
    var x = e.pageX - canvas.offsetLeft;
    var y = e.pageY - canvas.offsetTop;
    if (paint) {
        addClick(x, y, true);
        drawNew();
    }
}

function touchMoveEventHandler(e) {
    if (paint) {
        addClick(e.touches[0].pageX - canvas.offsetLeft, e.touches[0].pageY - canvas.offsetTop, true);
        drawNew();
    }
}

function setUpHandler(isMouseandNotTouch, detectEvent) {
    removeRaceHandlers();
    if (isMouseandNotTouch) {
        canvas.addEventListener('mouseup', mouseUpEventHandler);
        canvas.addEventListener('mousemove', mouseMoveEventHandler);
        canvas.addEventListener('mousedown', mouseDownEventHandler);
        mouseDownEventHandler(detectEvent);
    } else {
        canvas.addEventListener('touchstart', touchstartEventHandler);
        canvas.addEventListener('touchmove', touchMoveEventHandler);
        canvas.addEventListener('touchend', mouseUpEventHandler);
        touchstartEventHandler(detectEvent);
    }
}

function mouseWins(e) {
    setUpHandler(true, e);
}

function touchWins(e) {
    setUpHandler(false, e);
}

function removeRaceHandlers() {
    canvas.removeEventListener('mousedown', mouseWins);
    canvas.removeEventListener('touchstart', touchWins);
}

canvas.addEventListener('mousedown', mouseWins);
canvas.addEventListener('touchstart', touchWins);
    </script>
  </body>
</html>

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ResourceBundle\Routing;

use Gedmo\Sluggable\Util\Urlizer;
use Sylius\Component\Resource\Metadata\MetadataInterface;
use Sylius\Component\Resource\Metadata\RegistryInterface;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Loader\LoaderResolverInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Yaml\Yaml;

final class ResourceLoader implements LoaderInterface
{
    /**
     * @var RegistryInterface
     */
    private $resourceRegistry;

    /**
     * @var RouteFactoryInterface
     */
    private $routeFactory;

    /**
     * @param RegistryInterface $resourceRegistry
     * @param RouteFactoryInterface $routeFactory
     */
    public function __construct(RegistryInterface $resourceRegistry, RouteFactoryInterface $routeFactory)
    {
        $this->resourceRegistry = $resourceRegistry;
        $this->routeFactory = $routeFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function load($resource, $type = null): RouteCollection
    {
        $processor = new Processor();
        $configurationDefinition = new Configuration();

        $configuration = Yaml::parse($resource);
        $configuration = $processor->processConfiguration($configurationDefinition, ['routing' => $configuration]);

        if (!empty($configuration['only']) && !empty($configuration['except'])) {
            throw new \InvalidArgumentException('You can configure only one of "except" & "only" options.');
        }

        $routesToGenerate = ['show', 'index', 'create', 'update', 'delete', 'bulkDelete'];

        if (!empty($configuration['only'])) {
            $routesToGenerate = $configuration['only'];
        }
        if (!empty($configuration['except'])) {
            $routesToGenerate = array_diff($routesToGenerate, $configuration['except']);
        }

        $isApi = $type === 'sylius.resource_api';

        /** @var MetadataInterface $metadata */
        $metadata = $this->resourceRegistry->get($configuration['alias']);
        $routes = $this->routeFactory->createRouteCollection();

        $rootPath = sprintf('/%s/', $configuration['path'] ?? Urlizer::urlize($metadata->getPluralName()));
        $identifier = sprintf('{%s}', $configuration['identifier']);

        if (in_array('index', $routesToGenerate, true)) {
            $indexRoute = $this->createRoute($metadata, $configuration, $rootPath, 'index', ['GET'], $isApi);
            $routes->add($this->getRouteName($metadata, $configuration, 'index'), $indexRoute);
        }

        if (in_array('create', $routesToGenerate, true)) {
            $createRoute = $this->createRoute($metadata, $configuration, $isApi ? $rootPath : $rootPath . 'new', 'create', $isApi ? ['POST'] : ['GET', 'POST'], $isApi);
            $routes->add($this->getRouteName($metadata, $configuration, 'create'), $createRoute);
        }

        if (in_array('update', $routesToGenerate, true)) {
            $updateRoute = $this->createRoute($metadata, $configuration, $isApi ? $rootPath . $identifier : $rootPath . $identifier . '/edit', 'update', $isApi ? ['PUT', 'PATCH'] : ['GET', 'PUT', 'PATCH'], $isApi);
            $routes->add($this->getRouteName($metadata, $configuration, 'update'), $updateRoute);
        }

        if (in_array('show', $routesToGenerate, true)) {
            $showRoute = $this->createRoute($metadata, $configuration, $rootPath . $identifier, 'show', ['GET'], $isApi);
            $routes->add($this->getRouteName($metadata, $configuration, 'show'), $showRoute);
        }

        if (!$isApi && in_array('bulkDelete', $routesToGenerate, true)) {
            $bulkDeleteRoute = $this->createRoute($metadata, $configuration, $rootPath . 'bulk-delete', 'bulkDelete', ['DELETE'], $isApi);
            $routes->add($this->getRouteName($metadata, $configuration, 'bulk_delete'), $bulkDeleteRoute);
        }

        if (in_array('delete', $routesToGenerate, true)) {
            $deleteRoute = $this->createRoute($metadata, $configuration, $rootPath . $identifier, 'delete', ['DELETE'], $isApi);
            $routes->add($this->getRouteName($metadata, $configuration, 'delete'), $deleteRoute);
        }

        return $routes;
    }

    /**
     * {@inheritdoc}
     */
    public function supports($resource, $type = null): bool
    {
        return 'sylius.resource' === $type || 'sylius.resource_api' === $type;
    }

    /**
     * {@inheritdoc}
     */
    public function getResolver(): void
    {
        // Intentionally left blank.
    }

    /**
     * {@inheritdoc}
     */
    public function setResolver(LoaderResolverInterface $resolver): void
    {
        // Intentionally left blank.
    }

    /**
     * @param MetadataInterface $metadata
     * @param array $configuration
     * @param string $path
     * @param string $actionName
     * @param array $methods
     * @param bool $isApi
     *
     * @return Route
     */
    private function createRoute(
        MetadataInterface $metadata,
        array $configuration,
        string $path,
        string $actionName,
        array $methods,
        bool $isApi = false
    ): Route {
        $defaults = [
            '_controller' => $metadata->getServiceId('controller') . sprintf(':%sAction', $actionName),
        ];

        if ($isApi && 'index' === $actionName) {
            $defaults['_sylius']['serialization_groups'] = ['Default'];
        }
        if ($isApi && in_array($actionName, ['show', 'create', 'update'], true)) {
            $defaults['_sylius']['serialization_groups'] = ['Default', 'Detailed'];
        }
        if ($isApi && 'delete' === $actionName) {
            $defaults['_sylius']['csrf_protection'] = false;
        }
        if (isset($configuration['grid']) && 'index' === $actionName) {
            $defaults['_sylius']['grid'] = $configuration['grid'];
        }
        if (isset($configuration['form']) && in_array($actionName, ['create', 'update'], true)) {
            $defaults['_sylius']['form'] = $configuration['form'];
        }
        if (isset($configuration['serialization_version'])) {
            $defaults['_sylius']['serialization_version'] = $configuration['serialization_version'];
        }
        if (isset($configuration['section'])) {
            $defaults['_sylius']['section'] = $configuration['section'];
        }
        if (!empty($configuration['criteria'])) {
            $defaults['_sylius']['criteria'] = $configuration['criteria'];
        }
        if (array_key_exists('filterable', $configuration)) {
            $defaults['_sylius']['filterable'] = $configuration['filterable'];
        }
        if (isset($configuration['templates']) && in_array($actionName, ['show', 'index', 'create', 'update'], true)) {
            $defaults['_sylius']['template'] = sprintf('%s:%s.html.twig', $configuration['templates'], $actionName);
        }
        if (isset($configuration['redirect']) && in_array($actionName, ['create', 'update'], true)) {
            $defaults['_sylius']['redirect'] = $this->getRouteName($metadata, $configuration, $configuration['redirect']);
        }
        if (isset($configuration['permission'])) {
            $defaults['_sylius']['permission'] = $configuration['permission'];
        }
        if (isset($configuration['vars']['all'])) {
            $defaults['_sylius']['vars'] = $configuration['vars']['all'];
        }

        if (isset($configuration['vars'][$actionName])) {
            $vars = $configuration['vars']['all'] ?? [];
            $defaults['_sylius']['vars'] = array_merge($vars, $configuration['vars'][$actionName]);
        }

        if ($actionName === 'bulkDelete') {
            $defaults['_sylius']['paginate'] = false;
            $defaults['_sylius']['repository'] = [
                'method' => 'findById',
                'arguments' => ['$ids'],
            ];
        }

        return $this->routeFactory->createRoute($path, $defaults, [], [], '', [], $methods);
    }

    /**
     * @param MetadataInterface $metadata
     * @param array $configuration
     * @param string $actionName
     *
     * @return string
     */
    private function getRouteName(MetadataInterface $metadata, array $configuration, string $actionName): string
    {
        $sectionPrefix = isset($configuration['section']) ? $configuration['section'] . '_' : '';

        return sprintf('%s_%s%s_%s', $metadata->getApplicationName(), $sectionPrefix, $metadata->getName(), $actionName);
    }
}


text:
package com.carrotsearch.junitbenchmarks;

import java.io.*;
import java.util.Locale;

/**
 * {@link IResultsConsumer} printing benchmark results to a given writer.
 */
public final class WriterConsumer implements IResultsConsumer
{
    private final Writer w;

    public WriterConsumer()
    {
        this(getDefaultWriter());
    }

    public WriterConsumer(Writer w)
    {
        this.w = w;
    }

    public void accept(Result result) throws IOException
    {
        w.write(String.format(Locale.ENGLISH,
            "%s: [measured %d out of %d rounds, %s]\n" +
            " round: %s, round.gc: %s, GC.calls: %d, GC.time: %.2f," +
            " time.total: %.2f, time.warmup: %.2f, time.bench: %.2f\n",
            result.getShortTestClassName() + "." + result.getTestMethodName(),
            result.benchmarkRounds,
            result.benchmarkRounds + result.warmupRounds,
            concurrencyToText(result.options),
            result.roundAverage.toString(),
            result.gcAverage.toString(),
            result.gcInfo.accumulatedInvocations(),
            result.gcInfo.accumulatedTime() / 1000.0,
            (result.warmupTime + result.benchmarkTime) * 0.001,
            result.warmupTime * 0.001,
            result.benchmarkTime * 0.001
        ));
        w.flush();
    }

    private String concurrencyToText(BenchmarkOptions options)
    {
        switch (options.concurrency())
        {
            case BenchmarkOptions.CONCURRENCY_AVAILABLE_CORES:
                return "threads: " + Runtime.getRuntime().availableProcessors() +
                    " (all physical processors)";

            case BenchmarkOptions.CONCURRENCY_SEQUENTIAL:
                return "threads: 1 (sequential)";

            default:
                return "threads: " + options.concurrency()
                    + " (physical processors: " + Runtime.getRuntime().availableProcessors() + ")";
        }
    }

    /**
     * Return the default writer (console).
     */
    private static Writer getDefaultWriter()
    {
        return new OutputStreamWriter(System.out)
        {
            public void close() throws IOException
            {
                // Don't close the superstream.
            }
        };
    }
}


text:
package org.diirt.service.exec;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import org.diirt.service.AbstractFileServiceProvider;
import org.diirt.service.Service;
import org.diirt.util.config.Configuration;

/**
 * A service factory that crawls a directory for xml files, and creates an exec
 * service from each of them.
 *
 * @author carcassi
 */
public class ExecServiceProvider extends AbstractFileServiceProvider {

    private static final Logger log = Logger.getLogger(ExecServiceProvider.class.getName());

    private final boolean includeGenericExecService;

    /**
     * Creates a new factory that reads from the given directory.
     * <p>
     * If the directory does not exist, it simply returns an empty set.
     *
     * @param directory a directory
     * @param includeGenericExecService whether to include the general purpose
     * exec service
     */
    public ExecServiceProvider(File directory, boolean includeGenericExecService) {
        super(directory);
        this.includeGenericExecService = includeGenericExecService;
    }

    /**
     * Creates a new factory using the default configuration directory.
     */
    public ExecServiceProvider() {
        this(new File(Configuration.getDirectory(), "services/exec"), true);
    }

    @Override
    public String getName() {
        return "exec";
    }

    @Override
    public Service createService(File file) throws Exception {
        if (file.getName().endsWith(".xml")) {
            return ExecServices.createFromXml(new FileInputStream(file));
        } else {
            return null;
        }
    }

    @Override
    public Collection<Service> additionalServices() {
        if (includeGenericExecService) {
            return Collections.<Service>singleton(new GenericExecService());
        } else {
            return Collections.emptySet();
        }
    }

}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30744_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">PETROLEUM"—

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">10/22/2014
Michael Kukuk Regulatory Supervisor Oasis Petroleum
1001 Fannin St.
Suite 1500
Houston, TX 77002

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Todd Holweger
Mineral Resources Permit Manager North Dakota Industrial Commission 600 East Boulevard Avenue Dept. 405 Bismarck, ND 58505-0840

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">RE:

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">McCauley 5501 14-4 8TX Request for a legal street address

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dear Mr. Holweger:

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Oasis Petroleum has requested a physical street address for the subject well/well facility. The request was made to Corey B., with the Mountrail County Sherriff's Department, in Mountrail County. Upon
receiving a legal street address, Oasis will submit the address to the NDIC on a Sundry Notice (form 4) pursuant to 43-02-03-28.
Thank you for your consideration.

    <p class="styleSans36.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Respectfully,
fl  /v
Michael Kukuk
Regulatory Supervisor Oasis Petroleum

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1001 Fannin, Suite 1500 0 Houston, Texas 77002 0 Phone (281) 404-9500 - Fax: (281)404-9501

    <p class="styleSans16.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
<?php

declare(strict_types=1);

namespace VonageTest\Voice\Message;

use PHPUnit\Framework\TestCase;
use Vonage\Voice\Message\Message;

class MessageTest extends TestCase
{
    /**
     * @var Message
     */
    protected $message;

    /**
     * @var string
     */
    protected $text = 'TTS Text';

    /**
     * @var string
     */
    protected $to = '15553331212';

    /**
     * @var string
     */
    protected $from = '15554441212';

    public function setUp(): void
    {
        $this->message = new Message($this->text, $this->to, $this->from);
    }

    public function testConstructorParams(): void
    {
        $params = $this->message->getParams();

        $this->assertArrayHasKey('text', $params);
        $this->assertArrayHasKey('to', $params);
        $this->assertArrayHasKey('from', $params);
        $this->assertEquals($this->text, $params['text']);
        $this->assertEquals($this->to, $params['to']);
        $this->assertEquals($this->from, $params['from']);
    }

    public function testFromIsOptional(): void
    {
        $message = new Message($this->text, $this->to);
        $params = $message->getParams();

        $this->assertArrayNotHasKey('from', $params);
    }

    public function testCallback(): void
    {
        $this->message->setCallback('http://example.com');
        $params = $this->message->getParams();

        $this->assertArrayHasKey('callback', $params);
        $this->assertEquals('http://example.com', $params['callback']);
        $this->assertArrayNotHasKey('callback_method', $params);

        $this->message->setCallback('http://example.com', 'POST');
        $params = $this->message->getParams();

        $this->assertArrayHasKey('callback', $params);
        $this->assertEquals('http://example.com', $params['callback']);
        $this->assertArrayHasKey('callback_method', $params);
        $this->assertEquals('POST', $params['callback_method']);

        $this->message->setCallback('http://example.com');
        $params = $this->message->getParams();

        $this->assertArrayHasKey('callback', $params);
        $this->assertEquals('http://example.com', $params['callback']);
        $this->assertArrayNotHasKey('callback_method', $params);
    }

    public function testMachine(): void
    {
        $this->message->setMachineDetection();
        $params = $this->message->getParams();

        $this->assertArrayHasKey('machine_detection', $params);
        $this->assertArrayNotHasKey('machine_timeout', $params);
        $this->assertEquals('hangup', $params['machine_detection']);

        $this->message->setMachineDetection(true, 100);
        $params = $this->message->getParams();

        $this->assertArrayHasKey('machine_detection', $params);
        $this->assertArrayHasKey('machine_timeout', $params);
        $this->assertEquals('hangup', $params['machine_detection']);
        $this->assertEquals(100, $params['machine_timeout']);

        $this->message->setMachineDetection(false);
        $params = $this->message->getParams();

        $this->assertArrayHasKey('machine_detection', $params);
        $this->assertArrayNotHasKey('machine_timeout', $params);
        $this->assertEquals('true', $params['machine_detection']);
    }

    /**
     * @dataProvider optionalParams
     *
     * @param $setter
     * @param $param
     * @param $values
     */
    public function testOptionalParams($setter, $param, $values): void
    {
        //check no default value
        $params = $this->message->getParams();
        $this->assertArrayNotHasKey($param, $params);

        //test values
        foreach ($values as $value => $expected) {
            $this->message->$setter($value);
            $params = $this->message->getParams();

            $this->assertArrayHasKey($param, $params);
            $this->assertEquals($expected, $params[$param]);
        }
    }

    /**
     * @return array[]
     */
    public function optionalParams(): array
    {
        return [
            ['setLanguage', 'lg', ['test' => 'test']],
            ['setVoice', 'voice', ['test' => 'test']],
            ['setRepeat', 'repeat', [2 => 2]],
        ];
    }
}


text:
package be.bagofwords.distributed.computingClient;

import org.springframework.core.io.AbstractResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class LoadedClassResource extends AbstractResource {

    private String name;
    private byte[] data;

    public LoadedClassResource(String name, byte[] data) {
        this.name = name;
        this.data = data;
    }

    @Override
    public String getDescription() {
        return name;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(data);
    }

    @Override
    public boolean exists() {
        return true;
    }

    @Override
    public long contentLength() throws IOException {
        return data.length;
    }

}


text:
[Latexify.jl](https://github.com/korsbo/Latexify.jl) is a package which supplies functions for producing ``\LaTeX``
formatted strings from Julia objects. The package allows for latexification of a many different kinds of Julia object
and it can output several different ``\LaTeX`` or Markdown environments.

A small teaser:

```@example main
using Latexify
copy_to_clipboard(false) # hide
Latexify.set_default(; starred=true)
m = [2//3 "e^(-c*t)" 1+3im; :(x/(x+k_1)) "gamma(n)" :(log10(x))]
latexify(m)
```

## Supported input
This package supplies functionality for latexifying objects of the following types:

- Expressions,
- Strings,
- Numbers (including rational and complex),
- Missing,
- Symbols,
- Symbolic expressions from SymEngine.jl,
- DataFrame from DataFrames.jl,
- Any shape of array containing a mix of any of the above types,
- ParameterizedFunctions from DifferentialEquations.jl,
- ReactionNetworks from DifferentialEquations.jl

Example:

```@example main
str = "x/(2*k_1+x^2)"
latexify(str)
```

## Supported output

Latexify has support for generating a range of different ``\LaTeX`` environments.
The main function of the package, `latexify()`, automatically picks a suitable output environment based on the type(s) of the input.
However, you can override this by passing the keyword argument `env = `. The following environments are available:

| environment | `env= ` | description
| ------ | ---- | --- |
| no env | `:raw` | Latexifies an object and returns a ``\LaTeX`` formatted string. If the input is an array it will be recursed and all its elements latexified. This function does not surround the resulting string in any ``\LaTeX`` environments.
| Inline | `:inline` | latexify the input and surround it with $$ for inline rendering. |
| Align | `:align` | Latexifies input and surrounds it with an align environment. Useful for systems of equations and such fun stuff. |
| Equation | `:equation` or `:eq` | Latexifies input and surrounds it with an equation environment. |
| Array | `:array` | Latexify the elements of an Array or a Dict and output them in a ``\LaTeX`` array. |
| Tabular | `:table` or `:tabular` | Latexify the elements of an array and output a tabular environment. Note that tabular is not supported by MathJax and will therefore not be rendered in Jupyter, etc.|
| Markdown Table | `:mdtable` | Output a Markdown table. This will be rendered nicely by Jupyter, etc. |
| Markdown Text | `:mdtext` | Output and render any string which can be parsed into Markdown. This is really nothing but a call to `Base.Markdown.parse()`,  but it does the trick. Useful for rendering bullet lists and such things. |
| Chemical arrow notation | `:chem`, `:chemical`, `:arrow` or `:arrows` | Latexify an AbstractReactionNetwork to ``\LaTeX`` formatted chemical arrow notation using [mhchem](https://ctan.org/pkg/mhchem?lang=en).

## Modifying the output
Some of the different outputs can be modified using keyword arguments. You can for example transpose an array with `transpose=true` or specify a header of a table or mdtable with `header=[]`. For more options, see the [List of possible arguments](@ref).

## Printing vs displaying

`latexify()` returns a LaTeXString. Using `display()` on such a string will try to render it.

```@example main
latexify("x/y") |> display
```
$\frac{x}{y}$

Using `print()` will output text which is formatted for latex.

```@example main
latexify("x/y") |> print
```

## Number formatting

You can control the formatting of numbers by passing any of the following to the `fmt` keyword:

- a [printf-style](https://en.wikipedia.org/wiki/Printf_format_string) formatting string, for example `fmt = "%.2e"`.
- a single argument function, for example `fmt = x -> round(x, sigdigits=2)`.
- a formatter supplied by Latexify.jl, for example `fmt = FancyNumberFormatter(2)` (thanks to @simeonschaub). You can pass any of these formatters an integer argument which specifies how many significant digits you want.
  - `FancyNumberFormatter()` replaces the exponent notation, from `1.2e+3` to `1.2 \cdot 10^3`.
  - `StyledNumberFormatter()` replaces the exponent notation, from `1.2e+3` to `1.2 \mathrm{e} 3`.

Examples:
```@example main
latexify(12345.678; fmt="%.1e")
```
$1.2e+04$

```@example main
latexify([12893.1 1.328e2; "x/y" 7832//2378]; fmt=FancyNumberFormatter(3))
```
```math
\begin{equation}
\left[
\begin{array}{cc}
1.29 \cdot 10^{4} & 133 \\
\frac{x}{y} & \frac{3916}{1189} \\
\end{array}
\right]
\end{equation}
```

```@example main
using Formatting
latexify([12893.1 1.328e2]; fmt=x->format(round(x, sigdigits=2), autoscale=:metric))
```

## Automatic copying to clipboard
The strings that you would see when using print on any of the above functions can be automatically copied to the clipboard if you so specify.
Since I do not wish to mess with your clipboard without you knowing it, this feature must be activated by you.

To do so, run

```julia
copy_to_clipboard(true)
```

To once again disable the feature, pass `false` to the same function.

The copying to the clipboard will now occur at every call to a Latexify.jl function, regardless of how you chose to display the output.

## Automatic displaying of result

You can toggle whether the result should be automatically displayed. Instead of

```julia
latexify("x/y") |> display
## or
display( latexify("x/y") )
```

one can toggle automatic display by:

```julia
auto_display(true)
```

after which all calls to `latexify` will automatically be displayed. This can be rather convenient, but it can also cause a lot of unwanted printouts if you are using `latexify` in any form of loop.
You can turn off this behaviour again by passing `false` to the same function.

## Setting your own defaults
If you get tired of specifying the same keyword argument over and over in a session, you can just reset its default:
```julia
set_default(fmt = "%.2f", convert_unicode = false)
```

Note that this changes Latexify.jl from within and should therefore only be used in your own Julia sessions (do not call this from within your packages).

The calls are additive so that a new call with
```julia
set_default(cdot = false)
```
will not cancel out the changes we just made to `fmt` and `convert_unicode`.

To view your changes, use
```julia
get_default()
```
and to reset your changes, use
```julia
reset_default()
```
## Macros
Three macros are exported.

- `@latexify` simply latexifies the expression that you provide to it, similar to `latexify(:(...))`.
- `@latexrun` both executes and latexifies the given expression.
- `@latexdefine` executes the expression, and latexifies the expression together with the its value

They can for example be useful for latexifying simple mathsy functions like
```julia
julia> lstr = @latexrun f(x; y=2) = x/y
L"$f\left( x; y = 2 \right) = \frac{x}{y}$"

julia> f(1)
0.5
```

```julia
julia> @latexdefine x = 1/2
L"$x = \frac{1}{2} = 0.5

julia> x
0.5
```

The arguments to the macro can be interpolated with `$` to use the actual
value, instead of the representation:
```julia
julia> @latexify x = abs2(-3)
L"$x = \left|-3\right|^{2}$"

julia> @latexify x = $(abs2(-3))
L"$x = 9$"
```

Keyword arguments can be supplied after these macros:
```julia
julia> @latexdefine x env=:equation
L"\begin{equation}
x = 0.5
\end{equation}
"
```

A special keyword `post` can be supplied to `@latexdefine`, which is a
function that will be called on the final right hand sign before
latexification. This is merely formatting and will not affect any assignments.

```julia
julia> @latexdefine x=π  post=round
L"$x = \pi = 3.0$"

julia> @latexdefine x
L"$x = \pi$"
```

## External rendering
While LaTeXStrings already render nicely in many IDEs or in Jupyter, they do not render in the REPL. Therefore, we provide a function `render(str)` which generates a standalone PDF using LuaLaTeX and opens that file in your default PDF viewer.

I have found the following syntax pretty useful:
```julia
latexify(:(x/y)) |> render
```

Alternatively, `render(str, mime)` can also be used to generate and display DVI, PNG and SVG files, which might be useful for other purposes:

```julia
latexify(:(x/y)) |> s -> render(s, MIME("image/png"))
```

PNG output relies on [ghostscript](https://www.ghostscript.com) or alternatively on [dvipng](http://www.nongnu.org/dvipng): if `render` is called with the keyword `convert = :gs`, ghostcript will be used to convert the `pdf` output to `png` format.

SVG output relies on [dvisvgm](https://dvisvgm.de) or alternatively on [pdf2svg](https://github.com/dawbarton/pdf2svg).

If your code requires specific packages or document classes to render correctly, you can supply those as keyword arguments:

```julia
L"\qty{1.25}{nm}" |> render(s, MIME("image/png"); documentclass="article", packages=("microtype", ("siunitx", exponent-product="\cdot")))
```

The arguments to these are either strings, or tuples of strings where the first
one is the name of the package or class, and any further are optional arguments.

One can use `Latexify` together with `ImageInTerminal` to render equations in a [sixel compatible](https://github.com/JuliaIO/Sixel.jl#terminals-that-support-sixel) terminal, where the size of the sixel encoded image can be controlled using `dpi`:

```julia
using ImageInTerminal, Latexify

latexify(:(iħ * (∂Ψ(𝐫, t) / ∂t) = -ħ^2 / 2m * ΔΨ(𝐫, t) + V * Ψ(𝐫, t))) |> s -> render(s, dpi=200)
```

## Legacy support

Latexify.jl has stopped supporting Julia versions older than 0.7. This does not mean that you cannot use Latexify with earlier versions, just that these will not get new features. Latexify.jl's release v0.4.1 was the last which supported Julia 0.6. Choose that release in the dropdown menu if you want to see that documentation.


text:
function dom = domain(N)
%DOMAIN   Domain of function definition.
% DOMAIN(N) returns the domain of the functions on which the chebop N
% operates, (Note that this isn't quite the "domain of N", which would be
% the space in which the functions it could act upon live).

% Copyright 2011 by The University of Oxford and The Chebfun Developers.
% See http://www.maths.ox.ac.uk/chebfun/ for Chebfun information.

dom = N.domain;

end


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/breadcrumbs/breadcrumb_manager_tab_helper.h"

#include "base/format_macros.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "chrome/browser/breadcrumbs/breadcrumb_manager_keyed_service_factory.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "components/breadcrumbs/core/breadcrumb_manager_keyed_service.h"
#include "components/breadcrumbs/core/breadcrumb_manager_tab_helper.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/infobar.h"
#include "components/infobars/core/infobar_delegate.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_web_contents_factory.h"
#include "content/test/test_web_contents.h"
#include "testing/gtest/include/gtest/gtest.h"

using infobars::InfoBarDelegate;

namespace {

class FakeInfoBarDelegate : public infobars::InfoBarDelegate {
 public:
  explicit FakeInfoBarDelegate(
      infobars::InfoBarDelegate::InfoBarIdentifier identifier)
      : identifier_(identifier) {}

  ~FakeInfoBarDelegate() override = default;

  infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override {
    return identifier_;
  }

  bool EqualsDelegate(infobars::InfoBarDelegate* delegate) const override {
    return delegate->GetIdentifier() == GetIdentifier();
  }

  infobars::InfoBarDelegate::InfoBarIdentifier identifier_;
};

std::unique_ptr<infobars::InfoBar> CreateInfoBar(
    infobars::InfoBarDelegate::InfoBarIdentifier identifier) {
  auto infobar_delegate = std::make_unique<FakeInfoBarDelegate>(identifier);
  return std::make_unique<infobars::InfoBar>(std::move(infobar_delegate));
}

}  // namespace

// Test fixture for BreadcrumbManagerTabHelper class.
class BreadcrumbManagerTabHelperTest : public ChromeRenderViewHostTestHarness {
 protected:
  void SetUp() override {
    ChromeRenderViewHostTestHarness::SetUp();
    second_web_contents_ = CreateTestWebContents();
    infobars::ContentInfoBarManager::CreateForWebContents(web_contents());
    infobars::ContentInfoBarManager::CreateForWebContents(
        second_web_contents_.get());
    breadcrumb_service_ =
        BreadcrumbManagerKeyedServiceFactory::GetForBrowserContext(
            browser_context());
    BreadcrumbManagerTabHelper::CreateForWebContents(web_contents());
    BreadcrumbManagerTabHelper::CreateForWebContents(
        second_web_contents_.get());
  }

  void TearDown() override {
    second_web_contents_.reset();
    ChromeRenderViewHostTestHarness::TearDown();
  }

  std::unique_ptr<content::WebContents> second_web_contents_;
  raw_ptr<breadcrumbs::BreadcrumbManagerKeyedService> breadcrumb_service_;
};

// Tests that the identifiers returned for different WebContents are unique.
TEST_F(BreadcrumbManagerTabHelperTest, UniqueIdentifiers) {
  const int first_tab_identifier =
      BreadcrumbManagerTabHelper::FromWebContents(web_contents())
          ->GetUniqueId();
  const int second_tab_identifier =
      BreadcrumbManagerTabHelper::FromWebContents(second_web_contents_.get())
          ->GetUniqueId();

  EXPECT_GT(first_tab_identifier, 0);
  EXPECT_GT(second_tab_identifier, 0);
  EXPECT_NE(first_tab_identifier, second_tab_identifier);
}

// Tests that BreadcrumbManagerTabHelper events are logged to the
// associated BreadcrumbManagerKeyedService.
TEST_F(BreadcrumbManagerTabHelperTest, EventsLogged) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());

  auto simulator = content::NavigationSimulator::CreateBrowserInitiated(
      GURL(), web_contents());
  simulator->Start();

  std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(1ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbDidStartNavigation))
      << events.back();

  simulator->Commit();
  events = breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(3ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbPageLoaded))
      << events.back();
  events.pop_back();
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbDidFinishNavigation))
      << events.back();
}

// Tests that BreadcrumbManagerTabHelper events logged from separate
// WebContents are unique.
TEST_F(BreadcrumbManagerTabHelperTest, UniqueEvents) {
  auto first_simulator = content::NavigationSimulator::CreateBrowserInitiated(
      GURL(), web_contents());
  first_simulator->Start();
  auto second_simulator = content::NavigationSimulator::CreateBrowserInitiated(
      GURL(), web_contents());
  second_simulator->Start();
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(2ul, events.size());
  EXPECT_STRNE(events.front().c_str(), events.back().c_str());
  EXPECT_NE(std::string::npos,
            events.front().find(breadcrumbs::kBreadcrumbDidStartNavigation))
      << events.front();
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbDidStartNavigation))
      << events.back();
}

// Tests metadata for www.google.com navigation.
TEST_F(BreadcrumbManagerTabHelperTest, GoogleNavigationStart) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  auto simulator = content::NavigationSimulator::CreateBrowserInitiated(
      GURL("https://www.google.com"), web_contents());
  simulator->Start();
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(1ul, events.size());
  EXPECT_NE(std::string::npos,
            events.front().find(breadcrumbs::kBreadcrumbGoogleNavigation))
      << events.front();
}

// Tests metadata for https://play.google.com/ navigation.
TEST_F(BreadcrumbManagerTabHelperTest, GooglePlayNavigationStart) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  auto simulator = content::NavigationSimulator::CreateBrowserInitiated(
      GURL("https://play.google.com/"), web_contents());
  simulator->Start();
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(1ul, events.size());
  // #google is useful to indicate SRP. There is no need to know URLs of other
  // visited google properties.
  EXPECT_EQ(std::string::npos,
            events.front().find(breadcrumbs::kBreadcrumbGoogleNavigation))
      << events.front();
}

// TODO(crbug.com/1164014): special handling is needed for new-tab-page tests on
// Android, as it uses a different new-tab URL.
#if !defined(OS_ANDROID)
// Tests metadata for chrome://newtab NTP navigation.
TEST_F(BreadcrumbManagerTabHelperTest, ChromeNewTabNavigationStart) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  auto simulator = content::NavigationSimulator::CreateBrowserInitiated(
      GURL(chrome::kChromeUINewTabURL), web_contents());
  simulator->Start();
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(1ul, events.size());
  EXPECT_NE(std::string::npos,
            events.front().find(base::StringPrintf(
                "%s%" PRIu64, breadcrumbs::kBreadcrumbDidStartNavigation,
                simulator->GetNavigationHandle()->GetNavigationId())))
      << events.front();
  EXPECT_NE(std::string::npos,
            events.front().find(breadcrumbs::kBreadcrumbNtpNavigation))
      << events.front();
}
#endif  // !defined(OS_ANDROID)

// Tests unique ID in DidStartNavigation and DidFinishNavigation.
TEST_F(BreadcrumbManagerTabHelperTest, NavigationUniqueId) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  // DidStartNavigation
  auto simulator = content::NavigationSimulator::CreateBrowserInitiated(
      GURL("https://test"), web_contents());
  simulator->Start();
  std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(1ul, events.size());
  const int64_t navigation_id =
      simulator->GetNavigationHandle()->GetNavigationId();
  EXPECT_NE(std::string::npos,
            events.front().find(base::StringPrintf(
                "%s%" PRIu64, breadcrumbs::kBreadcrumbDidStartNavigation,
                navigation_id)))
      << events.front();
  // DidFinishNavigation
  simulator->Commit();
  events = breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(3ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbPageLoaded))
      << events.back();
  events.pop_back();
  EXPECT_NE(std::string::npos,
            events.back().find(base::StringPrintf(
                "%s%" PRIu64, breadcrumbs::kBreadcrumbDidFinishNavigation,
                navigation_id)))
      << events.back();
}

// Tests renderer initiated metadata in DidStartNavigation.
TEST_F(BreadcrumbManagerTabHelperTest, RendererInitiatedByUser) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  auto simulator = content::NavigationSimulator::CreateRendererInitiated(
      GURL(), web_contents()->GetMainFrame());
  simulator->SetHasUserGesture(true);
  simulator->SetTransition(ui::PAGE_TRANSITION_LINK);
  simulator->Start();
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(1ul, events.size());
  EXPECT_NE(std::string::npos, events.back().find("#link")) << events.back();
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbDidStartNavigation))
      << events.back();
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbRendererInitiatedByUser))
      << events.back();
  EXPECT_EQ(
      std::string::npos,
      events.back().find(breadcrumbs::kBreadcrumbRendererInitiatedByScript))
      << events.back();
}

// Tests renderer initiated metadata in DidStartNavigation.
TEST_F(BreadcrumbManagerTabHelperTest, RendererInitiatedByScript) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  auto simulator = content::NavigationSimulator::CreateRendererInitiated(
      GURL(), web_contents()->GetMainFrame());
  simulator->SetHasUserGesture(false);
  simulator->Start();
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(1ul, events.size());
  EXPECT_NE(std::string::npos, events.back().find("#link")) << events.back();
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbDidStartNavigation))
      << events.back();
  EXPECT_EQ(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbRendererInitiatedByUser))
      << events.back();
  EXPECT_NE(
      std::string::npos,
      events.back().find(breadcrumbs::kBreadcrumbRendererInitiatedByScript))
      << events.back();
}

// Tests browser initiated metadata in DidStartNavigation.
TEST_F(BreadcrumbManagerTabHelperTest, BrowserInitiatedByScript) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  auto simulator = content::NavigationSimulator::CreateBrowserInitiated(
      GURL(), web_contents());
  simulator->SetTransition(ui::PAGE_TRANSITION_TYPED);
  simulator->Start();
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(1ul, events.size());
  EXPECT_NE(std::string::npos, events.back().find("#typed")) << events.back();
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbDidStartNavigation))
      << events.back();
  EXPECT_EQ(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbRendererInitiatedByUser))
      << events.back();
  EXPECT_EQ(
      std::string::npos,
      events.back().find(breadcrumbs::kBreadcrumbRendererInitiatedByScript))
      << events.back();
}

// Tests PDF load.
TEST_F(BreadcrumbManagerTabHelperTest, PdfLoad) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  auto simulator = content::NavigationSimulator::CreateBrowserInitiated(
      GURL(), web_contents());
  simulator->SetContentsMimeType("application/pdf");
  simulator->Commit();
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(3ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbPageLoaded))
      << events.back();
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbPdfLoad))
      << events.back();
}

// Tests page load succeess.
TEST_F(BreadcrumbManagerTabHelperTest, PageLoadSuccess) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  content::NavigationSimulator::NavigateAndCommitFromBrowser(web_contents(),
                                                             GURL());
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(3ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbPageLoaded))
      << events.back();
  EXPECT_EQ(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbPageLoadFailure))
      << events.back();
}

// Tests page load failure.
TEST_F(BreadcrumbManagerTabHelperTest, PageLoadFailure) {
  auto simulator = content::NavigationSimulator::CreateBrowserInitiated(
      GURL(), web_contents());
  simulator->Start();
  ASSERT_EQ(1ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());

  static_cast<content::TestWebContents*>(web_contents())
      ->GetMainFrame()
      ->DidFailLoadWithError(GURL(), net::ERR_ABORTED);
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(2ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbPageLoaded))
      << events.back();
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbPageLoadFailure))
      << events.back();
}

// TODO(crbug.com/1164014): special handling is needed for new-tab-page tests on
// Android, as it uses a different new-tab URL.
// Tests NTP page load.
#if !defined(OS_ANDROID)
TEST_F(BreadcrumbManagerTabHelperTest, NtpPageLoad) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  content::NavigationSimulator::NavigateAndCommitFromBrowser(
      web_contents(), GURL(chrome::kChromeUINewTabURL));
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(3ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbPageLoaded))
      << events.back();
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbNtpNavigation))
      << events.back();
  // NTP navigation can't fail, so there is no success/failure metadata.
  EXPECT_EQ(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbPageLoadFailure))
      << events.back();
}
#endif  // !defined(OS_ANDROID)

// Tests navigation error.
TEST_F(BreadcrumbManagerTabHelperTest, NavigationError) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  content::NavigationSimulator::NavigateAndFailFromBrowser(
      web_contents(), GURL("https://test"), net::ERR_INTERNET_DISCONNECTED);
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(2ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbDidFinishNavigation))
      << events.back();
  EXPECT_NE(std::string::npos, events.back().find(net::ErrorToShortString(
                                   net::ERR_INTERNET_DISCONNECTED)))
      << events.back();
}

// Tests that adding an infobar logs the expected breadcrumb.
TEST_F(BreadcrumbManagerTabHelperTest, AddInfobar) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  const auto identifier = InfoBarDelegate::InfoBarIdentifier::TEST_INFOBAR;
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->AddInfoBar(CreateInfoBar(identifier));
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(1ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(base::StringPrintf(
                "%s%d", breadcrumbs::kBreadcrumbInfobarAdded, identifier)))
      << events.back();
}

// Tests that infobar breadcrumbs specify the infobar type.
TEST_F(BreadcrumbManagerTabHelperTest, InfobarTypes) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  // Add and remove first infobar.
  const auto first_identifier =
      InfoBarDelegate::InfoBarIdentifier::SESSION_CRASHED_INFOBAR_DELEGATE_IOS;
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->AddInfoBar(CreateInfoBar(first_identifier));
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->RemoveAllInfoBars(/*animate=*/false);
  // Add second infobar.
  const auto second_identifier =
      InfoBarDelegate::InfoBarIdentifier::SYNC_ERROR_INFOBAR_DELEGATE_IOS;
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->AddInfoBar(CreateInfoBar(second_identifier));
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(3ul, events.size());
  EXPECT_NE(events.front(), events.back());
  EXPECT_NE(std::string::npos, events.front().find(base::StringPrintf(
                                   "%s%d", breadcrumbs::kBreadcrumbInfobarAdded,
                                   first_identifier)))
      << events.back();
  EXPECT_NE(std::string::npos, events.back().find(base::StringPrintf(
                                   "%s%d", breadcrumbs::kBreadcrumbInfobarAdded,
                                   second_identifier)))
      << events.back();
}

// Tests that removing an infobar without animation logs the expected breadcrumb
// event.
TEST_F(BreadcrumbManagerTabHelperTest, RemoveInfobarNotAnimated) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  const auto identifier = InfoBarDelegate::InfoBarIdentifier::TEST_INFOBAR;
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->AddInfoBar(CreateInfoBar(identifier));
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->RemoveAllInfoBars(/*animate=*/false);
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(2ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(base::StringPrintf(
                "%s%d", breadcrumbs::kBreadcrumbInfobarRemoved, identifier)))
      << events.back();
  EXPECT_NE(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbInfobarNotAnimated))
      << events.back();
}

// Tests that removing an infobar with animation logs the expected breadcrumb
// event.
TEST_F(BreadcrumbManagerTabHelperTest, RemoveInfobarAnimated) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  const auto identifier = InfoBarDelegate::InfoBarIdentifier::TEST_INFOBAR;
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->AddInfoBar(CreateInfoBar(identifier));
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->RemoveAllInfoBars(/*animate=*/true);
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(2ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(base::StringPrintf(
                "%s%d", breadcrumbs::kBreadcrumbInfobarRemoved, identifier)))
      << events.back();
  EXPECT_EQ(std::string::npos,
            events.back().find(breadcrumbs::kBreadcrumbInfobarNotAnimated))
      << events.back();
}

// Tests that replacing an infobar logs the expected breadcrumb event.
TEST_F(BreadcrumbManagerTabHelperTest, ReplaceInfobar) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  const auto identifier = InfoBarDelegate::InfoBarIdentifier::TEST_INFOBAR;
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->AddInfoBar(CreateInfoBar(identifier));
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->AddInfoBar(CreateInfoBar(identifier),
                   /*replace_existing=*/true);
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  ASSERT_EQ(2ul, events.size());
  EXPECT_NE(std::string::npos,
            events.back().find(base::StringPrintf(
                "%s%d", breadcrumbs::kBreadcrumbInfobarReplaced, identifier)))
      << events.back();
}

// Tests that replacing an infobar many times only logs the replaced infobar
// breadcrumb at major increments.
TEST_F(BreadcrumbManagerTabHelperTest, SequentialInfobarReplacements) {
  ASSERT_EQ(0ul,
            breadcrumb_service_->GetEvents(/*event_count_limit=*/0).size());
  const auto identifier = InfoBarDelegate::InfoBarIdentifier::TEST_INFOBAR;
  infobars::ContentInfoBarManager::FromWebContents(web_contents())
      ->AddInfoBar(CreateInfoBar(identifier));
  for (int replacements = 0; replacements < 500; replacements++) {
    infobars::ContentInfoBarManager::FromWebContents(web_contents())
        ->AddInfoBar(CreateInfoBar(identifier),
                     /*replace_existing=*/true);
  }
  const std::list<std::string> events =
      breadcrumb_service_->GetEvents(/*event_count_limit=*/0);
  // Replacing the infobar 500 times should only log breadcrumbs on the 1st,
  // 2nd, 5th, 20th, 100th, 200th replacement.
  ASSERT_EQ(7ul, events.size());
  // The events should contain the number of times the info has been replaced.
  // Validate the last one, which occurs at the 200th replacement.
  const std::string expected_event = base::StringPrintf(
      "%s%d %d", breadcrumbs::kBreadcrumbInfobarReplaced, identifier, 200);
  EXPECT_NE(std::string::npos, events.back().find(expected_event))
      << events.back();
}


text:
title: "securing your Expressjs app"
path: "/drafts/securing-your-expressjs-app/"
date: "2015-09-10T00:00:00.000Z"
draft: true
---

https://github.com/troygoode/node-cors
https://github.com/analog-nico/hpp
https://github.com/ericmdantas/express-content-length-validator
https://github.com/aredo/express-enforces-ssl


text:
package org.takes.facets.hamcrest;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.takes.Response;

/**
 * Response text body matcher.
 *
 *
This "matcher" tests given response body,
 * assuming that it has text content.

 *
The class is immutable and thread-safe.
 *
 * @since 2.0
 */
public final class HmRsTextBody extends AbstractHmTextBody<Response> {

    /**
     * Ctor with equalTo matcher and default charset.
     * @param expected String to test against
     */
    public HmRsTextBody(final String expected) {
        this(Matchers.equalTo(expected));
    }

    /**
     * Ctor with charset set to default one.
     * @param bdm Text body matcher
     */
    public HmRsTextBody(final Matcher<String> bdm) {
        this(bdm, Charset.defaultCharset());
    }

    /**
     * Ctor.
     * @param bdm Text body matcher
     * @param charset Text body charset
     */
    public HmRsTextBody(final Matcher<String> bdm, final Charset charset) {
        super(bdm, charset);
    }

    @Override
    public InputStream itemBody(final Response item) throws IOException {
        return item.body();
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__wchar_t_declare_loop_15.c
Label Definition File: CWE124_Buffer_Underwrite.stack.label.xml
Template File: sources-sink-15.tmpl.c
*/
/*
 * @description
 * CWE: 124 Buffer Underwrite
 * BadSource:  Set data pointer to before the allocated memory buffer
 * GoodSource: Set data pointer to the allocated memory buffer
 * Sink: loop
 *    BadSink : Copy string to data using a loop
 * Flow Variant: 15 Control flow: switch(6)
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifndef OMITBAD

void CWE124_Buffer_Underwrite__wchar_t_declare_loop_15_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[100];
    wmemset(dataBuffer, L'A', 100-1);
    dataBuffer[100-1] = L'\0';
    switch(6)
    {
    case 6:
        /* FLAW: Set data pointer to before the allocated memory buffer */
        data = dataBuffer - 8;
        break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    {
        size_t i;
        wchar_t source[100];
        wmemset(source, L'C', 100-1); /* fill with 'C's */
        source[100-1] = L'\0'; /* null terminate */
        /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
        for (i = 0; i < 100; i++)
        {
            data[i] = source[i];
        }
        /* Ensure the destination buffer is null terminated */
        data[100-1] = L'\0';
        printWLine(data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B1() - use goodsource and badsink by changing the switch to switch(5) */
static void goodG2B1()
{
    wchar_t * data;
    wchar_t dataBuffer[100];
    wmemset(dataBuffer, L'A', 100-1);
    dataBuffer[100-1] = L'\0';
    switch(5)
    {
    case 6:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    default:
        /* FIX: Set data pointer to the allocated memory buffer */
        data = dataBuffer;
        break;
    }
    {
        size_t i;
        wchar_t source[100];
        wmemset(source, L'C', 100-1); /* fill with 'C's */
        source[100-1] = L'\0'; /* null terminate */
        /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
        for (i = 0; i < 100; i++)
        {
            data[i] = source[i];
        }
        /* Ensure the destination buffer is null terminated */
        data[100-1] = L'\0';
        printWLine(data);
    }
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the switch */
static void goodG2B2()
{
    wchar_t * data;
    wchar_t dataBuffer[100];
    wmemset(dataBuffer, L'A', 100-1);
    dataBuffer[100-1] = L'\0';
    switch(6)
    {
    case 6:
        /* FIX: Set data pointer to the allocated memory buffer */
        data = dataBuffer;
        break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    {
        size_t i;
        wchar_t source[100];
        wmemset(source, L'C', 100-1); /* fill with 'C's */
        source[100-1] = L'\0'; /* null terminate */
        /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
        for (i = 0; i < 100; i++)
        {
            data[i] = source[i];
        }
        /* Ensure the destination buffer is null terminated */
        data[100-1] = L'\0';
        printWLine(data);
    }
}

void CWE124_Buffer_Underwrite__wchar_t_declare_loop_15_good()
{
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE124_Buffer_Underwrite__wchar_t_declare_loop_15_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE124_Buffer_Underwrite__wchar_t_declare_loop_15_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
<!doctype html>

<meta charset="utf-8">
<title>Threedo – Perfect Perusals</title>
<meta name="description" content="">
<meta name="keywords" content="app academy">

<meta property="og:locale" content="en_US">
<meta property="og:title" content="Threedo – Perfect Perusals">
<meta property="og:description" content="### Three-DoToday was a solo day and it was a great opportunity to go and exercise a broad spectrum of our skills by ...">
<meta property="og:url" content="http://jonathanstyu.github.io/threedo">
<meta property="og:site_name" content="Perfect Perusals">

<link href="http://jonathanstyu.github.io/feed.xml" type="application/atom+xml" rel="alternate" title="Perfect Perusals Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Crimson+Text:400,400italic,700,700italic" rel='stylesheet' type='text/css' />
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700" rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="http://jonathanstyu.github.io/assets/css/entypo/entypo.css" media="all">
<link rel='stylesheet' href='http://jonathanstyu.github.io/assets/css/entypo/animate.min.css' media='all' />

<link rel="stylesheet" href="http://jonathanstyu.github.io/assets/css/i.css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="http://jonathanstyu.github.io/favicon.ico">

        <hgroup>

Perfect Perusals

        </hgroup>
        ☰

              Home

About

Github

Resume

          <hgroup>

Threedo

Jun 21, 2013

App Academy W6D5

          </hgroup>

Three-Do

Today was a solo day and it was a great opportunity to go and exercise a broad spectrum of our skills by creating a todo app - one similar to the one we had created last week and giving it a nice single-page flair with some Javascript and AJAX. By blowing up a lot of the stuff that we did yesterday, we were able to go and create a todo app that would let someone manage all of their information without doing a single refresh. It is pretty awesome.

Three Things I learned Today:

1) Javascript in the browser can get confusing when you have a lot of AJAX callback functions flying around

2) You can go wild with Bootstrap and it is amazing

3) The pages that are sent to you at the beginning can get pretty amazingly complex. I managed to stuff a whole lot of data into those web pages and it felt honestly pretty stuffed. I look forward to being able to start on Backbone now.

You can find the github repo here: https://github.com/jonathanstyu/week6d5-threedo

      Share

Recent Posts

              A Strong Woman
              Sep 18, 2013

              Three Things About People
              Sep 11, 2013

              Some Thoughtful 'Quotes'
              Sep 04, 2013

Contact Me

    © 2013 Jonathan Yu. Powered by Jekyll using the Balzac theme.


text:
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.TException;

public class HelloClient {

    public static void main(String[] args) {
        TSocket trans = new TSocket("localhost", 9090);
        TBinaryProtocol proto = new TBinaryProtocol(trans);
        helloSvc.Client client = new helloSvc.Client(proto);

        try {
            trans.open();
            String str = client.getMessage("world");
            System.out.println("[Client] received: " + str);
        } catch (TException ex) {
            System.out.println("Error: " + ex.toString());
        }
        trans.close();
    }
}


text:
import cPickle
import cv2

loadfile = open('D:/Master Thesis/Dataset/landmarks_old.pkl', 'rb')

landmarks = cPickle.load(loadfile)

for person, videos in landmarks.iteritems():
    for video, data in sorted(videos.iteritems()):
        next_frame = 0
        continuous = 0
        num_frames = data['num_frames']
        del data['num_frames']
        cap = cv2.VideoCapture('D:/Master Thesis/Dataset/{}'.format(video))
        data['meta'] = {
            'num_frames': num_frames,
            'fps': cap.get(cv2.CAP_PROP_FPS),
            'width': cap.get(cv2.CAP_PROP_FRAME_WIDTH),
            'height': cap.get(cv2.CAP_PROP_FRAME_HEIGHT)}
        print(data['meta'])
        if not cap.isOpened():
            print('error opening D:/Master Thesis/Dataset/{}'.format(video))
        print 'num_frames:{}'.format(num_frames)

dumpfile = open('D:/Master Thesis/Dataset/landmarks.pkl', 'wb')

cPickle.dump(landmarks, dumpfile, -1)


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Defin. Austral. pl. 20. 1855 Jun 28-Jul 12 (Trans. Philos. Soc. Victoria 1:97. 1855 Sep 6-Sep 13; Hooker's J. Bot. Kew Gard. Misc. 8:2. 1856)

#### Original name
null

### Remarks
null


text:
layout: doc
title:  "Injections"
permalink: /docs/injections/
---

Oops! Looks like this section hasn't been completed yet.  If you'd like to contribute to the documentation, please open a pull request at the [github repository](https://github.com/njenan/turbulence/pulls).