text:
"""Integration tests for the GUIs."""

#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------

from itertools import cycle, islice
import logging
import os
from pathlib import Path
import shutil
import tempfile
import unittest

import numpy as np
from pytestqt.plugin import QtBot

from phylib.io.mock import (
    artificial_features, artificial_traces, artificial_spike_clusters, artificial_spike_samples,
    artificial_waveforms
)

from phylib.utils import connect, unconnect, Bunch, reset, emit

from phy.cluster.views import (
    WaveformView, FeatureView, AmplitudeView, TraceView, TemplateView,
)
from phy.gui.qt import Debouncer, create_app
from phy.gui.widgets import Barrier
from phy.plot.tests import mouse_click
from ..base import BaseController, WaveformMixin, FeatureMixin, TraceMixin, TemplateMixin

logger = logging.getLogger(__name__)

#------------------------------------------------------------------------------
# Mock models and controller classes
#------------------------------------------------------------------------------

class MyModel(object):
    seed = np.random.seed(0)
    n_channels = 8
    n_spikes = 20000
    n_clusters = 32
    n_templates = n_clusters
    n_pcs = 5
    n_samples_waveforms = 100
    channel_positions = np.random.normal(size=(n_channels, 2))
    channel_mapping = np.arange(0, n_channels)
    channel_shanks = np.zeros(n_channels, dtype=np.int32)
    features = artificial_features(n_spikes, n_channels, n_pcs)
    metadata = {'group': {3: 'noise', 4: 'mua', 5: 'good'}}
    sample_rate = 10000
    spike_attributes = {}
    amplitudes = np.random.normal(size=n_spikes, loc=1, scale=.1)
    spike_clusters = artificial_spike_clusters(n_spikes, n_clusters)
    spike_templates = spike_clusters
    spike_samples = artificial_spike_samples(n_spikes)
    spike_times = spike_samples / sample_rate
    spike_times_reordered = artificial_spike_samples(n_spikes) / sample_rate
    duration = spike_times[-1]
    spike_waveforms = None
    traces = artificial_traces(int(sample_rate * duration), n_channels)

    def _get_some_channels(self, offset, size):
        return list(islice(cycle(range(self.n_channels)), offset, offset + size))

    def get_features(self, spike_ids, channel_ids):
        return artificial_features(len(spike_ids), len(channel_ids), self.n_pcs)

    def get_waveforms(self, spike_ids, channel_ids):
        n_channels = len(channel_ids) if channel_ids else self.n_channels
        return artificial_waveforms(len(spike_ids), self.n_samples_waveforms, n_channels)

    def get_template(self, template_id):
        nc = self.n_channels // 2
        return Bunch(
            template=artificial_waveforms(1, self.n_samples_waveforms, nc)[0, ...],
            channel_ids=self._get_some_channels(template_id, nc))

    def save_spike_clusters(self, spike_clusters):
        pass

    def save_metadata(self, name, values):
        pass

class MyController(BaseController):
    """Default controller."""

    def get_best_channels(self, cluster_id):
        return self.model._get_some_channels(cluster_id, 5)

    def get_channel_amplitudes(self, cluster_id):
        return self.model._get_some_channels(cluster_id, 5), np.ones(5)

class MyControllerW(WaveformMixin, MyController):
    """With waveform view."""
    pass

class MyControllerF(FeatureMixin, MyController):
    """With feature view."""
    pass

class MyControllerT(TraceMixin, MyController):
    """With trace view."""
    pass

class MyControllerTmp(TemplateMixin, MyController):
    """With templates."""
    pass

class MyControllerFull(TemplateMixin, WaveformMixin, FeatureMixin, TraceMixin, MyController):
    """With everything."""
    pass

def _mock_controller(tempdir, cls):
    model = MyModel()
    return cls(
        dir_path=tempdir, config_dir=tempdir / 'config', model=model,
        clear_cache=True, enable_threading=False)

#------------------------------------------------------------------------------
# Base classes
#------------------------------------------------------------------------------

class MinimalControllerTests(object):

    # Methods to override
    #--------------------------------------------------------------------------

    @classmethod
    def get_controller(cls, tempdir):
        raise NotImplementedError()

    # Convenient properties
    #--------------------------------------------------------------------------

    @property
    def qtbot(self):
        return self.__class__._qtbot

    @property
    def controller(self):
        return self.__class__._controller

    @property
    def model(self):
        return self.__class__._controller.model

    @property
    def supervisor(self):
        return self.controller.supervisor

    @property
    def cluster_view(self):
        return self.supervisor.cluster_view

    @property
    def similarity_view(self):
        return self.supervisor.similarity_view

    @property
    def cluster_ids(self):
        return self.supervisor.clustering.cluster_ids

    @property
    def gui(self):
        return self.__class__._gui

    @property
    def selected(self):
        return self.supervisor.selected

    @property
    def amplitude_view(self):
        return self.gui.list_views(AmplitudeView)[0]

    # Convenience methods
    #--------------------------------------------------------------------------

    def stop(self):  # pragma: no cover
        """Used for debugging."""
        create_app().exec_()
        self.gui.close()

    def next(self):
        s = self.supervisor
        s.select_actions.next()
        s.block()

    def next_best(self):
        s = self.supervisor
        s.select_actions.next_best()
        s.block()

    def label(self, name, value):
        s = self.supervisor
        s.actions.label(name, value)
        s.block()

    def merge(self):
        s = self.supervisor
        s.actions.merge()
        s.block()

    def split(self):
        s = self.supervisor
        s.actions.split()
        s.block()

    def undo(self):
        s = self.supervisor
        s.actions.undo()
        s.block()

    def redo(self):
        s = self.supervisor
        s.actions.redo()
        s.block()

    def move(self, w):
        s = self.supervisor
        getattr(s.actions, 'move_%s' % w)()
        s.block()

    def lasso(self, view, scale=1.):
        w, h = view.canvas.get_size()
        w *= scale
        h *= scale
        mouse_click(self.qtbot, view.canvas, (1, 1), modifiers=('Control',))
        mouse_click(self.qtbot, view.canvas, (w - 1, 1), modifiers=('Control',))
        mouse_click(self.qtbot, view.canvas, (w - 1, h - 1), modifiers=('Control',))
        mouse_click(self.qtbot, view.canvas, (1, h - 1), modifiers=('Control',))

    # Fixtures
    #--------------------------------------------------------------------------

    @classmethod
    def setUpClass(cls):
        Debouncer.delay = 1
        cls._qtbot = QtBot(create_app())
        cls._tempdir_ = tempfile.mkdtemp()
        cls._tempdir = Path(cls._tempdir_)
        cls._controller = cls.get_controller(cls._tempdir)
        cls._create_gui()

    @classmethod
    def tearDownClass(cls):
        if os.environ.get('PHY_TEST_STOP', None):  # pragma: no cover
            cls._qtbot.stop()
        cls._close_gui()
        shutil.rmtree(cls._tempdir_)

    @classmethod
    def _create_gui(cls):
        cls._gui = cls._controller.create_gui(do_prompt_save=False)
        s = cls._controller.supervisor
        b = Barrier()
        connect(b('cluster_view'), event='ready', sender=s.cluster_view)
        connect(b('similarity_view'), event='ready', sender=s.similarity_view)
        cls._gui.show()
        # cls._qtbot.addWidget(cls._gui)
        cls._qtbot.waitForWindowShown(cls._gui)
        b.wait()

    @classmethod
    def _close_gui(cls):
        cls._gui.close()
        cls._gui.deleteLater()

        # NOTE: make sure all callback functions are unconnected at the end of the tests
        # to avoid side-effects and spurious dependencies between tests.
        reset()

class BaseControllerTests(MinimalControllerTests):

    # Common test methods
    #--------------------------------------------------------------------------

    def test_common_01(self):
        """Select one cluster."""
        self.next_best()
        self.assertEqual(len(self.selected), 1)

    def test_common_02(self):
        """Select one similar cluster."""
        self.next()
        self.assertEqual(len(self.selected), 2)

    def test_common_03(self):
        """Select another similar cluster."""
        self.next()
        self.assertEqual(len(self.selected), 2)

    def test_common_04(self):
        """Merge the selected clusters."""
        self.merge()
        self.assertEqual(len(self.selected), 1)

    def test_common_05(self):
        """Select a similar cluster."""
        self.next()
        self.assertEqual(len(self.selected), 2)

    def test_common_06(self):
        """Undo/redo the merge several times."""
        for _ in range(3):
            self.undo()
            self.assertEqual(len(self.selected), 2)

            self.redo()
            self.assertEqual(len(self.selected), 2)

    def test_common_07(self):
        """Move action."""
        self.move('similar_to_noise')
        self.assertEqual(len(self.selected), 2)

    def test_common_08(self):
        """Move action."""
        self.move('best_to_good')
        self.assertEqual(len(self.selected), 1)

    def test_common_09(self):
        """Label action."""
        self.next()

        @connect(sender=self.supervisor)
        def on_cluster(sender, up):
            cls = self.__class__
            cls._label_name, cls._label_value = 'new_label', up.metadata_value

        self.label('new_label', 3)

        unconnect(on_cluster)

    def test_common_10(self):
        self.supervisor.save()

    def test_common_11(self):
        s = self.controller.selection
        self.assertEqual(s.cluster_ids, self.selected)
        self.gui.view_actions.toggle_spike_reorder(True)
        self.gui.view_actions.switch_raw_data_filter()

class GlobalViewsTests(object):
    def test_global_filter_1(self):
        self.next()
        cv = self.supervisor.cluster_view
        emit('table_filter', cv, self.cluster_ids[::2])

    def test_global_sort_1(self):
        cv = self.supervisor.cluster_view
        emit('table_sort', cv, self.cluster_ids[::-1])

#------------------------------------------------------------------------------
# Mock test cases
#------------------------------------------------------------------------------

class MockControllerTests(MinimalControllerTests, GlobalViewsTests, unittest.TestCase):
    """Empty mock controller."""

    @classmethod
    def get_controller(cls, tempdir):
        return _mock_controller(tempdir, MyController)

    def test_create_ipython_view(self):
        self.gui.create_and_add_view('IPythonView')

    def test_create_raster_view(self):
        view = self.gui.create_and_add_view('RasterView')
        mouse_click(self.qtbot, view.canvas, (10, 10), modifiers=('Control',))
        view.actions.next_color_scheme()

class MockControllerWTests(MinimalControllerTests, unittest.TestCase):
    """Mock controller with waveforms."""

    @classmethod
    def get_controller(cls, tempdir):
        return _mock_controller(tempdir, MyControllerW)

    @property
    def waveform_view(self):
        return self.gui.list_views(WaveformView)[0]

    def test_waveform_view(self):
        self.waveform_view.actions.toggle_mean_waveforms(True)
        self.waveform_view.actions.next_waveforms_type()
        self.waveform_view.actions.change_n_spikes_waveforms(200)

    def test_mean_amplitudes(self):
        self.next()
        self.assertTrue(self.controller.get_mean_spike_raw_amplitudes(self.selected[0]) >= 0)

    def test_waveform_select_channel(self):
        self.amplitude_view.amplitudes_type = 'raw'

        fv = self.waveform_view
        # Select channel in waveform view.
        w, h = fv.canvas.get_size()
        w, h = w / 2, h / 2
        x, y = w / 2, h / 2
        mouse_click(self.qtbot, fv.canvas, (x, y), button='Left', modifiers=('Control',))

class MockControllerFTests(MinimalControllerTests, unittest.TestCase):
    """Mock controller with features."""

    @classmethod
    def get_controller(cls, tempdir):
        return _mock_controller(tempdir, MyControllerF)

    @property
    def feature_view(self):
        return self.gui.list_views(FeatureView)[0]

    def test_feature_view_split(self):
        self.next()
        n = max(self.cluster_ids)
        self.lasso(self.feature_view, .1)
        self.split()
        # Split one cluster => Two new clusters should be selected after the split.
        self.assertEqual(self.selected[:2], [n + 1, n + 2])

    def test_feature_view_toggle_spike_reorder(self):
        self.gui.view_actions.toggle_spike_reorder(True)

    def test_select_feature(self):
        self.next()

        fv = self.feature_view
        # Select feature in feature view.
        w, h = fv.canvas.get_size()
        w, h = w / 4, h / 4
        x, y = w / 2, h / 2
        mouse_click(self.qtbot, fv.canvas, (x, y), button='Right', modifiers=('Alt',))

class MockControllerTTests(GlobalViewsTests, MinimalControllerTests, unittest.TestCase):
    """Mock controller with traces."""

    @classmethod
    def get_controller(cls, tempdir):
        return _mock_controller(tempdir, MyControllerT)

    @property
    def trace_view(self):
        return self.gui.list_views(TraceView)[0]

    def test_trace_view(self):
        self.trace_view.actions.go_to_next_spike()
        self.trace_view.actions.go_to_previous_spike()
        self.trace_view.actions.toggle_highlighted_spikes(True)
        mouse_click(self.qtbot, self.trace_view.canvas, (100, 100), modifiers=('Control',))
        mouse_click(self.qtbot, self.trace_view.canvas, (150, 100), modifiers=('Shift',))
        emit('select_time', self, 0)
        self.trace_view.actions.next_color_scheme()

class MockControllerTmpTests(MinimalControllerTests, unittest.TestCase):
    """Mock controller with templates."""

    @classmethod
    def get_controller(cls, tempdir):
        return _mock_controller(tempdir, MyControllerTmp)

    @property
    def template_view(self):
        return self.gui.list_views(TemplateView)[0]

    def test_template_view_select(self):
        mouse_click(self.qtbot, self.template_view.canvas, (100, 100), modifiers=('Control',))
        mouse_click(self.qtbot, self.template_view.canvas, (150, 100), modifiers=('Shift',))

    def test_mean_amplitudes(self):
        self.next()
        self.assertTrue(self.controller.get_mean_spike_template_amplitudes(self.selected[0]) >= 0)

    def test_split_template_amplitude(self):
        self.next()
        self.amplitude_view.amplitudes_type = 'template'
        self.controller.get_amplitudes(self.selected[0], load_all=True)
        self.amplitude_view.plot()
        self.lasso(self.amplitude_view)
        self.split()

class MockControllerFullTests(MinimalControllerTests, unittest.TestCase):
    """Mock controller with all views."""
    @classmethod
    def get_controller(cls, tempdir):
        return _mock_controller(tempdir, MyControllerFull)

    def test_filter(self):
        rdf = self.controller.raw_data_filter

        @rdf.add_filter
        def diff(arr, axis=0):  # pragma: no cover
            out = np.zeros_like(arr)
            if axis == 0:
                out[1:, ...] = np.diff(arr, axis=axis)
            elif axis == 1:
                out[:, 1:, ...] = np.diff(arr, axis=axis)
            return out

        self.gui.view_actions.switch_raw_data_filter()
        self.gui.view_actions.switch_raw_data_filter()

        rdf.set('diff')
        assert rdf.current == 'diff'

    def test_y1_close_view(self):
        s = self.selected
        self.next_best()
        assert s != self.selected
        fv = self.gui.get_view(FeatureView)
        wv = self.gui.get_view(WaveformView)
        assert self.selected == wv.cluster_ids
        fv.dock.close()
        s = self.selected
        self.next_best()
        assert s != self.selected
        assert self.selected == wv.cluster_ids

    def test_z1_close_all_views(self):
        self.next()

        for view in self.gui.views:
            view.dock.close()
            self.qtbot.wait(200)

    def test_z2_open_all_views(self):
        for view_cls in self.controller.view_creator.keys():
            self.gui.create_and_add_view(view_cls)
            self.qtbot.wait(200)

    def test_z3_select(self):
        self.next()
        self.next()

    def test_z4_open_new_views(self):
        for view_cls in self.controller.view_creator.keys():
            self.gui.create_and_add_view(view_cls)
            self.qtbot.wait(200)

    def test_z5_select(self):
        self.next_best()
        self.next()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Background Worker Processes</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.6.2 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Server Programming"
HREF="server-programming.html"><LINK
REL="PREVIOUS"
TITLE="Examples"
HREF="spi-examples.html"><LINK
REL="NEXT"
TITLE="Logical Decoding"
HREF="logicaldecoding.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2017-02-06T21:56:32">

PostgreSQL 9.6.2 Documentation

Prev	Up		Next

Chapter 46. Background Worker Processes

  PostgreSQL can be extended to run user-supplied code in separate processes.
  Such processes are started, stopped and monitored by <TT
CLASS="COMMAND"
>postgres</TT
>,
  which permits them to have a lifetime closely linked to the server's status.
  These processes have the option to attach to PostgreSQL's
  shared memory area and to connect to databases internally; they can also run
  multiple transactions serially, just like a regular client-connected server
  process.  Also, by linking to libpq they can connect to the
  server and behave like a regular client application.

Warning

   There are considerable robustness and security risks in using background
   worker processes because, being written in the <TT
CLASS="LITERAL"
>C</TT
> language,
   they have unrestricted access to data.  Administrators wishing to enable
   modules that include background worker process should exercise extreme
   caution.  Only carefully audited modules should be permitted to run
   background worker processes.

  Background workers can be initialized at the time that
  PostgreSQL is started by including the module name in
  <TT
CLASS="VARNAME"
>shared_preload_libraries</TT
>.  A module wishing to run a background
  worker can register it by calling
  RegisterBackgroundWorker(<TT
CLASS="TYPE"
>BackgroundWorker *worker</TT
>)
  from its _PG_init().  Background workers can also be started
  after the system is up and running by calling the function
  RegisterDynamicBackgroundWorker(<TT
CLASS="TYPE"
>BackgroundWorker
  *worker, BackgroundWorkerHandle **handle</TT
>).  Unlike
  RegisterBackgroundWorker, which can only be called from within
  the postmaster, RegisterDynamicBackgroundWorker must be
  called from a regular backend.

  The structure <TT
CLASS="STRUCTNAME"
>BackgroundWorker</TT
> is defined thus:

typedef void (*bgworker_main_type)(Datum main_arg);
typedef struct BackgroundWorker
{
    char        bgw_name[BGW_MAXLEN];
    int         bgw_flags;
    BgWorkerStartTime bgw_start_time;
    int         bgw_restart_time;       /* in seconds, or BGW_NEVER_RESTART */
    bgworker_main_type bgw_main;
    char        bgw_library_name[BGW_MAXLEN];   /* only if bgw_main is NULL */
    char        bgw_function_name[BGW_MAXLEN];  /* only if bgw_main is NULL */
    Datum       bgw_main_arg;
    char        bgw_extra[BGW_EXTRALEN];
    int         bgw_notify_pid;
} BackgroundWorker;

   <TT
CLASS="STRUCTFIELD"
>bgw_name</TT
> is a string to be used in log messages, process
   listings and similar contexts.

   <TT
CLASS="STRUCTFIELD"
>bgw_flags</TT
> is a bitwise-or'd bit mask indicating the
   capabilities that the module wants.  Possible values are:

<TT
CLASS="LITERAL"
>BGWORKER_SHMEM_ACCESS</TT
>

       Requests shared memory access.  Workers without shared memory access
       cannot access any of PostgreSQL's shared
       data structures, such as heavyweight or lightweight locks, shared
       buffers, or any custom data structures which the worker itself may
       wish to create and use.

<TT
CLASS="LITERAL"
>BGWORKER_BACKEND_DATABASE_CONNECTION</TT
>

       Requests the ability to establish a database connection through which it
       can later run transactions and queries.  A background worker using
       <TT
CLASS="LITERAL"
>BGWORKER_BACKEND_DATABASE_CONNECTION</TT
> to connect to a
       database must also attach shared memory using
       <TT
CLASS="LITERAL"
>BGWORKER_SHMEM_ACCESS</TT
>, or worker start-up will fail.

   <TT
CLASS="STRUCTFIELD"
>bgw_start_time</TT
> is the server state during which
   <TT
CLASS="COMMAND"
>postgres</TT
> should start the process; it can be one of
   <TT
CLASS="LITERAL"
>BgWorkerStart_PostmasterStart</TT
> (start as soon as
   <TT
CLASS="COMMAND"
>postgres</TT
> itself has finished its own initialization; processes
   requesting this are not eligible for database connections),
   <TT
CLASS="LITERAL"
>BgWorkerStart_ConsistentState</TT
> (start as soon as a consistent state
   has been reached in a hot standby, allowing processes to connect to
   databases and run read-only queries), and
   <TT
CLASS="LITERAL"
>BgWorkerStart_RecoveryFinished</TT
> (start as soon as the system has
   entered normal read-write state).  Note the last two values are equivalent
   in a server that's not a hot standby.  Note that this setting only indicates
   when the processes are to be started; they do not stop when a different state
   is reached.

   <TT
CLASS="STRUCTFIELD"
>bgw_restart_time</TT
> is the interval, in seconds, that
   <TT
CLASS="COMMAND"
>postgres</TT
> should wait before restarting the process, in
   case it crashes.  It can be any positive value,
   or <TT
CLASS="LITERAL"
>BGW_NEVER_RESTART</TT
>, indicating not to restart the
   process in case of a crash.

   <TT
CLASS="STRUCTFIELD"
>bgw_main</TT
> is a pointer to the function to run when
   the process is started.  This field can only safely be used to launch
   functions within the core server, because shared libraries may be loaded
   at different starting addresses in different backend processes.  This will
   happen on all platforms when the library is loaded using any mechanism
   other than shared_preload_libraries.  Even when that
   mechanism is used, address space layout variations will still occur on
   Windows, and when <TT
CLASS="LITERAL"
>EXEC_BACKEND</TT
> is used.  Therefore, most users
   of this API should set this field to NULL.  If it is non-NULL, it takes
   precedence over <TT
CLASS="STRUCTFIELD"
>bgw_library_name</TT
> and
   <TT
CLASS="STRUCTFIELD"
>bgw_function_name</TT
>.

   <TT
CLASS="STRUCTFIELD"
>bgw_library_name</TT
> is the name of a library in
   which the initial entry point for the background worker should be sought.
   The named library will be dynamically loaded by the worker process and
   <TT
CLASS="STRUCTFIELD"
>bgw_function_name</TT
> will be used to identify the
   function to be called.  If loading a function from the core code,
   <TT
CLASS="STRUCTFIELD"
>bgw_main</TT
> should be set instead.

   <TT
CLASS="STRUCTFIELD"
>bgw_function_name</TT
> is the name of a function in
   a dynamically loaded library which should be used as the initial entry point
   for a new background worker.

   <TT
CLASS="STRUCTFIELD"
>bgw_main_arg</TT
> is the <TT
CLASS="TYPE"
>Datum</TT
> argument
   to the background worker main function.  Regardless of whether that
   function is specified via <TT
CLASS="STRUCTFIELD"
>bgw_main</TT
> or via the combination
   of bgw_library_name and bgw_function_name,
   this main function should take a single argument of type <TT
CLASS="TYPE"
>Datum</TT
>
   and return <TT
CLASS="TYPE"
>void</TT
>.  <TT
CLASS="STRUCTFIELD"
>bgw_main_arg</TT
> will be
   passed as the argument.  In addition, the global variable
   <TT
CLASS="LITERAL"
>MyBgworkerEntry</TT
>
   points to a copy of the <TT
CLASS="STRUCTNAME"
>BackgroundWorker</TT
> structure
   passed at registration time; the worker may find it helpful to examine
   this structure.

   On Windows (and anywhere else where <TT
CLASS="LITERAL"
>EXEC_BACKEND</TT
> is
   defined) or in dynamic background workers it is not safe to pass a
   <TT
CLASS="TYPE"
>Datum</TT
> by reference, only by value. If an argument is required, it
   is safest to pass an int32 or other small value and use that as an index
   into an array allocated in shared memory. If a value like a <TT
CLASS="TYPE"
>cstring</TT
>
   or <TT
CLASS="TYPE"
>text</TT
> is passed then the pointer won't be valid from the
   new background worker process.

   <TT
CLASS="STRUCTFIELD"
>bgw_extra</TT
> can contain extra data to be passed
   to the background worker.  Unlike <TT
CLASS="STRUCTFIELD"
>bgw_main_arg</TT
>, this data
   is not passed as an argument to the worker's main function, but it can be
   accessed via <TT
CLASS="LITERAL"
>MyBgworkerEntry</TT
>, as discussed above.

   <TT
CLASS="STRUCTFIELD"
>bgw_notify_pid</TT
> is the PID of a PostgreSQL
   backend process to which the postmaster should send <TT
CLASS="LITERAL"
>SIGUSR1</TT
>
   when the process is started or exits.  It should be 0 for workers registered
   at postmaster startup time, or when the backend registering the worker does
   not wish to wait for the worker to start up.  Otherwise, it should be
   initialized to <TT
CLASS="LITERAL"
>MyProcPid</TT
>.

Once running, the process can connect to a database by calling
   BackgroundWorkerInitializeConnection(<TT
CLASS="PARAMETER"
>char *dbname</TT
>, <TT
CLASS="PARAMETER"
>char *username</TT
>) or
   BackgroundWorkerInitializeConnectionByOid(<TT
CLASS="PARAMETER"
>Oid dboid</TT
>, <TT
CLASS="PARAMETER"
>Oid useroid</TT
>).
   This allows the process to run transactions and queries using the
   <TT
CLASS="LITERAL"
>SPI</TT
> interface.  If <TT
CLASS="VARNAME"
>dbname</TT
> is NULL or
   <TT
CLASS="VARNAME"
>dboid</TT
> is <TT
CLASS="LITERAL"
>InvalidOid</TT
>, the session is not connected
   to any particular database, but shared catalogs can be accessed.
   If <TT
CLASS="VARNAME"
>username</TT
> is NULL or <TT
CLASS="VARNAME"
>useroid</TT
> is
   <TT
CLASS="LITERAL"
>InvalidOid</TT
>, the process will run as the superuser created
   during <TT
CLASS="COMMAND"
>initdb</TT
>.
   A background worker can only call one of these two functions, and only
   once.  It is not possible to switch databases.

   Signals are initially blocked when control reaches the
   <TT
CLASS="STRUCTFIELD"
>bgw_main</TT
> function, and must be unblocked by it; this is to
   allow the process to customize its signal handlers, if necessary.
   Signals can be unblocked in the new process by calling
   BackgroundWorkerUnblockSignals and blocked by calling
   BackgroundWorkerBlockSignals.

   If <TT
CLASS="STRUCTFIELD"
>bgw_restart_time</TT
> for a background worker is
   configured as <TT
CLASS="LITERAL"
>BGW_NEVER_RESTART</TT
>, or if it exits with an exit
   code of 0 or is terminated by TerminateBackgroundWorker,
   it will be automatically unregistered by the postmaster on exit.
   Otherwise, it will be restarted after the time period configured via
   <TT
CLASS="STRUCTFIELD"
>bgw_restart_time</TT
>, or immediately if the postmaster
   reinitializes the cluster due to a backend failure.  Backends which need
   to suspend execution only temporarily should use an interruptible sleep
   rather than exiting; this can be achieved by calling
   WaitLatch(). Make sure the
   <TT
CLASS="LITERAL"
>WL_POSTMASTER_DEATH</TT
> flag is set when calling that function, and
   verify the return code for a prompt exit in the emergency case that
   <TT
CLASS="COMMAND"
>postgres</TT
> itself has terminated.

   When a background worker is registered using the
   RegisterDynamicBackgroundWorker function, it is
   possible for the backend performing the registration to obtain information
   regarding the status of the worker.  Backends wishing to do this should
   pass the address of a <TT
CLASS="TYPE"
>BackgroundWorkerHandle *</TT
> as the second
   argument to RegisterDynamicBackgroundWorker.  If the
   worker is successfully registered, this pointer will be initialized with an
   opaque handle that can subsequently be passed to
   GetBackgroundWorkerPid(<TT
CLASS="PARAMETER"
>BackgroundWorkerHandle *</TT
>, <TT
CLASS="PARAMETER"
>pid_t *</TT
>) or
   TerminateBackgroundWorker(<TT
CLASS="PARAMETER"
>BackgroundWorkerHandle *</TT
>).
   GetBackgroundWorkerPid can be used to poll the status of the
   worker: a return value of <TT
CLASS="LITERAL"
>BGWH_NOT_YET_STARTED</TT
> indicates that
   the worker has not yet been started by the postmaster;
   <TT
CLASS="LITERAL"
>BGWH_STOPPED</TT
> indicates that it has been started but is
   no longer running; and <TT
CLASS="LITERAL"
>BGWH_STARTED</TT
> indicates that it is
   currently running.  In this last case, the PID will also be returned via the
   second argument.
   TerminateBackgroundWorker causes the postmaster to send
   <TT
CLASS="LITERAL"
>SIGTERM</TT
> to the worker if it is running, and to unregister it
   as soon as it is not.

   In some cases, a process which registers a background worker may wish to
   wait for the worker to start up.  This can be accomplished by initializing
   <TT
CLASS="STRUCTFIELD"
>bgw_notify_pid</TT
> to <TT
CLASS="LITERAL"
>MyProcPid</TT
> and
   then passing the <TT
CLASS="TYPE"
>BackgroundWorkerHandle *</TT
> obtained at
   registration time to
   WaitForBackgroundWorkerStartup(<TT
CLASS="PARAMETER"
>BackgroundWorkerHandle
   *handle</TT
>, <TT
CLASS="PARAMETER"
>pid_t *</TT
>) function.
   This function will block until the postmaster has attempted to start the
   background worker, or until the postmaster dies.  If the background runner
   is running, the return value will <TT
CLASS="LITERAL"
>BGWH_STARTED</TT
>, and
   the PID will be written to the provided address.  Otherwise, the return
   value will be <TT
CLASS="LITERAL"
>BGWH_STOPPED</TT
> or
   <TT
CLASS="LITERAL"
>BGWH_POSTMASTER_DIED</TT
>.

   If a background worker sends asynchronous notifications with the
   <TT
CLASS="COMMAND"
>NOTIFY</TT
> command via the Server Programming Interface
   (<ACRONYM
CLASS="ACRONYM"
>SPI</ACRONYM
>), it should call
   ProcessCompletedNotifies explicitly after committing
   the enclosing transaction so that any notifications can be delivered.  If a
   background worker registers to receive asynchronous notifications with
   the <TT
CLASS="COMMAND"
>LISTEN</TT
> through <ACRONYM
CLASS="ACRONYM"
>SPI</ACRONYM
>, the worker
   will log those notifications, but there is no programmatic way for the
   worker to intercept and respond to those notifications.

   The <TT
CLASS="FILENAME"
>src/test/modules/worker_spi</TT
> module
   contains a working example,
   which demonstrates some useful techniques.

   The maximum number of registered background workers is limited by
   max_worker_processes.

Prev	Home	Next

Examples	Up	Logical Decoding

redpajama_set_name: RedPajamaGithub


text:
use crate::async_rt;
use crate::error::{ZmqError, ZmqResult};

use futures_channel::oneshot;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum TaskError {
    #[error("Internal task error: {0}")]
    Internal(#[from] Box<ZmqError>),
    #[error("Task panicked")]
    Panic,
    #[error("Task cancelled")]
    Cancelled,
}
impl From<async_rt::task::JoinError> for TaskError {
    fn from(err: async_rt::task::JoinError) -> Self {
        if err.is_panic() {
            TaskError::Panic
        } else {
            debug_assert!(err.is_cancelled());
            TaskError::Cancelled
        }
    }
}

pub struct TaskHandle<T> {
    // Using options to allow us to move resource without consuming `self`
    stop_channel: oneshot::Sender<()>,
    join_handle: async_rt::task::JoinHandle<ZmqResult<T>>,
}
impl<T> TaskHandle<T> {
    #[allow(unused)]
    pub(crate) fn new(
        stop_channel: oneshot::Sender<()>,
        join_handle: async_rt::task::JoinHandle<ZmqResult<T>>,
    ) -> Self {
        Self {
            stop_channel,
            join_handle,
        }
    }

    /// Shutdown the task and return the task's result, consuming the handle
    /// in the process
    #[allow(dead_code)]
    pub(crate) async fn shutdown(self) -> ZmqResult<T> {
        // Its ok to ignore possible error, because a dropped channel it has the same
        // effect as sending stop signal
        let _ = self.stop_channel.send(());
        let join_result = self.join_handle.await.map_err(TaskError::from);
        match join_result {
            Ok(Ok(ok)) => Ok(ok),
            Ok(Err(zmq_err)) => Err(zmq_err),
            Err(task_err) => Err(task_err.into()),
        }
    }
}


text:
[![Build Status](https://secure.travis-ci.org/zendframework/zend-xmlrpc.svg?branch=master)](https://secure.travis-ci.org/zendframework/zend-xmlrpc)
[![Coverage Status](https://coveralls.io/repos/github/zendframework/zend-xmlrpc/badge.svg?branch=master)](https://coveralls.io/github/zendframework/zend-xmlrpc?branch=master)

From its home page, XML-RPC is described as a "...remote procedure calling using
HTTP as the transport and XML as the encoding. XML-RPC is designed to be as
simple as possible, while allowing complex data structures to be transmitted,
processed and returned."

`Zend\XmlRpc` provides support for both consuming remote XML-RPC services and
building new XML-RPC servers.

- File issues at https://github.com/zendframework/zend-xmlrpc/issues
- Documentation is at https://docs.zendframework.com/zend-xmlrpc/


text:
#ifndef __OPENSPACE_CORE___INTLISTPROPERTY___H__
#define __OPENSPACE_CORE___INTLISTPROPERTY___H__

#include <openspace/properties/listproperty.h>

namespace openspace::properties {

class IntListProperty : public ListProperty<int> {
public:
    IntListProperty(Property::PropertyInfo info,
        std::vector<int> values = std::vector<int>());

    std::string_view className() const override;
    int typeLua() const override;

    using TemplateProperty<std::vector<int>>::operator std::vector<int>;
    using TemplateProperty<std::vector<int>>::operator=;

protected:
    std::vector<int> fromLuaConversion(lua_State* state, bool& success) const override;
    void toLuaConversion(lua_State* state) const override;
    std::string toStringConversion() const override;
};

} // namespace openspace::properties

#endif // __OPENSPACE_CORE___INTLISTPROPERTY___H__


text:
import {
	Collection,
	CollectionInsertOneOptions,
	Cursor,
	DeleteWriteOpResultObject,
	FilterQuery,
	FindOneOptions,
	InsertOneWriteOpResult,
	InsertWriteOpResult,
	ObjectID,
	ObjectId,
	OptionalId,
	UpdateManyOptions,
	UpdateOneOptions,
	UpdateQuery,
	UpdateWriteOpResult,
	WithId,
	WriteOpResult,
} from 'mongodb';

// [extracted from @types/mongo] TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions
type EnhancedOmit<T, K> = string | number extends keyof T
	? T // T has indexed type e.g. { _id: string; [k: string]: any; } or it is "any"
	: T extends any
		? Pick<T, Exclude<keyof T, K>> // discriminated unions
		: never;

// [extracted from @types/mongo]
type ExtractIdType<TSchema> = TSchema extends { _id: infer U } // user has defined a type for _id
	? {} extends U
		? Exclude<U, {}>
		: unknown extends U
			? ObjectId
			: U
	: ObjectId;

type ModelOptionalId<T> = EnhancedOmit<T, '_id'> & { _id?: ExtractIdType<T> };

interface ITrash {
	__collection__: string;
}

export interface IBaseRaw<T> {
	col: Collection<T>;
}

const baseName = 'rocketchat_';

export class BaseRaw<T> implements IBaseRaw<T> {
	public defaultFields?: Record<string, 1 | 0>;

	protected name: string;

	constructor(
		public readonly col: Collection<T>,
		public readonly trash?: Collection<T>,
	) {
		this.name = this.col.collectionName.replace(baseName, '');
	}

	_ensureDefaultFields<T>(options: FindOneOptions<T>): FindOneOptions<T> {
		if (!this.defaultFields) {
			return options;
		}

		if (!options) {
			return { projection: this.defaultFields };
		}

		// TODO: change all places using "fields" for raw models and remove the additional condition here
		if ((options.projection != null && Object.keys(options.projection).length > 0)
		|| (options.fields != null && Object.keys(options.fields).length > 0)) {
			return options;
		}

		return {
			...options,
			projection: this.defaultFields,
		};
	}

	async findOneById(_id: string, options: FindOneOptions<T> = {}): Promise<T | undefined> {
		return this.findOne({ _id }, options);
	}

	async findOne(query = {}, options: FindOneOptions<T> = {}): Promise<T | undefined> {
		const optionsDef = this._ensureDefaultFields<T>(options);

		if (typeof query === 'string') {
			return this.findOneById(query, options);
		}

		return await this.col.findOne<T>(query, optionsDef) ?? undefined;
	}

	findUsersInRoles(): void {
		throw new Error('[overwrite-function] You must overwrite this function in the extended classes');
	}

	find(query = {}, options: FindOneOptions<T> = {}): Cursor<T> {
		const optionsDef = this._ensureDefaultFields(options);
		return this.col.find(query, optionsDef);
	}

	update(filter: FilterQuery<T>, update: UpdateQuery<T> | Partial<T>, options?: UpdateOneOptions & { multi?: boolean }): Promise<WriteOpResult> {
		return this.col.update(filter, update, options);
	}

	updateOne(filter: FilterQuery<T>, update: UpdateQuery<T> | Partial<T>, options?: UpdateOneOptions & { multi?: boolean }): Promise<UpdateWriteOpResult> {
		return this.col.updateOne(filter, update, options);
	}

	updateMany(filter: FilterQuery<T>, update: UpdateQuery<T> | Partial<T>, options?: UpdateManyOptions): Promise<UpdateWriteOpResult> {
		return this.col.updateMany(filter, update, options);
	}

	insertMany(docs: Array<ModelOptionalId<T>>, options?: CollectionInsertOneOptions): Promise<InsertWriteOpResult<WithId<T>>> {
		docs = docs.map((doc) => {
			if (!doc._id || typeof doc._id !== 'string') {
				const oid = new ObjectID();
				return { _id: oid.toHexString(), ...doc };
			}
			return doc;
		});

		// TODO reavaluate following type casting
		return this.col.insertMany(docs as unknown as Array<OptionalId<T>>, options);
	}

	insertOne(doc: ModelOptionalId<T>, options?: CollectionInsertOneOptions): Promise<InsertOneWriteOpResult<WithId<T>>> {
		if (!doc._id || typeof doc._id !== 'string') {
			const oid = new ObjectID();
			doc = { _id: oid.toHexString(), ...doc };
		}

		// TODO reavaluate following type casting
		return this.col.insertOne(doc as unknown as OptionalId<T>, options);
	}

	removeById(_id: string): Promise<DeleteWriteOpResultObject> {
		const query: object = { _id };
		return this.col.deleteOne(query);
	}

	// Trash
	trashFind(query: FilterQuery<T & ITrash>, options: FindOneOptions<T>): Cursor<T> | undefined {
		return this.trash?.find<T>({
			__collection__: this.name,
			...query,
		}, options);
	}

	async trashFindOneById(_id: string, options: FindOneOptions<T> = {}): Promise<T | undefined> {
		const query: object = {
			_id,
			__collection__: this.name,
		};

		return await this.trash?.findOne<T>(query, options) ?? undefined;
	}
}


text:
@interface TapLabel : UILabel

- (void)setupIconfontWithText:(NSString *)text size:(float)size textColor:(UIColor *)textColor andTapAction:(void (^)(id obj))action;

@end


text:
{% with DEFAULT_VIEW_OBJECTS.ask_admin as ask_admin %}

            Ask an Admin

        Got a question that's not answered here? Type it below and an admin will email you
        the answer.
        <form id="help-ask-form" action="{% url 'ask_admin_feedback' %}"
                                 method="POST">
            {% csrf_token %}
            {{ ask_admin.form.url }}
            {% if ask_admin.form.question.errors %}
                {{ ask_admin.form.question.errors }}
            {% endif %}
            {{ ask_admin.form.question }}

                <button id="help-ask-submit" class="btn btn-widget" disabled="true" href="javascript:void(0);">Send</button>

                Sending

        </form>

{% endwith %}


text:
#ifndef NN_CHUNK_INCLUDED
#define NN_CHUNK_INCLUDED

#include <stddef.h>
#include "int.h"

/*  Allocates the chunk using the allocation mechanism specified by 'type'. */
int nn_chunk_alloc (size_t size, int type, void **result);

/*  Resizes a chunk previously allocated with nn_chunk_alloc. */
int nn_chunk_realloc (size_t size, void **chunk);

/*  Releases a reference to the chunk and once the reference count had dropped
    to zero, deallocates the chunk. */
void nn_chunk_free (void *p);

/*  Increases the reference count of the chunk by 'n'. */
void nn_chunk_addref (void *p, uint32_t n);

/*  Returns size of the chunk buffer. */
size_t nn_chunk_size (void *p);

/*  Trims n bytes from the beginning of the chunk. Returns pointer to the new
    chunk. */
void *nn_chunk_trim (void *p, size_t n);

#endif


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Describes the vCPU configurations for the instance type.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class VCpuInfo implements Serializable, Cloneable {

    /**
     *

     * The default number of vCPUs for the instance type.
     *

     */
    private Integer defaultVCpus;
    /**
     *

     * The default number of cores for the instance type.
     *

     */
    private Integer defaultCores;
    /**
     *

     * The default number of threads per core for the instance type.
     *

     */
    private Integer defaultThreadsPerCore;
    /**
     *

     * The valid number of cores that can be configured for the instance type.
     *

     */
    private com.amazonaws.internal.SdkInternalList<Integer> validCores;
    /**
     *

     * The valid number of threads per core that can be configured for the instance type.
     *

     */
    private com.amazonaws.internal.SdkInternalList<Integer> validThreadsPerCore;

    /**
     *

     * The default number of vCPUs for the instance type.
     *

     *
     * @param defaultVCpus
     *        The default number of vCPUs for the instance type.
     */

    public void setDefaultVCpus(Integer defaultVCpus) {
        this.defaultVCpus = defaultVCpus;
    }

    /**
     *

     * The default number of vCPUs for the instance type.
     *

     *
     * @return The default number of vCPUs for the instance type.
     */

    public Integer getDefaultVCpus() {
        return this.defaultVCpus;
    }

    /**
     *

     * The default number of vCPUs for the instance type.
     *

     *
     * @param defaultVCpus
     *        The default number of vCPUs for the instance type.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public VCpuInfo withDefaultVCpus(Integer defaultVCpus) {
        setDefaultVCpus(defaultVCpus);
        return this;
    }

    /**
     *

     * The default number of cores for the instance type.
     *

     *
     * @param defaultCores
     *        The default number of cores for the instance type.
     */

    public void setDefaultCores(Integer defaultCores) {
        this.defaultCores = defaultCores;
    }

    /**
     *

     * The default number of cores for the instance type.
     *

     *
     * @return The default number of cores for the instance type.
     */

    public Integer getDefaultCores() {
        return this.defaultCores;
    }

    /**
     *

     * The default number of cores for the instance type.
     *

     *
     * @param defaultCores
     *        The default number of cores for the instance type.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public VCpuInfo withDefaultCores(Integer defaultCores) {
        setDefaultCores(defaultCores);
        return this;
    }

    /**
     *

     * The default number of threads per core for the instance type.
     *

     *
     * @param defaultThreadsPerCore
     *        The default number of threads per core for the instance type.
     */

    public void setDefaultThreadsPerCore(Integer defaultThreadsPerCore) {
        this.defaultThreadsPerCore = defaultThreadsPerCore;
    }

    /**
     *

     * The default number of threads per core for the instance type.
     *

     *
     * @return The default number of threads per core for the instance type.
     */

    public Integer getDefaultThreadsPerCore() {
        return this.defaultThreadsPerCore;
    }

    /**
     *

     * The default number of threads per core for the instance type.
     *

     *
     * @param defaultThreadsPerCore
     *        The default number of threads per core for the instance type.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public VCpuInfo withDefaultThreadsPerCore(Integer defaultThreadsPerCore) {
        setDefaultThreadsPerCore(defaultThreadsPerCore);
        return this;
    }

    /**
     *

     * The valid number of cores that can be configured for the instance type.
     *

     *
     * @return The valid number of cores that can be configured for the instance type.
     */

    public java.util.List<Integer> getValidCores() {
        if (validCores == null) {
            validCores = new com.amazonaws.internal.SdkInternalList<Integer>();
        }
        return validCores;
    }

    /**
     *

     * The valid number of cores that can be configured for the instance type.
     *

     *
     * @param validCores
     *        The valid number of cores that can be configured for the instance type.
     */

    public void setValidCores(java.util.Collection<Integer> validCores) {
        if (validCores == null) {
            this.validCores = null;
            return;
        }

        this.validCores = new com.amazonaws.internal.SdkInternalList<Integer>(validCores);
    }

    /**
     *

     * The valid number of cores that can be configured for the instance type.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setValidCores(java.util.Collection)} or {@link #withValidCores(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param validCores
     *        The valid number of cores that can be configured for the instance type.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public VCpuInfo withValidCores(Integer... validCores) {
        if (this.validCores == null) {
            setValidCores(new com.amazonaws.internal.SdkInternalList<Integer>(validCores.length));
        }
        for (Integer ele : validCores) {
            this.validCores.add(ele);
        }
        return this;
    }

    /**
     *

     * The valid number of cores that can be configured for the instance type.
     *

     *
     * @param validCores
     *        The valid number of cores that can be configured for the instance type.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public VCpuInfo withValidCores(java.util.Collection<Integer> validCores) {
        setValidCores(validCores);
        return this;
    }

    /**
     *

     * The valid number of threads per core that can be configured for the instance type.
     *

     *
     * @return The valid number of threads per core that can be configured for the instance type.
     */

    public java.util.List<Integer> getValidThreadsPerCore() {
        if (validThreadsPerCore == null) {
            validThreadsPerCore = new com.amazonaws.internal.SdkInternalList<Integer>();
        }
        return validThreadsPerCore;
    }

    /**
     *

     * The valid number of threads per core that can be configured for the instance type.
     *

     *
     * @param validThreadsPerCore
     *        The valid number of threads per core that can be configured for the instance type.
     */

    public void setValidThreadsPerCore(java.util.Collection<Integer> validThreadsPerCore) {
        if (validThreadsPerCore == null) {
            this.validThreadsPerCore = null;
            return;
        }

        this.validThreadsPerCore = new com.amazonaws.internal.SdkInternalList<Integer>(validThreadsPerCore);
    }

    /**
     *

     * The valid number of threads per core that can be configured for the instance type.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setValidThreadsPerCore(java.util.Collection)} or {@link #withValidThreadsPerCore(java.util.Collection)}
     * if you want to override the existing values.
     *

     *
     * @param validThreadsPerCore
     *        The valid number of threads per core that can be configured for the instance type.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public VCpuInfo withValidThreadsPerCore(Integer... validThreadsPerCore) {
        if (this.validThreadsPerCore == null) {
            setValidThreadsPerCore(new com.amazonaws.internal.SdkInternalList<Integer>(validThreadsPerCore.length));
        }
        for (Integer ele : validThreadsPerCore) {
            this.validThreadsPerCore.add(ele);
        }
        return this;
    }

    /**
     *

     * The valid number of threads per core that can be configured for the instance type.
     *

     *
     * @param validThreadsPerCore
     *        The valid number of threads per core that can be configured for the instance type.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public VCpuInfo withValidThreadsPerCore(java.util.Collection<Integer> validThreadsPerCore) {
        setValidThreadsPerCore(validThreadsPerCore);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDefaultVCpus() != null)
            sb.append("DefaultVCpus: ").append(getDefaultVCpus()).append(",");
        if (getDefaultCores() != null)
            sb.append("DefaultCores: ").append(getDefaultCores()).append(",");
        if (getDefaultThreadsPerCore() != null)
            sb.append("DefaultThreadsPerCore: ").append(getDefaultThreadsPerCore()).append(",");
        if (getValidCores() != null)
            sb.append("ValidCores: ").append(getValidCores()).append(",");
        if (getValidThreadsPerCore() != null)
            sb.append("ValidThreadsPerCore: ").append(getValidThreadsPerCore());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof VCpuInfo == false)
            return false;
        VCpuInfo other = (VCpuInfo) obj;
        if (other.getDefaultVCpus() == null ^ this.getDefaultVCpus() == null)
            return false;
        if (other.getDefaultVCpus() != null && other.getDefaultVCpus().equals(this.getDefaultVCpus()) == false)
            return false;
        if (other.getDefaultCores() == null ^ this.getDefaultCores() == null)
            return false;
        if (other.getDefaultCores() != null && other.getDefaultCores().equals(this.getDefaultCores()) == false)
            return false;
        if (other.getDefaultThreadsPerCore() == null ^ this.getDefaultThreadsPerCore() == null)
            return false;
        if (other.getDefaultThreadsPerCore() != null && other.getDefaultThreadsPerCore().equals(this.getDefaultThreadsPerCore()) == false)
            return false;
        if (other.getValidCores() == null ^ this.getValidCores() == null)
            return false;
        if (other.getValidCores() != null && other.getValidCores().equals(this.getValidCores()) == false)
            return false;
        if (other.getValidThreadsPerCore() == null ^ this.getValidThreadsPerCore() == null)
            return false;
        if (other.getValidThreadsPerCore() != null && other.getValidThreadsPerCore().equals(this.getValidThreadsPerCore()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDefaultVCpus() == null) ? 0 : getDefaultVCpus().hashCode());
        hashCode = prime * hashCode + ((getDefaultCores() == null) ? 0 : getDefaultCores().hashCode());
        hashCode = prime * hashCode + ((getDefaultThreadsPerCore() == null) ? 0 : getDefaultThreadsPerCore().hashCode());
        hashCode = prime * hashCode + ((getValidCores() == null) ? 0 : getValidCores().hashCode());
        hashCode = prime * hashCode + ((getValidThreadsPerCore() == null) ? 0 : getValidThreadsPerCore().hashCode());
        return hashCode;
    }

    @Override
    public VCpuInfo clone() {
        try {
            return (VCpuInfo) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
// Configuration dependencies
global.$AnsibleConfig = null;
// Provided via Webpack DefinePlugin in webpack.config.js
global.$ENV = {} ;
// ui-router debugging
if ($ENV['route-debug']){
    let trace = angular.module('ui.router').trace;
    trace.enable();
}

var urlPrefix;

if ($basePath) {
    urlPrefix = `${$basePath}`;
}

// Modules
import portalMode from './portal-mode/main';
import systemTracking from './system-tracking/main';
import inventoriesHosts from './inventories-hosts/main';
import inventoryScripts from './inventory-scripts/main';
import credentials from './credentials/main';
import credentialTypes from './credential-types/main';
import organizations from './organizations/main';
import managementJobs from './management-jobs/main';
import workflowResults from './workflow-results/main';
import jobResults from './job-results/main';
import jobSubmission from './job-submission/main';
import notifications from './notifications/main';
import about from './about/main';
import license from './license/main';
import breadCrumb from './bread-crumb/main';
import browserData from './browser-data/main';
import configuration from './configuration/main';
import home from './home/main';
import login from './login/main';
import activityStream from './activity-stream/main';
import standardOut from './standard-out/main';
import Templates from './templates/main';
import jobs from './jobs/main';
import teams from './teams/main';
import users from './users/main';
import projects from './projects/main';
import RestServices from './rest/main';
import access from './access/main';
import scheduler from './scheduler/main';
import instanceGroups from './instance-groups/main';

import '../lib/components';
import '../lib/models';
import '../lib/services';
import '../features';

angular.module('awApp', [
    'I18N',
    'AngularCodeMirrorModule',
    'angular-duration-format',
    'angularMoment',
    'AngularScheduler',
    'angular-md5',
    'dndLists',
    'ncy-angular-breadcrumb',
    'ngSanitize',
    'ngCookies',
    'ngToast',
    'gettext',
    'Timezones',
    'ui.router',
    'ui.router.state.events',
    'lrInfiniteScroll',

    about.name,
    access.name,
    license.name,
    RestServices.name,
    browserData.name,
    configuration.name,
    systemTracking.name,
    inventoriesHosts.name,
    inventoryScripts.name,
    credentials.name,
    credentialTypes.name,
    organizations.name,
    managementJobs.name,
    breadCrumb.name,
    home.name,
    login.name,
    activityStream.name,
    workflowResults.name,
    jobResults.name,
    jobSubmission.name,
    notifications.name,
    standardOut.name,
    Templates.name,
    portalMode.name,
    jobs.name,
    teams.name,
    users.name,
    projects.name,
    scheduler.name,
    instanceGroups.name,

    'Utilities',
    'templates',
    'PromptDialog',
    'AWDirectives',
    'features',

    'at.lib.components',
    'at.lib.models',
    'at.lib.services',
    'at.features',
])
    .constant('AngularScheduler.partials', urlPrefix + 'lib/angular-scheduler/lib/')
    .constant('AngularScheduler.useTimezone', true)
    .constant('AngularScheduler.showUTCField', true)
    .constant('$timezones.definitions.location', urlPrefix + 'lib/angular-tz-extensions/tz/data')
    .config(['$logProvider', function($logProvider) {
        $logProvider.debugEnabled($ENV['ng-debug'] || false);
    }])
    .config(['ngToastProvider', function(ngToastProvider) {
        ngToastProvider.configure({
            animation: 'slide',
            dismissOnTimeout: false,
            dismissButton: true,
            timeout: 4000
        });
    }])
    .config(['$urlRouterProvider', '$breadcrumbProvider', 'QuerySetProvider',
        '$urlMatcherFactoryProvider',
        function($urlRouterProvider, $breadcrumbProvider, QuerySet,
            $urlMatcherFactoryProvider) {
            $urlMatcherFactoryProvider.strictMode(false);
            $breadcrumbProvider.setOptions({
                templateUrl: urlPrefix + 'partials/breadcrumb.html'
            });

            // route to the details pane of /job/:id/host-event/:eventId if no other child specified
            $urlRouterProvider.when('/jobs/*/host-event/*', '/jobs/*/host-event/*/details');
            $urlRouterProvider.otherwise('/home');

            $urlMatcherFactoryProvider.type('queryset', {
                // encoding
                // from {operator__key1__comparator=value, ... }
                // to "_search=operator:key:compator=value& ... "
                encode: function(item) {
                    return QuerySet.$get().encodeArr(item);
                },
                // decoding
                // from "_search=operator:key:compator=value& ... "
                // to {operator__key1__comparator=value, ... }
                decode: function(item) {
                    return QuerySet.$get().decodeArr(item);
                },
                // directionality - are we encoding or decoding?
                is: function(item) {
                    // true: encode to uri
                    // false: decode to $stateParam
                    return angular.isObject(item);
                }
            });

            // Handy hook for debugging register/deregister of lazyLoad'd states
            // $stateProvider.stateRegistry.onStatesChanged((event, states) =>{
            //     console.log(event, states)
            // })
        }
    ])
    .run(['$stateExtender', '$q', '$compile', '$cookies', '$rootScope', '$log', '$stateParams',
        'CheckLicense', '$location', 'Authorization', 'LoadBasePaths', 'Timer',
        'LoadConfig', 'Store', 'pendoService', 'Prompt', 'Rest',
        'Wait', 'ProcessErrors', '$state', 'GetBasePath', 'ConfigService',
        'FeaturesService', '$filter', 'SocketService', 'AppStrings',
        function($stateExtender, $q, $compile, $cookies, $rootScope, $log, $stateParams,
            CheckLicense, $location, Authorization, LoadBasePaths, Timer,
            LoadConfig, Store, pendoService, Prompt, Rest, Wait,
            ProcessErrors, $state, GetBasePath, ConfigService, FeaturesService,
            $filter, SocketService, AppStrings) {
            $rootScope.$state = $state;
            $rootScope.$state.matches = function(stateName) {
                return $state.current.name.search(stateName) > 0;
            };
            $rootScope.$stateParams = $stateParams;

            $state.defaultErrorHandler(function(error) {
                $log.debug(`$state.defaultErrorHandler: ${error}`);
            });

            $rootScope.refresh = function() {
                $state.go('.', null, {reload: true});
            };

            $rootScope.refreshJobs = function(){
                $state.go('.', null, {reload: true});
            };

            $rootScope.breadcrumb = {};
            $rootScope.BRAND_NAME = AppStrings.get('BRAND_NAME');
            $rootScope.tabTitle = `Ansible ${$rootScope.BRAND_NAME}`;
            $rootScope.$watch('$state.current.ncyBreadcrumbLabel', function(title) {
                title = (title) ? "| " + title : "";
                $rootScope.tabTitle = `Ansible ${$rootScope.BRAND_NAME} ${title}`;
            });

            function activateTab() {
                // Make the correct tab active
                var base = $location.path().replace(/^\//, '').split('/')[0];

                if (base === '') {
                    base = 'home';
                } else {
                    //base.replace(/\_/g, ' ');
                    base = (base === 'job_events' || base === 'job_host_summaries') ? 'jobs' : base;
                }
            }

            if ($rootScope.removeConfigReady) {
                $rootScope.removeConfigReady();
            }
            $rootScope.removeConfigReady = $rootScope.$on('ConfigReady', function() {
                var list, id;
                // initially set row edit indicator for crud pages
                if ($location.$$path && $location.$$path.split("/")[3] && $location.$$path.split("/")[3] === "schedules") {
                    list = $location.$$path.split("/")[3];
                    id = $location.$$path.split("/")[4];
                    $rootScope.listBeingEdited = list;
                    $rootScope.rowBeingEdited = id;
                    $rootScope.initialIndicatorLoad = true;
                } else if ($location.$$path.split("/")[2]) {
                    list = $location.$$path.split("/")[1];
                    id = $location.$$path.split("/")[2];
                    $rootScope.listBeingEdited = list;
                    $rootScope.rowBeingEdited = id;
                }

                LoadBasePaths();

                $rootScope.crumbCache = [];

                $rootScope.$on("$stateChangeStart", function (event, next) {
                    // let current_title = $rootScope.$state.current.ncyBreadcrumbLabel || "";
                    // $rootScope.tabTitle = `Ansible ${$rootScope.BRAND_NAME} ${current_title}`;
                    // Remove any lingering intervals
                    // except on jobResults.* states
                    var jobResultStates = [
                        'jobResult',
                        'jobResult.host-summary',
                        'jobResult.host-event.details',
                        'jobResult.host-event.json',
                        'jobResult.host-events',
                        'jobResult.host-event.stdout'
                    ];
                    if ($rootScope.jobResultInterval && !_.includes(jobResultStates, next.name) ) {
                        window.clearInterval($rootScope.jobResultInterval);
                    }
                    if ($rootScope.jobStdOutInterval && !_.includes(jobResultStates, next.name) ) {
                        window.clearInterval($rootScope.jobStdOutInterval);
                    }

                    $rootScope.flashMessage = null;

                    $('#form-modal2 .modal-body').empty();

                    $('.tooltip').each(function() {
                        $(this).remove();
                    });

                    $('.popover').each(function() {
                        $(this).remove();
                    });

                    $('.ui-dialog-content').each(function() {
                        $(this).dialog('close');
                    });

                    try {
                        $('#help-modal').dialog('close');
                    } catch (e) {
                        // ignore
                    }

                    // On each navigation request, check that the user is logged in
                    if (!/^\/(login|logout)/.test($location.path())) {
                        // capture most recent URL, excluding login/logout
                        $rootScope.lastPath = $location.path();
                        $rootScope.enteredPath = $location.path();
                        $cookies.put('lastPath', $location.path());
                    }

                    if (Authorization.isUserLoggedIn() === false) {
                        if (next.name !== "signIn") {
                            $state.go('signIn');
                        }
                    } else if ($rootScope && $rootScope.sessionTimer && $rootScope.sessionTimer.isExpired()) {
                      // gets here on timeout
                        if (next.name !== "signIn") {
                            $state.go('signIn');
                        }
                    } else {
                        if ($rootScope.current_user === undefined || $rootScope.current_user === null) {
                            Authorization.restoreUserInfo(); //user must have hit browser refresh
                        }
                        if (next && (next.name !== "signIn"  && next.name !== "signOut" && next.name !== "license")) {
                            ConfigService.getConfig().then(function() {
                                // if not headed to /login or /logout, then check the license
                                CheckLicense.test(event);
                            });
                        }
                    }
                    activateTab();
                });

                $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {

                    if(toState === fromState) {
                        // check to see if something other than a search param has changed
                        let toParamsWithoutSearchKeys = {};
                        let fromParamsWithoutSearchKeys = {};
                        for (let key in toParams) {
                            if (toParams.hasOwnProperty(key) && !/_search/.test(key)) {
                                toParamsWithoutSearchKeys[key] = toParams[key];
                            }
                        }
                        for (let key in fromParams) {
                            if (fromParams.hasOwnProperty(key) && !/_search/.test(key)) {
                                fromParamsWithoutSearchKeys[key] = fromParams[key];
                            }
                        }

                        if(!_.isEqual(toParamsWithoutSearchKeys, fromParamsWithoutSearchKeys)) {
                            document.body.scrollTop = document.documentElement.scrollTop = 0;
                        }
                    }
                    else {
                        document.body.scrollTop = document.documentElement.scrollTop = 0;
                    }

                    if (fromState.name === 'license' && toParams.hasOwnProperty('licenseMissing')) {
                        $rootScope.licenseMissing = toParams.licenseMissing;
                    }
                    var list, id;
                    // broadcast event change if editing crud object
                    if ($location.$$path && $location.$$path.split("/")[3] && $location.$$path.split("/")[3] === "schedules") {
                        list = $location.$$path.split("/")[3];
                        id = $location.$$path.split("/")[4];

                        if (!$rootScope.initialIndicatorLoad) {
                            delete $rootScope.listBeingEdited;
                            delete $rootScope.rowBeingEdited;
                        } else {
                            delete $rootScope.initialIndicatorLoad;
                        }

                        $rootScope.$broadcast("EditIndicatorChange", list, id);
                    } else if ($location.$$path.split("/")[2]) {
                        list = $location.$$path.split("/")[1];
                        id = $location.$$path.split("/")[2];

                        delete $rootScope.listBeingEdited;
                        delete $rootScope.rowBeingEdited;

                        $rootScope.$broadcast("EditIndicatorChange", list, id);
                    } else if ($rootScope.addedAnItem) {
                        delete $rootScope.addedAnItem;
                        $rootScope.$broadcast("RemoveIndicator");
                    } else {
                        $rootScope.$broadcast("RemoveIndicator");
                    }
                });

                if (!Authorization.getToken() || !Authorization.isUserLoggedIn()) {
                    // User not authenticated, redirect to login page
                    if (!/^\/(login|logout)/.test($location.path())) {
                        $rootScope.preAuthUrl = $location.path();
                    }
                    $location.path('/login');
                } else {
                    var lastUser = $cookies.getObject('current_user'),
                        timestammp = Store('sessionTime');
                    if (lastUser && lastUser.id && timestammp && timestammp[lastUser.id] && timestammp[lastUser.id].loggedIn) {
                        var stime = timestammp[lastUser.id].time,
                            now = new Date().getTime();
                        if ((stime - now) <= 0) {
                            $location.path('/login');
                        }
                    }
                    // If browser refresh, set the user_is_superuser value
                    $rootScope.user_is_superuser = Authorization.getUserInfo('is_superuser');
                    $rootScope.user_is_system_auditor = Authorization.getUserInfo('is_system_auditor');

                    // state the user refreshes we want to open the socket, except if the user is on the login page, which should happen after the user logs in (see the AuthService module for that call to OpenSocket)
                    if (!_.contains($location.$$url, '/login')) {
                        ConfigService.getConfig().then(function() {
                            Timer.init().then(function(timer) {
                                $rootScope.sessionTimer = timer;
                                SocketService.init();
                                pendoService.issuePendoIdentity();
                                CheckLicense.test();
                                FeaturesService.get();
                                if ($location.$$path === "/home" && $state.current && $state.current.name === "") {
                                    $state.go('dashboard');
                                } else if ($location.$$path === "/portal" && $state.current && $state.current.name === "") {
                                    $state.go('portalMode');
                                }
                            });
                        });
                    }
                }

                activateTab();

                $rootScope.viewCurrentUser = function() {
                    $location.path('/users/' + $rootScope.current_user.id);
                };

                $rootScope.viewLicense = function() {
                    $location.path('/license');
                };
                $rootScope.toggleTab = function(e, tab, tabs) {
                    e.preventDefault();
                    $('#' + tabs + ' #' + tab).tab('show');
                };

            }); // end of 'ConfigReady'

            if (!$AnsibleConfig) {
                // create a promise that will resolve state $AnsibleConfig is loaded
                $rootScope.loginConfig = $q.defer();
            }
            if (!$rootScope.featuresConfigured) {
                // create a promise that will resolve when features are loaded
                $rootScope.featuresConfigured = $q.defer();
            }
            $rootScope.licenseMissing = true;
            //the authorization controller redirects to the home page automatcially if there is no last path defined. in order to override
            // this, set the last path to /portal for instances where portal is visited for the first time.
            $rootScope.lastPath = ($location.path() === "/portal") ? 'portal' : undefined;

            LoadConfig();
        }
    ]);


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd" id="_FVEpwO_VEeOtYvXzz5ksgw" exporter="camunda modeler" exporterVersion="2.5.0" targetNamespace="http://camunda.org/schema/1.0/bpmn">
  <process id="testProcess" isExecutable="true">
    <startEvent id="start"/>
    <sequenceFlow id="flow1" name="" sourceRef="start" targetRef="noneThrow"/>
    <intermediateThrowEvent  id="noneThrow">
      <extensionElements>
        <camunda:executionListener class="org.camunda.bpm.engine.test.bpmn.iomapping.VariableLogDelegate" event="start" />
        <camunda:inputOutput>
          <camunda:inputParameter name="mappedVariable">mappedValue</camunda:inputParameter>
          <camunda:outputParameter name="outVariable">${mappedVariable}</camunda:outputParameter>
        </camunda:inputOutput>
      </extensionElements>
    </intermediateThrowEvent>
    <sequenceFlow id="flow2" name="" sourceRef="noneThrow" targetRef="task"/>
    <userTask id="task"/>
    <sequenceFlow id="flow3" name="" sourceRef="task" targetRef="end"/>
    <endEvent id="end"/>
  </process>
</definitions>


text:
var assert = require('assert')
  , svgicons2svgfont = require(__dirname + '/../src/index.js')
  , Fs = require('fs')
  , StringDecoder = require('string_decoder').StringDecoder
  , Path = require("path");

// Helpers
function generateFontToFile(options, done, fileSuffix) {
  var codepoint = 0xE001
    , dest = __dirname + '/results/' + options.fontName
      + (fileSuffix || '') + '.svg'
    , stream = svgicons2svgfont(Fs.readdirSync(__dirname + '/fixtures/' + options.fontName)
      .map(function(file) {
        var matches = file.match(/^(?:u([0-9a-f]{4})\-)?(.*).svg$/i);
        return {
          codepoint: (matches[1] ? parseInt(matches[1], 16) : codepoint++),
          name: matches[2],
          stream: Fs.createReadStream(__dirname + '/fixtures/' + options.fontName + '/' + file)
        };
      }), options);
  stream.pipe(Fs.createWriteStream(dest)).on('finish', function() {
    assert.equal(
      Fs.readFileSync(__dirname + '/expected/' + options.fontName
        + (fileSuffix || '') + '.svg',
        {encoding: 'utf8'}),
      Fs.readFileSync(dest,
        {encoding: 'utf8'})
    );
    done();
  });
}

function generateFontToMemory(options, done) {
  var content = ''
    , decoder = new StringDecoder('utf8')
    , codepoint = 0xE001
    , stream = svgicons2svgfont(Fs.readdirSync(__dirname + '/fixtures/' + options.fontName)
      .map(function(file) {
        var matches = file.match(/^(?:u([0-9a-f]{4})\-)?(.*).svg$/i);
        return {
          codepoint: (matches[1] ? parseInt(matches[1], 16) : codepoint++),
          name: matches[2],
          stream: Fs.createReadStream(__dirname + '/fixtures/' + options.fontName + '/' + file)
        };
      }), options);
  stream.on('data', function(chunk) {
    content += decoder.write(chunk);
  });
  stream.on('finish', function() {
    assert.equal(
      Fs.readFileSync(__dirname + '/expected/' + options.fontName + '.svg',
        {encoding: 'utf8'}),
      content
    );
    done();
  });
}

// Tests
describe('Generating fonts to files', function() {

	it("should work for simple SVG", function(done) {
    generateFontToFile({
      fontName: 'originalicons'
    }, done);
	});

	it("should work for simple fixedWidth and normalize option", function(done) {
    generateFontToFile({
      fontName: 'originalicons',
      fixedWidth: true,
      normalize: true
    }, done, 'n');
	});

	it("should work for simple SVG", function(done) {
    generateFontToFile({
      fontName: 'cleanicons'
    }, done);
	});

	it("should work for codepoint mapped SVG icons", function(done) {
    generateFontToFile({
      fontName: 'prefixedicons',
      callback: function(){}
    }, done);
	});

	it("should work with multipath SVG icons", function(done) {
    generateFontToFile({
      fontName: 'multipathicons'
    }, done);
	});

	it("should work with simple shapes SVG icons", function(done) {
    generateFontToFile({
      fontName: 'shapeicons'
    }, done);
	});

	it("should work with variable height icons", function(done) {
    generateFontToFile({
      fontName: 'variableheighticons'
    }, done);
	});

	it("should work with variable height icons and the normalize option", function(done) {
    generateFontToFile({
      fontName: 'variableheighticons',
      normalize: true
    }, done, 'n');
	});

	it("should work with variable width icons", function(done) {
    generateFontToFile({
      fontName: 'variablewidthicons'
    }, done);
	});

	it("should work with centered variable width icons and the fixed width option", function(done) {
    generateFontToFile({
      fontName: 'variablewidthicons',
      fixedWidth: true,
      centerHorizontally: true
    }, done, 'n');
	});

	it("should not display hidden pathes", function(done) {
    generateFontToFile({
      fontName: 'hiddenpathesicons'
    }, done);
	});

	it("should work with real world icons", function(done) {
    generateFontToFile({
      fontName: 'realicons'
    }, done);
	});

  it("should work with rendering test SVG icons", function(done) {
    generateFontToFile({
      fontName: 'rendricons'
    }, done);
  });

  it("should work with a single SVG icon", function(done) {
    generateFontToFile({
      fontName: 'singleicon'
    }, done);
  });

  it("should work with transformed SVG icons", function(done) {
    generateFontToFile({
      fontName: 'transformedicons'
    }, done);
  });

  it("should work when horizontally centering SVG icons", function(done) {
    generateFontToFile({
      fontName: 'tocentericons',
      centerHorizontally: true
    }, done);
  });

});

describe('Generating fonts to memory', function() {

  it("should work for simple SVG", function(done) {
    generateFontToMemory({
      fontName: 'originalicons'
    }, done);
  });

  it("should work for simple SVG", function(done) {
    generateFontToMemory({
      fontName: 'cleanicons'
    }, done);
  });

  it("should work for codepoint mapped SVG icons", function(done) {
    generateFontToMemory({
      fontName: 'prefixedicons'
    }, done);
  });

  it("should work with multipath SVG icons", function(done) {
    generateFontToMemory({
      fontName: 'multipathicons'
    }, done);
  });

  it("should work with simple shapes SVG icons", function(done) {
    generateFontToMemory({
      fontName: 'shapeicons'
    }, done);
  });

});

describe('Using options', function() {

  it("should work with fixedWidth option set to true", function(done) {
    generateFontToFile({
      fontName: 'originalicons',
      fixedWidth: true
    }, done, '2');
  });

  it("should work with custom fontHeight option", function(done) {
    generateFontToFile({
      fontName: 'originalicons',
      fontHeight: 800
    }, done, '3');
  });

  it("should work with custom descent option", function(done) {
    generateFontToFile({
      fontName: 'originalicons',
      descent: 200
    }, done, '4');
  });

  it("should work with fixedWidth set to true and with custom fontHeight option", function(done) {
    generateFontToFile({
      fontName: 'originalicons',
      fontHeight: 800,
      fixedWidth: true
    }, done, '5');
  });

  it("should work with fixedWidth and centerHorizontally set to true and with custom fontHeight option", function(done) {
    generateFontToFile({
      fontName: 'originalicons',
      fontHeight: 800,
      fixedWidth: true,
      centerHorizontally: true
    }, done, '6');
  });

  it("should work with fixedWidth, normalize and centerHorizontally set to true and with custom fontHeight option", function(done) {
    generateFontToFile({
      fontName: 'originalicons',
      fontHeight: 800,
      normalize: true,
      fixedWidth: true,
      centerHorizontally: true
    }, done, '7');
  });

});

describe('Testing CLI', function() {

  it("should work for simple SVG", function(done) {
    (require('child_process').exec)(
      'node '+__dirname+'../bin/svgicons2svgfont.js '
      + __dirname + '/expected/originalicons.svg '
      + __dirname + '/results/originalicons.svg',
      function() {
        assert.equal(
          Fs.readFileSync(__dirname + '/expected/originalicons.svg',
            {encoding: 'utf8'}),
          Fs.readFileSync(__dirname + '/results/originalicons.svg',
            {encoding: 'utf8'})
        );
        done();
      }
    );
  });

});

describe('Providing bad glyphs', function() {

	it("should fail when not providing glyph name", function() {
	  var hadError = false;
    try {
      svgicons2svgfont([{
	      stream: Fs.createReadStream('/dev/null'),
	      codepoint: 0xE001
      }]);
    } catch(err) {
	    assert.equal(err instanceof Error, true);
	    assert.equal(err.message, 'Please provide a name for the glyph at index 0');
	    hadError = true;
    }
    assert.equal(hadError, true);
	});

	it("should fail when not providing codepoints", function() {
	  var hadError = false;
    try {
      svgicons2svgfont([{
	      stream: Fs.createReadStream('/dev/null'),
	      name: 'test'
      }]);
    } catch(err) {
	    assert.equal(err instanceof Error, true);
	    assert.equal(err.message, 'Please provide a codepoint for the glyph "test"');
	    hadError = true;
    }
    assert.equal(hadError, true);
	});

	it("should fail when providing the same codepoint twice", function() {
	  var hadError = false;
    try {
      svgicons2svgfont([{
	      stream: Fs.createReadStream('/dev/null'),
	      name: 'test',
	      codepoint: 0xE001
      },{
	      stream: Fs.createReadStream('/dev/null'),
	      name: 'test2',
	      codepoint: 0xE001
      }]);
    } catch(err) {
	    assert.equal(err instanceof Error, true);
	    assert.equal(err.message, 'The glyph "test" codepoint seems to be used already elsewhere.');
	    hadError = true;
    }
    assert.equal(hadError, true);
	});

	it("should fail when providing the same name twice", function() {
	  var hadError = false;
    try {
      svgicons2svgfont([{
	      stream: Fs.createReadStream('/dev/null'),
	      name: 'test',
	      codepoint: 0xE001
      },{
	      stream: Fs.createReadStream('/dev/null'),
	      name: 'test',
	      codepoint: 0xE002
      }]);
    } catch(err) {
	    assert.equal(err instanceof Error, true);
	    assert.equal(err.message, 'The glyph name "test" must be unique.');
	    hadError = true;
    }
    assert.equal(hadError, true);
	});

});


text:
package com.blazebit.persistence.parser.predicate;

import com.blazebit.persistence.parser.expression.Expression;
import com.blazebit.persistence.parser.expression.ExpressionCopyContext;

/**
 *
 * @author Christian Beikov
 * @author Moritz Becker
 * @since 1.0.0
 */
public abstract class UnaryExpressionPredicate extends AbstractPredicate {

    protected Expression expression;

    public UnaryExpressionPredicate(Expression expression, boolean negated) {
        super(negated);
        this.expression = expression;
        this.negated = negated;
    }

    public UnaryExpressionPredicate(Expression expression) {
        this(expression, false);
    }

    @Override
    public abstract UnaryExpressionPredicate copy(ExpressionCopyContext copyContext);

    public Expression getExpression() {
        return expression;
    }

    public void setExpression(Expression expression) {
        this.expression = expression;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof UnaryExpressionPredicate)) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }

        UnaryExpressionPredicate that = (UnaryExpressionPredicate) o;

        return expression != null ? expression.equals(that.expression) : that.expression == null;

    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (expression != null ? expression.hashCode() : 0);
        return result;
    }
}


text:
import React from 'react';
import { ForwardRef } from 'react-is';

type ElementType = string | React.ComponentType;

type ExtendedComponentType = React.ComponentType & {
  $$typeof: any;
};

export function isRefSupported(elementType: ElementType): boolean {
  if (typeof elementType === 'string') {
    return false;
  }

  const { $$typeof, prototype } = elementType as ExtendedComponentType;
  return (
    $$typeof === ForwardRef ||
    // Warning: Some functions don't have the .prototype property
    (prototype &&
      // ES6 Class
      // Warning: This will return false is the component is extending a
      // different copy of React than the one used by Cosmos. This is relevant
      // when running Cosmos from an external location instead of node_modules.
      (prototype instanceof React.Component ||
        // React.createClass
        prototype.getInitialState !== undefined) &&
      true)
  );
}


text:
var JATreeMenu = new
function () {
	this.menuid = 'jacom-mainnav';
	this.openedcls = 'opened';
	this.closedcls = 'closed';
	this.initmenu = function () {
		var mainnav = document.getElementById(this.menuid);
		if (!mainnav) return;
		var uls = mainnav.getElementsByTagName('ul');
		var menustatus = Cookie.read('menustatus');

		open_obj = document.getElementById('menu_open');
		close_obj = document.getElementById('menu_close');

		if (menustatus == this.closedcls) {
			close_obj.className = 'closeall';
			open_obj.className = 'openall opened';
		} else {
			open_obj.className = 'openall';
			close_obj.className = 'closeall closed';
		}

		for (var i = 1; i < uls.length; i++) {
			var li = uls[i].parentNode;
			if (li.tagName.toLowerCase() != 'li') continue;

			if (li.className.indexOf('opened') == -1) {

				if (menustatus == "" || menustatus == null) {
					menustatus = this.openedcls;
				}
				li.className += " " + menustatus;
			}
			var a = li.getElementsByTagName('a')[0];
			a._p = li;
			a._o = this.openedcls;
			a._c = this.closedcls;
			a.onclick = function () {
				var _p = this._p;
				if (_p.className.indexOf(this._o) == -1) {
					_p.className = _p.className.replace(new RegExp(" " + this._c + "\\b"), " " + this._o);
				} else {
					_p.className = _p.className.replace(new RegExp(" " + this._o + "\\b"), " " + this._c);
				}
			}
			a.href = 'javascript:;';
		}
	};

	this.openall = function () {
		open_obj = document.getElementById('menu_open');
		open_obj.className = 'openall';
		close_obj = document.getElementById('menu_close');
		close_obj.className = 'closeall closed';
		Cookie.write('menustatus', this.openedcls);
		var mainnav = document.getElementById(this.menuid);
		if (!mainnav) return;
		var uls = mainnav.getElementsByTagName('ul');
		for (var i = 1; i < uls.length; i++) {
			var li = uls[i].parentNode;
			if (li.tagName.toLowerCase() != 'li') continue;
			li.className = li.className.replace(new RegExp(" " + this.closedcls + "\\b"), " " + this.openedcls);
		}

	};
	this.closeall = function () {
		close_obj = document.getElementById('menu_close');
		close_obj.className = 'closeall';
		open_obj = document.getElementById('menu_open');
		open_obj.className = 'openall opened';
		Cookie.write('menustatus', this.closedcls);
		var mainnav = document.getElementById(this.menuid);
		if (!mainnav) return;
		var uls = mainnav.getElementsByTagName('ul');
		for (var i = 1; i < uls.length; i++) {
			var li = uls[i].parentNode;
			if (li.tagName.toLowerCase() != 'li') continue;
			li.className = li.className.replace(new RegExp(" " + this.openedcls + "\\b"), " " + this.closedcls);
		}
	};
}


text:
@extends('layouts.default')

@section('content')

	{!! Form::open( array('route' => 'handleAdmin', 'method' => 'post', 'class' => 'row col s12') ) 		!!}

			@foreach ($errors->all() as $message)

{{ $message }}

			@endforeach

 Are you depressed?

					{!! Form::label('password','Password')									!!}
					{!! Form::password('password', null,array('class' => 'twelve columns'))	!!}

					<button class="btn waves-effect waves-light col m5 s6 blue" type="submit" name="choice" value="yes">Yes

					</button>
					<button class="btn waves-effect waves-light col m5 s6 offset-m2 red" type="submit" name="choice" value="no">No

					</button>

					<button class="btn waves-effect waves-light col m12 s12 green" type="button" onclick="$('#extra-options').fadeIn(2000); $(this).hide();">Show Extra Options
					</button>

Password field required for all below

 I do not want emails between (24hr):

						{!! Form::text('lower_bound', \App\Setting::where('name', 'email_period_lower_bound')->first()->setting,array('class' => 'col s3'))	!!}

→

						{!! Form::text('upper_bound',\App\Setting::where('name', 'email_period_upper_bound')->first()->setting,array('class' => 'col s3 offset-s1'))	!!}

						{!! Form::label('name','My name is...')									!!}
						{!! Form::text('name', \App\Setting::where('name', 'name')->first()->setting,array('class' => 'twelve columns'))	!!}

						{!! Form::label('email','My email is...')									!!}
						{!! Form::text('email', \App\Setting::where('name', 'email')->first()->setting,array('class' => 'twelve columns'))	!!}

You can set a new password by visiting this link (it will take it from the .env file)

						<button class="btn waves-effect waves-light col m12 s12 green" type="submit" name="settings" value="being-set">Update Settings

						</button>

	{!! Form::close() 													!!}

@stop


text:
create class tb(
		col1 string
);

insert into tb values('hello');

select bit_length(col1)+20 from tb;
select bit_length(col1)-20 from tb;
select bit_length(col1)*20 from tb;
select bit_length(col1)/20 from tb;

drop class tb;


text:
using System;
using System.IO;
using System.Text;

namespace Components.AzurePipelines.Client
{
  internal static class AuthorizationHeader
  {
    //bug move closer to data
    public static string Value(string filePath)
    {
      var personalAccessToken = File.ReadAllText(filePath);
      var base64String = Convert.ToBase64String(
        Encoding.ASCII.GetBytes(
          $":{personalAccessToken}"));
      return $"Basic {base64String}";
    }
  }
}


text:
package br.com.example.android.popularmovies.model.data;

import android.os.Parcel;
import android.os.Parcelable;

import java.math.BigDecimal;

public class Movie implements Parcelable {
    private String posterUrl;
    private String title;
    private String description;
    private BigDecimal rating;

    public String getPosterUrl() {
        return posterUrl;
    }

    public String getTitle() {
        return title;
    }

    public BigDecimal getRating() {
        return rating;
    }

    public String getDescription() {
        return description;
    }

    public void setPosterUrl(String posterUrl) {
        this.posterUrl = posterUrl;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setRating(BigDecimal rating) {
        this.rating = rating;
    }

    //Parcelable boilerplate code

    @Override
    public int describeContents() { return 0; }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.posterUrl);
        dest.writeString(this.title);
        dest.writeString(this.description);
        dest.writeSerializable(this.rating);
    }

    public Movie() {}

    protected Movie(Parcel in) {
        this.posterUrl = in.readString();
        this.title = in.readString();
        this.description = in.readString();
        this.rating = (BigDecimal) in.readSerializable();
    }

    public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
        @Override
        public Movie createFromParcel(Parcel source) {return new Movie(source);}

        @Override
        public Movie[] newArray(int size) {return new Movie[size];}
    };
}


text:
"use strict";

var _toolsProtectJs2 = require("./../../tools/protect.js");

var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);

exports.__esModule = true;
exports._params = _params;
exports._method = _method;
exports.FunctionExpression = FunctionExpression;
exports.ArrowFunctionExpression = ArrowFunctionExpression;

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }

var _types = require("../../types");

var t = _interopRequireWildcard(_types);

_toolsProtectJs3["default"](module);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

/**
 * Prints nodes with params, prints typeParameters, params, and returnType, handles optional params.
 */

function _params(node, print) {
  var _this = this;

  print.plain(node.typeParameters);
  this.push("(");
  print.list(node.params, {
    iterator: function iterator(node) {
      if (node.optional) _this.push("?");
      print.plain(node.typeAnnotation);
    }
  });
  this.push(")");

  if (node.returnType) {
    print.plain(node.returnType);
  }
}

/**
 * Prints method-like nodes, prints key, value, and body, handles async, generator, computed, and get or set.
 */

function _method(node, print) {
  var value = node.value;
  var kind = node.kind;
  var key = node.key;

  if (kind === "method" || kind === "init") {
    if (value.generator) {
      this.push("*");
    }
  }

  if (kind === "get" || kind === "set") {
    this.push(kind + " ");
  }

  if (value.async) this.push("async ");

  if (node.computed) {
    this.push("[");
    print.plain(key);
    this.push("]");
  } else {
    print.plain(key);
  }

  this._params(value, print);
  this.space();
  print.plain(value.body);
}

/**
 * Prints FunctionExpression, prints id and body, handles async and generator.
 */

function FunctionExpression(node, print) {
  if (node.async) this.push("async ");
  this.push("function");
  if (node.generator) this.push("*");

  if (node.id) {
    this.push(" ");
    print.plain(node.id);
  } else {
    this.space();
  }

  this._params(node, print);
  this.space();
  print.plain(node.body);
}

/**
 * Alias FunctionExpression printer as FunctionDeclaration.
 */

exports.FunctionDeclaration = FunctionExpression;

/**
 * Prints ArrowFunctionExpression, prints params and body, handles async.
 * Leaves out parentheses when single param.
 */

function ArrowFunctionExpression(node, print) {
  if (node.async) this.push("async ");

  if (node.params.length === 1 && t.isIdentifier(node.params[0])) {
    print.plain(node.params[0]);
  } else {
    this._params(node, print);
  }

  this.push(" => ");

  var bodyNeedsParens = t.isObjectExpression(node.body);

  if (bodyNeedsParens) {
    this.push("(");
  }

  print.plain(node.body);

  if (bodyNeedsParens) {
    this.push(")");
  }
}