text:
@interface UIColor (SQHex)

+ (UIColor *)sq_colorWithHexString:(NSString *)hexString;

@end

redpajama_set_name: RedPajamaGithub


text:
require 'simplecov'

if ENV['CI']
  require 'coveralls'
  SimpleCov.formatter = Coveralls::SimpleCov::Formatter
end

if ENV['COVERAGE'] || ENV['CI']
  SimpleCov.start('rails') do
    add_filter '/spec'
    add_filter '/.internal_test_app'
    add_filter '/lib/generators'
    add_filter '/lib/geo_works/version.rb'
  end
end

require 'engine_cart'
require 'pry'

ENV['RAILS_ENV'] ||= 'test'
EngineCart.load_application!
Dir['./spec/support/**/*.rb'].sort.each { |f| require f }
require 'rspec/rails'

Capybara.default_driver = :rack_test
Capybara.javascript_driver = :poltergeist
Capybara.default_max_wait_time = ENV['TRAVIS'] ? 30 : 15
# Adding the below to deal with random Capybara-related timeouts in CI.
# Found in this thread: https://github.com/teampoltergeist/poltergeist/issues/375
poltergeist_options = {
  js_errors: true,
  timeout: 30,
  logger: nil,
  phantomjs_logger: StringIO.new,
  phantomjs_options: [
    '--load-images=no',
    '--ignore-ssl-errors=yes'
  ]
}
Capybara.register_driver(:poltergeist) do |app|
  Capybara::Poltergeist::Driver.new(app, poltergeist_options)
end

ActiveJob::Base.queue_adapter = :inline

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
  config.fixture_path = File.expand_path("../fixtures", __FILE__)

  config.include FactoryGirl::Syntax::Methods
  if defined? Devise::Test::ControllerHelpers
    config.include Devise::Test::ControllerHelpers, type: :controller
    config.include Devise::Test::ControllerHelpers, type: :view
  else
    config.include Devise::TestHelpers, type: :controller
    config.include Devise::TestHelpers, type: :view
  end

  config.include TestViewHelpers, type: :view

  config.include(ControllerLevelHelpers, type: :helper)
  config.before(:each, type: :helper) { initialize_controller_helpers(helper) }

  config.include(ControllerLevelHelpers, type: :view)
  config.before(:each, type: :view) { initialize_controller_helpers(view) }

  config.include BackportTest, type: :controller unless Rails.version > '5'
  config.include Controllers::EngineHelpers, type: :controller
  config.include Controllers::EngineHelpers, type: :helper
  config.include ::Rails.application.routes.url_helpers
end


text:
/* eslint no-param-reassign: 0 */
/*
#     CloudBoost - Core Engine that powers Bakend as a Service
#     (c) 2014 HackerBay, Inc.
#     CloudBoost may be freely distributed under the Apache 2 License
*/

const q = require('q');
const winston = require('winston');
const { MongoAdapter } = require('mongo-adapter');
const config = require('../config/config');

module.exports = {

  getAccessList(req) {
    // req is a http request object.

    try {
      const accessList = {};

      if (!req || !req.session) return accessList;
      if (req.session.userId) {
        accessList.userId = req.session.userId;
      }

      if (req.session.roles) {
        accessList.roles = req.session.roles;
      }

      return accessList;
    } catch (err) {
      winston.log('error', {
        error: String(err),
        stack: new Error().stack,
      });
      return null;
    }
  },

  checkWriteAclAndUpdateVersion(appId, documents, accessList, isMasterKey) {
    const deferred = q.defer();

    try {
      const promises = [];
      for (let i = 0; i < documents.length; i++) {
        promises.push(
          this.verifyWriteACLAndUpdateVersion(
            appId, documents[i]._tableName, documents[i], accessList, isMasterKey,
          ),
        );
      }
      q.all(promises).then((docs) => {
        deferred.resolve(docs);
      }, (err) => {
        deferred.reject(err);
      });
    } catch (err) {
      winston.log('error', {
        error: String(err),
        stack: new Error().stack,
      });
      deferred.reject('Unauthorized to modify');
    }
    return deferred.promise;
  },

  checkWriteAcl(appId, document, accessList, isMasterKey) {
    try {
      if (isMasterKey) {
        return true;
      }

      const acl = document.ACL;
      if (acl.write.allow.user.indexOf('all') > -1) {
        return true;
      } if (Object.keys(accessList).length === 0) {
        if (acl.write.allow.user.indexOf('all') > -1) {
          return true;
        } return false;
      }
      if (accessList.userId && acl.write.allow.user.indexOf(accessList.userId) > -1) {
        return true;
      } if (accessList.userId && acl.write.deny.user.indexOf(accessList.userId) > -1) return false;

      for (let i = 0; i < accessList.roles.length; i++) {
        if (acl.write.allow.role.indexOf(accessList.roles[i]) > -1) {
          return true;
        }
      }
      return false;
    } catch (err) {
      winston.log('error', {
        error: String(err),
        stack: new Error().stack,
      });
      return err;
    }
  },

  async verifyWriteACLAndUpdateVersion(
    appId,
    collectionName,
    document,
    accessList,
    isMasterKey,
  ) {
    const [doc] = await MongoAdapter.find({
      client: config.mongoClient,
      appId,
      tableName: collectionName,
      query: {
        _id: document._id,
      },
      accessList,
      isMasterKey,
    });

    if (doc) {
      if (document._version > 0) {
        if (document._version >= doc._version) {
          document._version += 1;
        } else {
          document._version = doc._version + 1;
        }
      } else {
        document._version = doc._version + 1;
      }
      const acl = doc.ACL;
      let status = false; // eslint-disable-line no-unused-vars

      if (isMasterKey) {
        status = true;
      } else if (acl.write.allow.user.indexOf('all') > -1) {
        status = true;
      } else if (Object.keys(accessList).length === 0) {
        if (acl.write.allow.user.indexOf('all') > -1) {
          status = true;
        } else {
          throw false;
        }
      } else if (
        accessList.userId
        && acl.write.allow.user.indexOf(accessList.userId) > -1) {
        status = true;
      } else if (
        accessList.userId
        && acl.write.deny.user.indexOf(accessList.userId) > -1) {
        throw false;
      } else {
        for (let i = 0; i < accessList.roles.length; i++) {
          if (acl.write.allow.role.indexOf(accessList.roles[i]) > -1) {
            status = true;
          }
        }
        throw false;
      }

      const storedKeys = Object.keys(doc);
      const documentKeys = Object.keys(document);
      for (let i = 0; i < storedKeys.length; i++) {
        if (documentKeys.indexOf(storedKeys[i]) === -1) {
          document[storedKeys[i]] = doc[storedKeys[i]];
        }
      }
      const obj = {};
      obj.newDoc = document;
      obj.oldDoc = doc;

      return obj;
    }

    document._version = 0;
    const obj = {};
    obj.newDoc = document;
    obj.oldDoc = null;

    return obj;
  },
};


text:
template node['start_scheduler']['config_file'] do
  source 'component_home_config.erb'
  variables({
    :environmentVariable => 'SCHEDULER_HOME',
    :home => node['start_scheduler']['home']
  })
end

# Create systemd service file.
template node['start_scheduler']['systemd_service'] do
  source 'start_component.service.erb'
  variables({
    :componentName => 'Scheduler',
    :home => node['start_scheduler']['home']
  })
end

# Register component as a service in systemd.
bash 'register_scheduler' do
  user "root"
  code <<-EOH
    if [ systemctl is-enabled #{node['start_scheduler']['systemd_service']} != "*enabled*" ]
    then
      systemctl enable #{node['start_scheduler']['systemd_service']}
    fi
  EOH
end

# Start Scheduler component using systemd.
service "scheduler_start" do
  not_if do ::File.exists?("#{node['dmon']['scheduler']['component_home_directory']}/var/specs_monitoring_nmap_scheduler.pid") end
  provider Chef::Provider::Service::Systemd
  service_name "scheduler"
  action :start
end


text:
import CircleStyle from '../../../../src/ol/style/Circle.js';
import Feature from '../../../../src/ol/Feature.js';
import Fill from '../../../../src/ol/style/Fill.js';
import Map from '../../../../src/ol/Map.js';
import Point from '../../../../src/ol/geom/Point.js';
import Stroke from '../../../../src/ol/style/Stroke.js';
import Style from '../../../../src/ol/style/Style.js';
import Text from '../../../../src/ol/style/Text.js';
import VectorLayer from '../../../../src/ol/layer/Vector.js';
import VectorSource from '../../../../src/ol/source/Vector.js';
import View from '../../../../src/ol/View.js';

const vectorSource = new VectorSource({
  features: [
    // Latin - end (right)
    new Feature({
      geometry: new Point([-10, 50]),
      text: 'Latin',
      textAlign: 'end',
    }),

    // Hebrew - start (right)
    new Feature({
      geometry: new Point([-10, 0]),
      text: 'עִברִית',
      textAlign: 'start',
    }),

    // Arabic - start (right)
    new Feature({
      geometry: new Point([-10, -50]),
      text: 'عربى',
      textAlign: 'start',
    }),

    // Latin - start (left)
    new Feature({
      geometry: new Point([10, 50]),
      text: 'Latin',
      textAlign: 'start',
    }),

    // Hebrew - end (left)
    new Feature({
      geometry: new Point([10, 0]),
      text: 'עִברִית',
      textAlign: 'end',
    }),

    // Arabic - end (left)
    new Feature({
      geometry: new Point([10, -50]),
      text: 'عربى',
      textAlign: 'end',
    }),
  ],
});

new Map({
  pixelRatio: 1,
  layers: [
    new VectorLayer({
      source: vectorSource,
      style: function (feature) {
        return new Style({
          text: new Text({
            text: feature.get('text'),
            font: '24px Ubuntu',
            textAlign: feature.get('textAlign'),
            fill: new Fill({
              color: 'black',
            }),
            stroke: new Stroke({
              color: 'white',
            }),
          }),
          image: new CircleStyle({
            radius: 10,
            fill: new Fill({
              color: 'cyan',
            }),
          }),
        });
      },
    }),
  ],
  target: 'map',
  view: new View({
    center: [0, 0],
    resolution: 1,
  }),
});

render({tolerance: 0.01});


text:
package com.virjar.vscrawler.core.util;

/**
 * Created by virjar on 17/5/2.
 *
 * @author virjar
 * @since 0.0.1
 */
public interface VSCrawlerConstant {
    String SESSION_POOL_MAX_IDLE = "sessionPool.maxIdle";
    String SESSION_POOL_MIN_IDLE = "sessionPool.minIdl";
    String SESSION_POOL_MAX_DURATION = "sessionPool.maxDuration";
    String SESSION_POOL_MAX_OCCURS = "sessionPool.maxOccurs";
    String SESSION_POOL_ACTIVE_USER = "sessionPool.activeUser";
    String SEEION_POOL_USER_KEY = "sessionPool.userKEY";

    String SESSION_POOL_MONTOR_THREAD_NUMBER = "sessionPool.monitorThreadNumber";

    String VSCRAWLER_THREAD_NUMBER = "vsCrawler.%s.threadNumber";

    String USER_RESOURCE_USERINFO = "userResource.%s.userInfo";

    String VSCRAWLER_AVPROXY_KEY = "vsCrawler.avProxy.key";

    String VSCRAWLER_WORKING_DIRECTORY = "vsCrawler.Working.directory";

    String VSCRAWLER_INIT_SEED_FILE = "vsCrawler.%s.initSeedFile";

    String DEFAULT_CRAWLER_NAME = "vsCrawler";

    String VSCRAWLER_SEED_MANAGER_EXPECTED_SEED_NUMBER = "seedManager.expectedSeedNumber";

    Long defaultSessionRequestTimeOut = 2000L;
}


text:
========================
WebUI Page API Reference
========================

The web pages are created (mainly) on the client from a JSON control stucture delivered by the server. This document describes the structure expected by the rendering engine.

Top-Level Structure
===================

This is the root element of any json result::

    %structure = (

        page => { TOP_LEVEL_INFO},

        right => [ PAGE_SECTION, PAGE_SECTION,...] , # optional, information which will be displayed in additional right pane

        main => [ PAGE_SECTION, PAGE_SECTION,...] , # information which will be displayed in the main section

        reloadTree => BOOL (1/0), # optional, the browser will perform a complete reload. If an additional "goto" is set, the page-url will change to this target

        goto => STRING PAGE, # optional, will be evaluated as url-hashtag target

        status => { STATUS_INFO } # optional
    );

    Example { reloadTree => 1, goto => 'login/login'}

Page Head (TOP_LEVEL_INFO):
---------------------------

This is rendered as the page main headline and intro text.
::

    TOP_LEVEL_INFO:
    {
        label => STRING, #Page Header
        description => STRING, # additional text (opt.)
    }

    Example: page => {label => 'OpenXPKI Login', description => 'Please log in!'}

Status Notification (STATUS_INFO):
----------------------------------

Show a status bar on top of the page, the level indicates the severity and results in different colors of the status bar.
::

    STATUS_INFO:
    {
        level => STRING, # allowed values: "info", "success","warn", "error"
        message => STRING # status message shown
    }

    Example:   status => { level => 'error', message => 'Login credentials are wrong!' }

Page Level
==========

The page sections (``main`` and ``right``) can hold multiple subpage definitions. The main section must always contain at least one section while right can be omitted or empty.

Page Section (PAGE_SECTION)
---------------------------

This is the top level container of each page section.
::

    PAGE_SECTION:
    {
        type => STRING # determines type of section, can be one of: text|grid|form|keyvalue

        content => {
            label => STRING # optional, section headline

            description => STRING , # optional, additional text (html is allowed)

            buttons => [BUTTON_DEF, BUTTON_DEF, BUTTON_DEF] , #optional, defines the buttons/links for this section

            # additional content-params depending on type (see below)
        },

        # additional section-params depending on type:
    }

SECTION-TYPE "text"
-------------------

Print the label as subheadline (h2) and description as intro text, buttons are rendered after the text. Does not have any additional parameters. Note: If you omit label and description this can be used to render a plain button bar or even a single button.

SECTION-TYPE "grid"
-------------------

Grids are rendered using the `jquery datatable plugin (http://datatables.net) <http://datatables.net>`_. The grid related parameters are just pushed to the dataTables engine and therefore have a different notation and syntax used as the remainder of the project.
::

    content => {
        label => .., description => .., buttons => ..,
        columns => [ GRID_COL_DEF, GRID_COL_DEF , GRID_COL_DEF... ],
        data => [ GRID_ROW, GRID_ROW, GRID_ROW, ... ],
        actions => [ GRID_ACTION_DEF, GRID_ACTION_DEF, GRID_ACTION_DEF... ], # defines available actions, displayed as context menu
        processing_type => STRING, # only possible value (for now) is "all"
    }

    GRID_COL_DEF:
    {
        sTitle => STRING, # displayed title of that columnd AND unique key
        format => STRING_FORMAT # optional, triggers a formatting helper (see below)
    }

    GRID_ROW:
        ['col1','col2','col3']

    GRID_ACTION_DEF:
    {
        path => STRING_PATH, # will be submitted to server as page. terms enclosed in {brackets} will be evaluated as column-keys and replaced with the value of the given row for that column
        label => STRING, # visible menu entry
        target => STRING_TARGET # optional, where to open the new page, one of main|right|modal|tab
        icon => STRING , # optional, file name of image icon, must be placed in htdocs/img/contextmenu
    }

Columns, whose sTitle begin with an underscore will not be displayed but used as internal information (e.g. as path in GRID_ACTION_DEF). A column with the special title ``_status`` is used as css class for the row. Also a pulldown menu to filter by status will be displayed.
The rows hold the data in form of a positional array.

Action target ``modal`` creates a modal popup, ``tab`` inits or extends a tabbed window view in the current section.

*Example*::

    content => {
        columns => [
        { sTitle => "Serial" },
            { sTitle => "Subject" },
        { sTitle => "date_issued", format => 'timestamp'},
        { sTitle => "link", format => 'link'},
        { sTitle => "_id"}, # internal ID (will not be displayed)
        { sTitle => "_status"}, # row status
        ],
        data => [
            ['0123','CN=John M Miller,DC=My Company,DC=com',1379587708, {page => 'http://../', label => 'Click On Me'}, 'swBdX','issued'],
            ['0456','CN=Bob Builder,DC=My Company,DC=com',1379587517,{...},'qqA2H','expired'],
        ],
        actions => [
            {
                path => 'cert!detail!{_id}',
                label => 'Details',
                icon => 'view',
                target => 'modal'
            },
            {
                path => 'cert!mail2issuer!{email}',
                label => 'Send an email to issuer'
            },
        ]
    }

SECTION-TYPE "form"
-------------------

Render a form to submit data to the server
::

    content => {
        label => .., description => ..,
        buttons => [ ... ], # a form must contain at least one button to be useful
        fields => [ FORM_FIELD_DEF,FORM_FIELD_DEF,FORM_FIELD_DEF ],
    }

    FORM_FIELD_DEF:
    {
        name => STRING # internal key - will be transmitted to server
        value => MIXED, # value of the field, scalar or array (depending on type)
        label => STRING, # displayed label
        type => STRING_FIELD_TYPE, # see below for supported field types
        is_optional => BOOL, # if false (or not given at all) the field is required
        clonable => BOOL,  creates fields that can be added more than once
        visible => BOOL, #if set to "false" ("0" in perl) this field will be not displayed (initial)
        keys => ARRAY ,#optional, activates the special feature of "dynamic key value fields", see below.
        # + additional keys depending for some types
    }

Field-Type "text", "hidden", "password", "textarea"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

No additional parameters, create a simple html form element without any extras.

Field-Type "static"
^^^^^^^^^^^^^^^^^^^

No additional parameters, creates a simple "readonly" text element with the
value treated as a "hidden" form element. If you want to display a formatted
version of the value, you can pass this using the ``verbose`` key.

Field-Type "checkbox/bool"
^^^^^^^^^^^^^^^^^^^^^^^^^^

A html checkbox, ``value`` and ``is_optional`` are without effect, as always 0 or 1 is send to the server.

Field-Type "date"
^^^^^^^^^^^^^^^^^^

A text field with a jquery datapicker attached. Additional (all optional) params are:
::

    FORM_FIELD_DEF:
    {
        notbefore => INTEGER, # optional, unixtime, earliest selectable date
        notafter => INTEGER, # optional, unixtime, earliest selectable date
        return_format => STRING # one of terse|printable|iso8601|epoch, see OpenXPKI::Datetime
    }

Field-Type "select"
^^^^^^^^^^^^^^^^^^^^

A html select element, the options parameter is required, others are optional::

    FORM_FIELD_DEF:
    {
        options => [{value=>'key 1',label=>'Label 1'},{value=>'key 2',label=>'Label 2'},...],
        prompt => STRING # first option shown in the box, no value (soemthing like "please choose")
        editable => BOOL # activates the ComboBox,
        actionOnChange => STRING_ACTION # if the pulldown is changed by the user (or an initial value is given), server will be called with this "action". See "Dynamic form rendering" for details.
    }

The ``options`` parameter can be fetched via an ajax call. If you set ``options => 'fetch_cert_status_options'``, an ajax call to "server_url.cgi?action=fetch_cert_status_options" is made. The call must return the label/value list as defined given above.

Setting the editable flag to a true value enables the users to enter any value into the select box (created with `Bootstrap Combobox <https://github.com/danielfarrell/bootstrap-combobox>`_).

Field-Type "radio"
^^^^^^^^^^^^^^^^^^

The radio type is the little brother of the select field, but renders the items as a list of items using html radio-buttons. It shares the syntax of the ``options`` field with the select element::

    FORM_FIELD_DEF:
    {
        options => [{....}] or 'ajax_action_string'..
        multi => BOOL, # optional, if true, uses checkbox elements instead radio buttons
    }

Field-Type "upload"
^^^^^^^^^^^^^^^^^^^

Renders a field to upload files with some additional benefits::

    FORM_FIELD_DEF:
    {
        mode => STRING, # one of hidden, visible, raw
        allowedFiles => ARRAY OF STRING, # ['txt', 'jpg'],
        textAreaSize => {width => '10', height => '15'},
    }

By default, a file upload button is shown which loads the selected file into a hidden textarea. Binary content is encoded with base64 and prefixed with the word "binary:". With `mode = visible` the textarea is also shown so the user can either upload or paste the data (which is very handy for CSR uploads), the textAreaSize will affect the size of the area field. With ``mode = raw`` the element degrades to a html form upload button and the selected file is send with the form as raw data.

AllowedFiles can contain a list of allowed file extensions.

Dynamic key value fields
^^^^^^^^^^^^^^^^^^^^^^^^
If a field is defined with the property "keys", a pulldown of options is displayed above the actual field. This allows the user to specify, which kind of information he wants to specify.
The content of the actual field will be submitted to the server with the selected key in the key-pulldown.

Example:
    { name => '...', label => 'Dyn Key-Value', 'keys' => [{value=>"key_x",label=>"Typ X"},{value=>"key_y",label=>"Typ Y"}], type => 'text' },

    This example definition will render a Textfield with label "Dyn Key-Value". Above the textfield a select is displayed with three options ("Typ x","Typ y" and "Typ z").
    If the user chooses "Typ Z", the entered value in the textfield will be posted to server with key "key_z".

    This feature makes often more sense in combination with "clonable" fields.

Dynamic form rendering
^^^^^^^^^^^^^^^^^^^^^^
If a select field is defined with the property "actionOnChange", each change event of this pulldown will trigger
an submit of all formvalues (without validity checks etc) to the server with key "action" set to the value of "actionOnChange".

The returned JSON must contain the key "_returnType" which should have the value "partial" or "full".
This "_returnType" defines the mode of re-definition of the content of the form.

**Partial redefinition:**

Beside the key "_returntype" the key "fields"  is expected in the returned JSON-Structure.
"fields" contains an array, which is semantically identic to the key "fields" in the definition of the form.
This array "fields" must contain only only the fields (and properties), which should react to the change of the (master-)field (pulldown) .
The property "name" is required (otherwise the client can not identify the field).
The property "type" can not be subject to changes. With aid of the property "visible" one can dynamically show or hide some fields.
Only known fields (which are already defined in the initial "fields"-property of the form-section) can be subject of the "partial" re-rendering.
Its not possible to add new fields here.

You can define more than one (cascading) dependent select.

*Example*:

Initial definition of fields::

    fields => [
        { name => 'cert_typ', label => 'Typ',value=> 't2', prompt => 'please select a type',  type => 'select', actionOnChange => 'test_dep_select!change_type', options=>[{value=>'t1',label=>'Typ 1'},{value=>'t2',label=>'Typ 2'},{value=>'t3',label=>'Typ 3'}] },
        { name => 'cert_subtyp', label => 'Sub-Type',prompt => 'first select type!', type => 'select',options=>[] },
        { name => 'special', label => 'Spezial (nur Typ 2',  type => 'checkbox',visible => 0 },
    ]

Action "test_dep_select!change_type" returns a (partially updated) definition of fields::

    {
        _returnType => 'partial',
        fields => [
            { name => 'cert_subtyp', options=> [{value=>'x', label => 'Subtyp X'},...],value=>'x'} ,
            { name => 'special',visible=> 1 }
        ]
    };

**Full redefinition:**

Is not implemented yet.

SECTION-TYPE "key-value"
-------------------------

Render a list of key/value items in a two column grid. The left column shows
the text given by "label", the right column is formated based on value and
format (see Formatted Strings).

There is a special format type "head" which renders a table head tag spanning
both columns. If a context item is referenced, the value is used as headline,
it might be decorated using a template. As an alternative, a fixed value can
be given using the key label.

Add an item with format set to spacer to create an empty separator line
(there is a global field names spacer in the default config so you can just
say '- spacer' in the output section).

An option className can be set which is put into the rows tr tag.

Item Level
==========

Buttons (BUTTON_DEF)
--------------------

Defines a button.::

    {
        page => STRING_PAGE,
        action => STRING_ACTION, # parameters "page" and "action" will be transmitted to server. if an "action" is given, POST will be used instead of GET
        label => STRING, # The label of the button
        target => STRING_TARGET, # one of main|modal|right|tab (optional, default is main)
        css_class => STRING, # optional, css class for the button element
        do_submit => BOOL, # optional, if true, the button submits the contents of the form to the given page/action target, only available with form-section
    }

Formattet Strings (STRING_FORMAT)
---------------------------------

Tells the ui to process the data before rendering with a special formatter. Available methods are:

timestamp
^^^^^^^^^

Expects a unix timestamp and outputs a full UTC timestamp.

datetime
^^^^^^^^

Expects a parseable date, outputs a full UTC timestamp.

certstatus
^^^^^^^^^^

Colorizes the given status word using css tags, e.g. ``issued`` becomes::

    issued

link
^^^^

Create an internal framework link to a page or action, expects a hash with ``label`` and ``page`` and optional ``target``, default is to open the link in a modal.

extlink
^^^^^^^

Similar to link but expects href to be an external target, default target is blank.

text
^^^^

Readable text without html markup (will be escaped)

nl2br
^^^^^

Like text with line breaks (\n) converted to "
"

raw
^^^

Displayed as is.

code
^^^^

Rendered with fixed-with typo, unix linebreaks are converted to html linebreaks.

defhash/deflist
^^^^^^^^^^^^^^^

Outputs a key/value list (dl/dt/dd) - defhash expects a hash where keys are
labels. deflist expects an array where each item is a hash with keys key and
value.

ullist
^^^^^^

Array of values, each item becomes a
 in the list, values are html-escaped.

rawlist
^^^^^^^

Like ullist but displays the items "as is" (can contain HTML markup)

linklist
^^^^^^^^

Array, where each item is a hash describing a link

styled
^^^^^^

Expects a value in the format ``stylename:Text to display``. The part left
of the colon is extracted and the text at the right is wrapped with span
with style class "styled-``stylename``. Predefined stylenames are
``valid``, ``failed`` and ``attention``

Customization
=============

The framework allows to register additional components via an exposed api.

Form-Field
-----------

Add a new FormField-Type::

    OXI.FormFieldFactory.registerComponent('type','ComponentName',JS_CODE [,bOverwriteExisting]);

*Example*::

    OXI.FormFieldFactory.registerComponent('select','MySpecialSelect', OXI.FormFieldContainer.extend({
        ....
    }), true);

This will overwrite the handler for the select element. The ComponentName will be registered in the OXI Namespace and can be used to call the object from within userdefined code.

Formatter
---------

Add a new Format-Handler::

    OXI.FormatHelperFactory.registerComponent('format','ComponentName',JS_CODE [,bOverwriteExisting])


text:
var XmlAdapter;
if (typeof window === 'undefined') {
	XmlAdapter = require('./csl_jquery');
} else {
	XmlAdapter = require('./xmldom');
}

module.exports = {
	CSL_NODEJS_JSDOM: XmlAdapter
};


text:
/*
 * framecat: output data from frames, one line per frame
 *
 * This is pretty simplistic; We don't bother checking for whitespace
 * in any of the data
 *
 * format is "source timestamp value"
 *
 * source is represented as k=v[,k=v[,k=v ... ]]
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>

#include "DataFrame.pb-c.h"

#define BUFFER_SIZE	16384

/* Really blunt way to stop invalid data from protobuf-c libraries
 * letting us overrun our buffer.
 */
#define MAX_STRING_LEN	8000

/* Make sure that the strings in the frame are null
 * terminated (at least up to MAX_STRING
 */
int check_frame_bounds(DataFrame *frame){
	int i;
	for (i=0; i<frame->n_source; i++) {
		if (strnlen(frame->source[i]->field, MAX_STRING_LEN) >= MAX_STRING_LEN)
			return 1;
		if (strnlen(frame->source[i]->value, MAX_STRING_LEN) >= MAX_STRING_LEN)
			return 1;
	}

	if (frame->payload == DATA_FRAME__TYPE__TEXT &&
		strnlen(frame->value_textual, MAX_STRING_LEN) >= MAX_STRING_LEN)
		return 1;
	return 0;
}

void dump_frame_source(FILE *fp, DataFrame *frame) {
	int i;
	for (i=0; i < frame->n_source; i++)  {
		fprintf(fp, "%s%s=%s", (i ? "," : ""),
			frame->source[i]->field, frame->source[i]->value );
	}
}

void dump_frame(FILE *fp, DataFrame *frame) {
	dump_frame_source(fp, frame);
	fprintf(fp, " %lu ", frame->timestamp);
	switch (frame->payload) {
		case DATA_FRAME__TYPE__NUMBER:
			fprintf(fp, "%lu\n", frame->value_numeric); break;
		case DATA_FRAME__TYPE__REAL:
			fprintf(fp, "%f\n", frame->value_measurement); break;
		case DATA_FRAME__TYPE__TEXT:
			fprintf(fp, "%s\n", frame->value_textual); break;
		case DATA_FRAME__TYPE__BINARY:
			fprintf(fp, "(BINARY DATA)\n"); break;
		case DATA_FRAME__TYPE__EMPTY:
			fprintf(fp, "(EMPTY)\n"); break;
		default:
			fprintf(fp, "(UNKNOWN PAYLOAD TYPE)\n");
			;;
	}
}

int main(int argc, char **argv) {
	DataFrame *frame;
	uint8_t *buf;
	size_t b;
	FILE *outfp = stdout;

	buf = malloc(BUFFER_SIZE);
	if (buf == NULL) { perror("malloc"); return 1; }

	while (1) {
		/* network ordered uint32_t leads saying how many bytes to read
		 * for the next frame
		 */
		uint32_t prelude;
		b = fread(&prelude, sizeof(prelude), 1, stdin);
		if (b < 1) break;

		prelude = ntohl(prelude);
		if (prelude > BUFSIZ) {
			fprintf(stderr, "header said frame was %u bytes, but our buffer is only %u bytes. Bailing\n",prelude, BUFSIZ);
			return 1;
		}
		b = fread(buf, prelude, 1, stdin);
		if (b < 1) { perror("fread didn't return frame"); return 1;}

		frame = data_frame__unpack(NULL,prelude,buf);
		if (frame == NULL) { perror("data_frame__unpack"); return 1; }

		if (check_frame_bounds(frame)) { perror("frame string overflow"); return 1; }

		dump_frame(outfp, frame);
		data_frame__free_unpacked(frame, NULL);
	}

	free(buf);

	return 0;
}


text:
package com.mojang.metagun.screen;

import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.mojang.metagun.Art;
import com.mojang.metagun.Input;
import com.mojang.metagun.Metagun;
import com.mojang.metagun.Stats;
import com.mojang.metagun.level.Camera;
import com.mojang.metagun.level.Level;

public class GameScreen extends Screen {
	public static final int MAX_HATS = 7;

	private static final boolean DEBUG_MODE = false;
	private int xLevel = DEBUG_MODE ? 8 : 0;
	private int yLevel = DEBUG_MODE ? 4 : 0;

	Level level = new Level(this, 32, 24, xLevel, yLevel, 0, 0);
	private final Camera camera = new Camera(Metagun.GAME_WIDTH, Metagun.GAME_HEIGHT);

	public boolean mayRespawn = false;
	private int gunLevel = DEBUG_MODE ? 2 : 0;
	private int hatCount = 1;

	public GameScreen () {
		Stats.reset();

		level.player.gunLevel = gunLevel;
		level.player.hatCount = hatCount;
	}

	@Override
	public void tick (Input input) {
		Stats.instance.time++;
		if (!input.oldButtons[Input.ESCAPE] && input.buttons[Input.ESCAPE]) {
			setScreen(new PauseScreen(this));
			return;
		}
		if (!level.player.removed)
			level.player.tick(input);
		else if (mayRespawn) {
			if (input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) {
				respawnRoom();
				mayRespawn = false;
			}
		}
		level.tick();
		Stats.instance.hats = level.player.hatCount;
	}

	public void transition (int xa, int ya) {
		Stats.instance.hats = level.player.hatCount;
		xLevel += xa;
		yLevel += ya;
		if (yLevel > 10) {
			setScreen(new WinScreen());
			return;
		}
		level.player.x -= xa * 300;
		level.player.y -= ya * 220;
		hatCount = level.player.hatCount;
		if (ya != 0) level.player.y -= 10;
		Level newLevel = new Level(this, 32, 24, xLevel, yLevel, (int)level.player.x, (int)(level.player.y + ya * 5));
		newLevel.player.remove();
		newLevel.player = level.player;
		newLevel.add(newLevel.player);
		setScreen(new LevelTransitionScreen(this, xLevel - xa, yLevel - ya, level, newLevel, xa, ya));
		this.level = newLevel;
		level.player.gunLevel = gunLevel;
		level.player.hatCount = hatCount;
		level.player.damage = 0;
	}

	@Override
	public void render () {
		spriteBatch.begin();
		draw(Art.bg, 0, 0);
		spriteBatch.end();
		level.render(this, camera);

		spriteBatch.begin();
		if (mayRespawn) {
			String msg = "PRESS X TO TRY AGAIN";
			drawString(msg, 160 - msg.length() * 3, 120 - 3);
		}
		if (Gdx.app.getType() == ApplicationType.Android) {
			draw(Art.buttons[0][0], 0, 240 - 32);
			draw(Art.buttons[1][0], 32, 240 - 32);

			draw(Art.buttons[4][0], 160 - 32, 240 - 32);
			draw(Art.buttons[5][0], 160, 240 - 32);

			draw(Art.buttons[2][0], 320 - 64, 240 - 32);
			draw(Art.buttons[3][0], 320 - 32, 240 - 32);
		}
		spriteBatch.end();
	}

	public void readSign (int id) {
		setScreen(new SignReadScreen(this, id));
	}

	public void respawnRoom () {
		Level newLevel = new Level(this, 32, 24, xLevel, yLevel, level.xSpawn, level.ySpawn);
		this.level = newLevel;
		level.player.gunLevel = gunLevel;
		if (hatCount < 1) hatCount = 1;
		level.player.hatCount = hatCount;
		level.player.damage = 0;
	}

	public void getGun (int level) {
		gunLevel = level;
	}
}


text:
$( document ).ready(function( e ){

});


text:
2.7.1
 * #1075 - overload of `LoggerSinkConfiguration.Wrap()` accepting `LoggingLevelSwitch`
 * #1083 - update package metadata, including `https://` project and icon URLs
 * #1091 - make `{Properties:j}` work consistently with the console sink
 * #1110 - expose an efficient `Logger.None`
 * #1113 - (tooling) improve tests for `LogContext`
 * #1136 - (tooling) fix `build.sh` exit code
 * #1141 - fix logging of `byte[]` smaller than 1 KB
 * #1157 - (tooling) update _.gitignore_
 * #1158 - (tooling) re-enable macOS builds
 * #1163 - SourceLink v2 support
 * #1165 - fix a number of issues with `LoggerSinkConfiguration.Wrap()` affecting `WriteTo.Async()`
 * #1134 - (tooling) add README badges for downloads/stats
 * #1166 - allow `LoggerConfiguration` to be garbage collected after logger is created
 * #1160 - (tooling) update NuGet.org API key
 * (tooling) Update to use the latest .NET SDK

2.6.0
 * #992 - fix `LogContext` remoting issue on .NET Framework 4.5
 * #1007 - `LogContext.Suspend()` and `LogContext.Reset()` to pass or drop context from child tasks
 * #1018 - include source in NUPKGs
 * #1020 - support for `LoggingLevelSwitch` in key-value/`<appSettings>` settings
 * #1033 - warn when `MinimumLevel.Override()` is used in a sub-logger
 * #1034 - more efficient levelled `ILogger.ForContext()`/`Log.ForContext()`
 * #1051 - handle duplicate keys in key-value/`<appSettings>` settings (last-in wins)
 * #1064 - support static member references as key-value/`<appSettings>` values
 * #1059 - support for abstract class parameters in settings
 * #1068 - handle parsing of token width more robustly
 * Plus build/documentation items #988, #994, #996, #1019, #842, #1042, #1050, #1055, #1063.

2.5.0
 * #939, #946, #972 - RTM .NET Standard/Core tooling
 * #955 - `LoggerSinkConfiguration.Wrap()`
 * #944 - `{Properties}` in output templates
 * #961 - fix parser exception when property tokens with zero-length names are encountered
 * #773 - `LogContext.Clone()` and `LogContext.Push(ILogEventEnricher)`
 * #976 - support for logging C# 7 `ValueTuple<>` values
 * #977 - output formatting performance improvements, `{Message:l}` (unquoted string) and `{Message:j}` (JSON structure) support in output templates
 * #981 - reduced allocations required for structured data capturing

Plus multiple build/test/configuration improvements.2.4.0
* #866 and #877- additional event payload limiting controls
* #833 - improve performance of message template cache lookup
* #885 - fix JSON formatting of `NaN` and infinity values
* #888 - allow minimum level overrides to be specified by configuration providers like _Serilog.Settings.AppSettings_
* #903 - add further `Log` static methods to match `ILogger` methods
* #907 - properly dispose audit sinks
* #913 - include commit hash in `AssemblyInformationalVersion`
* #925 - allow configuration providers to specify `filter` directives
* Build and test coverage work in #821, #824, #896.

2.3.0
 * #870 - fix dispose for level-restricted sinks
 * #852 - fix dictionary capturing when key/value are anonymous types
 * #835 - avoid `RemotingException` via `LogContext`
 * #855 -  allow custom enum rendering (better `ICustomFormatter` support
 * #841 - `audit-to` in key-value settings

2.2.1
 * #835 (fix for .NET 4.6+ only)

2.2.0
 * #826 - audit-style logging
 * #819 - deprecate virtual extension points on JsonFormatter

2.1.0
 * #782 - provide `Destructure.ByTransformingWhere()`
 * #779 - capture additional parameters even when template is malformed
 * #798 - fix overload selection in `KeyValueSettings`
 * #815 - allow level to be lowered by overrides, in addition to being raised

2.0.0
 * #535 - .NET Core support; split sinks, enrichers and settings providers into standalone packages; refactor to eliminate _Serilog.FullNetFx.dll_; remove .NET 4.0 support
 * #566 - `Log.CloseAndFlush()`
 * #561 - detect and throw exception if `LoggerConfiguration.CreateLogger()` is called more than once
 * #617 - update project to use C# 6 where appropriate
 * Use `R` round-trip formatting when converting floating point values to JSON
 * #623 - [PeriodicBatchingSink](https://github.com/serilog/serilog-sinks-periodicbatching) - reduce contention when enqueueing events to `PeriodicBatchingSink`
 * #618 - correctly handle VB.NET anonymous types when destructuring
 * #636 - support more enrichment scenarios in `<appSettings>`
 * #588 - enable `LogContext` on all target platforms
 * #654 - improved `WriteTo.Logger()` level and switch handling
 * #656 - [FileSink](https://github.com/serilog/serilog-sinks-file) - support buffered writes in file-based sinks
 * #649 - [ColoredConsoleSink](https://github.com/serilog/serilog-sinks-coloredconsole) - do not print empty properties in colored console output
 * #719 - concrete, `IDisposable` return value from `LoggerConfiguration.CreateLogger()`
 * #727 - remove the unimplementable `IScalarConversionPolicy` interface
 * #728 - allow user-specified destructuring of reflection types
 * #711 and #765 - formatting for short, all-upper/all-lowercase and fixed-width level names in output templates
 * #747 - `ForContext()` performance improvements
 * #752 - zero-allocation generic methods on `ILogger` for up to three args
 * #746 - add `BindMessageTemplate()` and `BindProperty()` to `ILogger`
 * #731 - `SelfLog` API improvements
 * #754 - `MinimumLevel.Override()` per-source level overrides
 * #770 - message template parser optimization
 * #769 - _BenchmarkDotNet_ performance tests for solution
 * #760 - TravisCI build on Mac OS and Linux
 * #772 - included `LogEventPropertyValueVisitor` and `JsonValueFormatter`
 * #776 - message template construction optimization
 * #733 - use `ObjectHandle` to wrap `LogContext` stack on remoting-capable targets; allows cross-`AppDomain` calls without `Suspend()` or `PermitCrossAppDomainCalls`, both removed
 * #781 - allow interface-typed values to be set in `<appSettings>` configuration by specifying an implementation type name

1.5.14
 * #567 - allow literal formatting to be overridden in `JsonFormatter`

1.5.13
 * #579 - fixed `NullReferenceException` in some `RollingFileSink` failure modes
 * #550 - support custom prefixes in `ReadFrom.AppSettings()` configuration
 * #570 - added `Enrich.WithEnvironmentUserName()`
 * #562 - turn logging off when no sinks are configured

1.5.12
 * #538 - mark assemblies as CLS compliant
 * #532 - `WriteTo.Logger()` improvements for sub-pipelines

1.5.11
 * #523 - prevent excessive RAM use when large strings are cached as message templates

1.5.10
 * #514 - provide `OnEmptyBatch()` to allow batching sinks to perform background work

1.5.9
 * #491 - enable `ReadFrom.KeyValuePairs()` in .NET 4.0 build

1.5.8
 * #484 - generic overloads on `Log` to avoid boxing/allocation

1.5.7
 * #456 - support `ReadFrom.AppSettings()` and friends on .NET 4.0

1.5.6
 * Builds on `master` now derive their version from `CHANGES.md` (rather than vice-versa)
 * #441 - Fix conversion of `Nullable<>` settings

1.5.5
 * #433 - Revert the default destructuring depth back to 10

1.5.1
 * #402 - `<appSettings>` configuration support now in the Serilog package

1.4.214
 * #344 - Moved "Extras" including Web, Owin, F#, destructuring to new organizations

1.4.204
 * #344 (partial) - Moved remaining sinks to individual repositories

1.4.196
 * #393 - Removed the Splunk sink for move to https://github.com/serilog/serilog-sinks-splunk
 * #389 - Fixed the default URI in the ES sink
 * #385 - Provided `IndexDecider` option to ES sink configuration

1.4.182
 * #382 - Fixed `CounterMeasure` counting in _Serilog.Extras.Timing_
 * #386 - Expand environment variables on _Serilog.Extras.AppSettings_ values
 * #387 - Elmah.io sink dependency version updated

1.4.168
 * #376 - Fixed flushing of async events to Loggly sink (moved to serilog/serilog-sinks-loggly)
 * #374 - Run destructuring policies before converting `IEnumerable` types

1.4.152
 * #196 - `LogContext.PermitCrossAppDomainCalls` property to prevent serialization exceptions in test frameworks and when .NET remoting is used
 * #365 - _Serilog.Sinks.ApplicationInsights_ now targets the new Azure Portal-based version (preview)
 * #367 - _Serilog.Sinks.MongoDB_ now targets the new preview driver (preview)
 * #369 - Fixed log message property in .NET 4.0 build of Elasticsearch sink
 * #373 - Update the _Raygun_ sink from 2.0.4 to 4.2.0
 * #344 - Moved the _MongoDB_ and _Application Insights_ sinks out to independent repositories

1.4.139
 * #125 - Merged _MonoTouch_ and _MonoAndroid_ sinks (**not currently published  to NuGet**)
 * #362 - Update Loggly sink package dependencies
 * #203 - _Azure Document DB_ sink

1.4.126
 * #354 - Added _Serilog.Extras.FSharp_

1.4.118
 * #351 - Azure Event Hubs sink

1.4.113
 * #329 - Write event properties as columns using the new `WriteTo.AzureTableStorageWithProperties()`
 * #346 - Pass all properties through to _Serilog.Sinks.NLog_ as context properties
 * #347 - Update _Serilog.Sinks.SignalR_ to SignalR version 2.1.0 (breaking)

1.4.99
 * #342 - Accept `ILogEventEnricher` rather than just `PropertyEnricher` to `ForContext`
 * #341 - Selectable logging level for request details in _Serilog.Extras.Web_

1.4.92
 * #340 - Accept an `Encoding` parameter on the file sinks
 * #336 - Use stream when writing to Splunk via HTTP
 * #335 - Remove use of `dynamic` when destructuring `Nullable<T>` (iOS)

1.4.65
 * #321 - Revert ES sink message property name to original value
 * #324 - Calculate ES index name from UTC timestamp
 * #315 - Remove Logentries SSL cert pinning (the cert changed)
 * #327 - Hide obsolete ES configuration methods
 * #311 - Accept multiple recipient addresses in the email sink

1.4.39
 * #289 - Elasticsearch sink improvements and new virtual methods on `JsonFormatter`

1.4.33
 * #302 - If a the last batch of log events sent by `PeriodicBatchingSink` was not full, wait the `period`
 * #304 - Make sure IO exceptions are suppressed by the `WriteTo.File()` configuration method

1.4.28
 * #303 - `AssemblyInformationalVersion` needs to track the package, not assembly, version, in order to play nicely with MSI

1.4.27
 * #283 - New solution targeting ASP.NET v.NEXT (when final, we'll refactor to give this first-class support)
 * #301 - _Serilog.Extras.Web_ improvements

1.4.23
 * Fixed some more NuGet packaging issues (_Serilog.Sinks.Splunk_ this time)

1.4.22
 * #297 - Update _loggly-csharp_ package dependency

1.4.21
 * Fixed some NuGet packaging issues (including a return to dependency groups for _Serilog.Sinks.Seq_)

1.4.18
1.4.17
1.4.16
 * New CI server used
 * #227 - Reduced default maximum destructuring depth and added configuration option
 * #245 - XML content escaping fixed in MSSQL sink
 * #272 - Allow underscores in property names

1.4.15
 * #259 - Update _loggly-sharp_ dependency (breaking change for _Serilog.Sinks.Loggly_, see PR for instructions)
 * #257 - Added _Serilog.Sinks.XSockets_
 * #246 - Changed target from _Profile78_ to (compatible but broader) _Profile259_
 * #250 - Allow an existing `MongoDatabase` instance to be used when configuring Mongo sink

1.4.14
 * #253 - Added `MessageTemplateFormatMethodAttribute`

1.4.13
 * #244 - Improvements to ElasticSearch sink, switch to just ElasticSearch.NET
 * #254 - Fix ElasticSearch dependency version
 * #249 - Track message template token indexes in parser to support tooling (binary-breaking)

1.4.12
 * #240 - Update TopShelf dependency
 * #243 - Caching in `AttributedDestructuringPolicy` closes over first seen object of a type rather than using the passed parameter
 * #242 - Update NLogSink to map `Verbose` level to `Trace` level in NLog
 * #229 - Created net40 version of Extras Topshelf
 * #236 - Ensure dictionary keys are quoted in JSON even when they're numeric
 * #237 - When `JsonFormatter` formats a dictionary of `<int, object>`, the key should be double quoted
 * #235 - Fixed serialization of dictionary keys in ES and similar sinks

1.4.11
 * #238 - Dynamic level switching

1.4.10
 * #225 - Ensure Azure Tablestorage rowkey is unique
 * #224 - Use UTC to generate partitionkey
 * #219 - .NET 4.0 support for Elastic Search
 * #221 - Exponential back-off for PeriodicBatchingSink

1.4.9
 * #213 - Check for null User.Identity when enriching events with usernames in ASP.NET
 * #216 - Updated to use Splunk TCP Writer

1.4.8
 * #204 - Basic HTTP authentication support for the CouchDB sink
 * #207 - Fixed typo in `DepthLimiter` error message
 * #209 - Update _Serilog.Sinks.Splunk_ to Splunk SDK 2.0 GA
 * #210 - Fixed string formatting in `PropertyBinder` error message

1.4.7
 * #192 - Additional enrichers for _Serilog.Extras.Web_
 * #202 - Batching mode for _Serilog.Sinks.AzureTableStorage_

1.4.6
 * Reintroduced fix from https://github.com/continuousit/seq-client/pull/19 dropped in project move

1.4.5
 * #179 - _Serilog.Sinks.Splunk_ updated for the Splunk SDK 2.0

1.4.4
  * Includes the _Serilog.Sinks.Seq_ sink, to write to the http://getseq.net event server

1.4.3
  * #169 - Added the _Serilog.Extras.DestructureByIgnoring_ package

1.4.2
  * #197 - Allow `EventSource` creation to be skipped when the source does not exist

1.4.1
  * #196 - Introduce `LogContext.Suspend()` to clear `LogicalCallContext` for cross-domain calls


text:
+++
Description = ""
date = "2016-05-16T12:00:00+00:00"
title = "Debug walkthrough"
parent = "/docs/debug-v0.3/"
prev = "/docs/debug-v0.3/osdsoftware/"
next = "/docs/debug-v0.3/simulation/"
showdisqus = true

+++

In this main part of this tutorial you will learn about the debug
features we have added to lowRISC. After introducing the
[debug enumeration and the general software usage with the RTL simulation]({{<
ref "simulation.md" >}}), we will introduce the different features in
[example debug sessions]({{< ref "debugsession.md" >}}). Finally, a
full [FPGA example]({{< ref "docs/debug-v0.3/fpga.md" >}}) is given based on the Nexys
4 board.


text:
Object *interpret(Interpreter *interpreter, Program *program);

Object *interpret_program(Interpreter *interpreter, Program *program);

Object *interpret_form(Interpreter *interpreter, Form *form);

Object *interpret_definition(Interpreter *interpreter, Definition *definition);

Object *interpret_vardef(Interpreter *interpreter, VarDefinition *vardef);

Object *interpret_expression(Interpreter *interpreter, Expression *expression);

Object *interpret_expression_list(Interpreter *interpreter, List *expressions);

Object *interpret_lambda(Interpreter *interpreter, Lambda *lambda);

Object *interpret_if(Interpreter *interpreter, If *ifExpr);

Object *interpret_let(Interpreter *interpreter, Let *let);

Object *interpret_let_binding(Interpreter *interpreter, LetBinding *letBinding);

Object *interpret_application(Interpreter *interpreter, Application *application);

Object *interpret_call_lambda(Interpreter *interpreter, LambdaObject *lambda, List *args);

Object *interpret_call_c_function(Interpreter *interpreter, c_func func, List *args);

Object *interpret_number(Interpreter *interpreter, Number *number);

Object *interpret_boolean(Interpreter *interpreter, Boolean *boolean);

Object *interpret_string(Interpreter *interpreter, String *string);

#endif


text:
package datafu.hourglass.fs;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.avro.Schema;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumReader;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.log4j.Logger;

/**
 * A collection of utility methods for dealing with files and paths.
 *
 */
public class PathUtils
{
  private static Logger _log = Logger.getLogger(PathUtils.class);

  public final static TimeZone timeZone = TimeZone.getTimeZone("UTC");
  public static final SimpleDateFormat datedPathFormat = new SimpleDateFormat("yyyyMMdd");
  public static final SimpleDateFormat nestedDatedPathFormat = new SimpleDateFormat("yyyy/MM/dd");
  private static final Pattern timestampPathPattern = Pattern.compile(".+/(\\d{8})");
  private static final Pattern dailyPathPattern = Pattern.compile("(.+)/(\\d{4}/\\d{2}/\\d{2})");

  /**
   * Filters out paths starting with "." and "_".
   */
  public static final PathFilter nonHiddenPathFilter = new PathFilter() {
    @Override
    public boolean accept(Path path)
    {
      String s = path.getName();
      return !s.startsWith(".") && !s.startsWith("_");
    }
  };

  static
  {
    datedPathFormat.setTimeZone(timeZone);
    nestedDatedPathFormat.setTimeZone(timeZone);
  }

  /**
   * Delete all but the last N days of paths matching the "yyyyMMdd" format.
   *
   * @param fs the filesystem
   * @param path path to delete file from
   * @param retentionCount how many days to keep
   * @throws IOException IOException
   */
  public static void keepLatestDatedPaths(FileSystem fs, Path path, int retentionCount) throws IOException
  {
    LinkedList<DatePath> outputs = new LinkedList<DatePath>(PathUtils.findDatedPaths(fs, path));

    while (outputs.size() > retentionCount)
    {
      DatePath toDelete = outputs.removeFirst();
      _log.info(String.format("Removing %s",toDelete.getPath()));
      fs.delete(toDelete.getPath(),true);
    }
  }

  /**
   * Delete all but the last N days of paths matching the "yyyy/MM/dd" format.
   *
   * @param fs the filesystem
   * @param path path to delete files from
   * @param retentionCount how many days to keep
   * @throws IOException IOException
   */
  public static void keepLatestNestedDatedPaths(FileSystem fs, Path path, int retentionCount) throws IOException
  {
    List<DatePath> outputPaths = PathUtils.findNestedDatedPaths(fs, path);

    if (outputPaths.size() > retentionCount)
    {
      Collections.sort(outputPaths);
      _log.info(String.format("Applying retention range policy"));
      for (DatePath output : outputPaths.subList(0, outputPaths.size() - retentionCount))
      {
        _log.info(String.format("Removing %s because it is outside retention range",output.getPath()));
        fs.delete(output.getPath(),true);
      }
    }
  }

  /**
   * List all paths matching the "yyyy/MM/dd" format under a given path.
   *
   * @param fs file system
   * @param input path to search under
   * @return paths paths matching pattern
   * @throws IOException IOException
   */
  public static List<DatePath> findNestedDatedPaths(FileSystem fs, Path input) throws IOException
  {
    List<DatePath> inputDates = new ArrayList<DatePath>();

    FileStatus[] pathsStatus = fs.globStatus(new Path(input,"*/*/*"), nonHiddenPathFilter);

    if (pathsStatus == null)
    {
      return inputDates;
    }

    for (FileStatus pathStatus : pathsStatus)
    {
      Matcher matcher = dailyPathPattern.matcher(pathStatus.getPath().toString());
      if (matcher.matches())
      {
        String datePath = matcher.group(2);
        Date date;
        try
        {
          date = nestedDatedPathFormat.parse(datePath);
        }
        catch (ParseException e)
        {
          continue;
        }

        Calendar cal = Calendar.getInstance(timeZone);

        cal.setTimeInMillis(date.getTime());

        inputDates.add(new DatePath(cal.getTime(), pathStatus.getPath()));
      }
    }

    return inputDates;
  }

  /**
   * List all paths matching the "yyyyMMdd" format under a given path.
   *
   * @param fs file system
   * @param path path to search under
   * @return paths paths matching pattern
   * @throws IOException IOException
   */
  public static List<DatePath> findDatedPaths(FileSystem fs, Path path) throws IOException
  {
    FileStatus[] outputPaths = fs.globStatus(new Path(path, "*"), nonHiddenPathFilter);

    List<DatePath> outputs = new ArrayList<DatePath>();

    if (outputPaths != null)
    {
      for (FileStatus outputPath : outputPaths)
      {
        Date date;
        try
        {
          date = datedPathFormat.parse(outputPath.getPath().getName());
        }
        catch (ParseException e)
        {
          continue;
        }

        outputs.add(new DatePath(date,outputPath.getPath()));
      }
    }

    Collections.sort(outputs);

    return outputs;
  }

  /**
   * Gets the schema from a given Avro data file.
   *
   * @param fs the filesystem
   * @param path path to get schema from
   * @return The schema read from the data file's metadata.
   * @throws IOException IOException
   */
  public static Schema getSchemaFromFile(FileSystem fs, Path path) throws IOException
  {
    FSDataInputStream dataInputStream = fs.open(path);
    DatumReader <GenericRecord> reader = new GenericDatumReader<GenericRecord>();
    DataFileStream<GenericRecord> dataFileStream = new DataFileStream<GenericRecord>(dataInputStream, reader);
    try
    {
      return dataFileStream.getSchema();
    }
    finally
    {
      dataFileStream.close();
    }
  }

  /**
   * Gets the schema for the first Avro file under the given path.
   *
   * @param fs the filesystem
   * @param path path to fetch schema for
   * @return Avro schema
   * @throws IOException IOException
   */
  public static Schema getSchemaFromPath(FileSystem fs, Path path) throws IOException
  {
    return getSchemaFromFile(fs,fs.listStatus(path, nonHiddenPathFilter)[0].getPath());
  }

  /**
   * Sums the size of all files listed under a given path.
   *
   * @param fs file system
   * @param path path to count bytes for
   * @return total bytes under path
   * @throws IOException IOException
   */
  public static long countBytes(FileSystem fs, Path path) throws IOException
  {
    FileStatus[] files = fs.listStatus(path, nonHiddenPathFilter);
    long totalForPath = 0L;
    for (FileStatus file : files)
    {
      totalForPath += file.getLen();
    }
    return totalForPath;
  }

  /**
   * Gets the date for a path in the "yyyyMMdd" format.
   *
   * @param path path to check
   * @return date for path
   */
  public static Date getDateForDatedPath(Path path)
  {
    Matcher matcher = timestampPathPattern.matcher(path.toString());

    if (!matcher.matches())
    {
      throw new RuntimeException("Unexpected input filename: " + path);
    }

    try
    {
      return PathUtils.datedPathFormat.parse(matcher.group(1));
    }
    catch (ParseException e)
    {
      throw new RuntimeException("Unexpected input filename: " + path);
    }
  }

  /**
   * Gets the date for a path in the "yyyy/MM/dd" format.
   *
   * @param path path to check
   * @return date
   */
  public static Date getDateForNestedDatedPath(Path path)
  {
    Matcher matcher = dailyPathPattern.matcher(path.toString());

    if (!matcher.matches())
    {
      throw new RuntimeException("Unexpected input filename: " + path);
    }

    try
    {
      return PathUtils.nestedDatedPathFormat.parse(matcher.group(2));
    }
    catch (ParseException e)
    {
      throw new RuntimeException("Unexpected input filename: " + path);
    }
  }

  /**
   * Gets the root path for a path in the "yyyy/MM/dd" format.  This is part of the path preceding the
   * "yyyy/MM/dd" portion.
   *
   * @param path in "yyyy/MM/dd" format
   * @return root of input path
   */
  public static Path getNestedPathRoot(Path path)
  {
    Matcher matcher = dailyPathPattern.matcher(path.toString());

    if (!matcher.matches())
    {
      throw new RuntimeException("Unexpected input filename: " + path);
    }

    return new Path(matcher.group(1));
  }
}


text:
/**
 * Given a reducer, returns a reducer which manages a keyed object of that value. Useful for usersById etc...
 * @param {bool} stripUndefinedItems Whenever to automatically remove undefined items from the collection.
 */
export default function (stripUndefinedItems = true){
    return reducer =>
        (state = {}, action) => {
            var newState = {};
            Object.keys(state).forEach(key => {
                var value = reducer(state[key], action);
                if((stripUndefinedItems && value != undefined) || !stripUndefinedItems){
                    newState[key] = value;
                }
            });
            return newState;
        };
}


text:
//
// Copyright 2014 Dropbox, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#import <Foundation/Foundation.h>

#include <memory>

/*
 * Helper class for DbxObjcWrapperCache to store C++ weak_ptr in Objective-C NSMapTable.
 */

@interface DBWeakPtrWrapper : NSObject

@property (nonatomic, readonly) std::weak_ptr<void> ptr;

- (id)initWithWeakPtr:(std::weak_ptr<void>)ptr;

@end


text:
.class public interface abstract Lcom/android/settingslib/users/AppRestrictionsHelper$OnDisableUiForPackageListener;
.super Ljava/lang/Object;
.source "AppRestrictionsHelper.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/settingslib/users/AppRestrictionsHelper;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "OnDisableUiForPackageListener"
.end annotation

# virtual methods
.method public abstract onDisableUiForPackage(Ljava/lang/String;)V
.end method


text:
using testing::_;
using testing::AnyNumber;
using testing::Invoke;
using testing::Return;

namespace blink {
namespace scheduler {

namespace {
void AppendToVectorTestTask(std::vector<std::string>* vector,
                            std::string value) {
  vector->push_back(value);
}

void AppendToVectorReentrantTask(base::SingleThreadTaskRunner* task_runner,
                                 std::vector<int>* vector,
                                 int* reentrant_count,
                                 int max_reentrant_count) {
  vector->push_back((*reentrant_count)++);
  if (*reentrant_count < max_reentrant_count) {
    task_runner->PostTask(
        FROM_HERE,
        base::Bind(AppendToVectorReentrantTask, base::Unretained(task_runner),
                   vector, reentrant_count, max_reentrant_count));
  }
}

};  // namespace

class SchedulerHelperTest : public testing::Test {
 public:
  SchedulerHelperTest()
      : clock_(new base::SimpleTestTickClock()),
        mock_task_runner_(new cc::OrderedSimpleTaskRunner(clock_.get(), false)),
        main_task_runner_(SchedulerTqmDelegateForTest::Create(
            mock_task_runner_,
            base::WrapUnique(new TestTimeSource(clock_.get())))),
        scheduler_helper_(new SchedulerHelper(
            main_task_runner_,
            "test.scheduler",
            TRACE_DISABLED_BY_DEFAULT("test.scheduler"),
            TRACE_DISABLED_BY_DEFAULT("test.scheduler.dbg"))),
        default_task_runner_(scheduler_helper_->DefaultTaskRunner()) {
    clock_->Advance(base::TimeDelta::FromMicroseconds(5000));
  }

  ~SchedulerHelperTest() override {}

  void TearDown() override {
    // Check that all tests stop posting tasks.
    mock_task_runner_->SetAutoAdvanceNowToPendingTasks(true);
    while (mock_task_runner_->RunUntilIdle()) {
    }
  }

  void RunUntilIdle() { mock_task_runner_->RunUntilIdle(); }

  template <typename E>
  static void CallForEachEnumValue(E first,
                                   E last,
                                   const char* (*function)(E)) {
    for (E val = first; val < last;
         val = static_cast<E>(static_cast<int>(val) + 1)) {
      (*function)(val);
    }
  }

 protected:
  std::unique_ptr<base::SimpleTestTickClock> clock_;
  scoped_refptr<cc::OrderedSimpleTaskRunner> mock_task_runner_;

  scoped_refptr<SchedulerTqmDelegateForTest> main_task_runner_;
  std::unique_ptr<SchedulerHelper> scheduler_helper_;
  scoped_refptr<base::SingleThreadTaskRunner> default_task_runner_;

  DISALLOW_COPY_AND_ASSIGN(SchedulerHelperTest);
};

TEST_F(SchedulerHelperTest, TestPostDefaultTask) {
  std::vector<std::string> run_order;
  default_task_runner_->PostTask(
      FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D1"));
  default_task_runner_->PostTask(
      FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D2"));
  default_task_runner_->PostTask(
      FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D3"));
  default_task_runner_->PostTask(
      FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D4"));

  RunUntilIdle();
  EXPECT_THAT(run_order,
              testing::ElementsAre(std::string("D1"), std::string("D2"),
                                   std::string("D3"), std::string("D4")));
}

TEST_F(SchedulerHelperTest, TestRentrantTask) {
  int count = 0;
  std::vector<int> run_order;
  default_task_runner_->PostTask(
      FROM_HERE, base::Bind(AppendToVectorReentrantTask,
                            base::RetainedRef(default_task_runner_), &run_order,
                            &count, 5));
  RunUntilIdle();

  EXPECT_THAT(run_order, testing::ElementsAre(0, 1, 2, 3, 4));
}

TEST_F(SchedulerHelperTest, IsShutdown) {
  EXPECT_FALSE(scheduler_helper_->IsShutdown());

  scheduler_helper_->Shutdown();
  EXPECT_TRUE(scheduler_helper_->IsShutdown());
}

TEST_F(SchedulerHelperTest, DefaultTaskRunnerRegistration) {
  EXPECT_EQ(main_task_runner_->default_task_runner(),
            scheduler_helper_->DefaultTaskRunner());
  scheduler_helper_->Shutdown();
  EXPECT_EQ(nullptr, main_task_runner_->default_task_runner());
}

TEST_F(SchedulerHelperTest, GetNumberOfPendingTasks) {
  std::vector<std::string> run_order;
  scheduler_helper_->DefaultTaskRunner()->PostTask(
      FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D1"));
  scheduler_helper_->DefaultTaskRunner()->PostTask(
      FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D2"));
  scheduler_helper_->ControlTaskRunner()->PostTask(
      FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "C1"));
  EXPECT_EQ(3U, scheduler_helper_->GetNumberOfPendingTasks());
  RunUntilIdle();
  EXPECT_EQ(0U, scheduler_helper_->GetNumberOfPendingTasks());
}

namespace {
class MockTaskObserver : public base::MessageLoop::TaskObserver {
 public:
  MOCK_METHOD1(DidProcessTask, void(const base::PendingTask& task));
  MOCK_METHOD1(WillProcessTask, void(const base::PendingTask& task));
};

void NopTask() {}
}  // namespace

TEST_F(SchedulerHelperTest, ObserversNotifiedFor_DefaultTaskRunner) {
  MockTaskObserver observer;
  scheduler_helper_->AddTaskObserver(&observer);

  scheduler_helper_->DefaultTaskRunner()->PostTask(FROM_HERE,
                                                   base::Bind(&NopTask));

  EXPECT_CALL(observer, WillProcessTask(_)).Times(1);
  EXPECT_CALL(observer, DidProcessTask(_)).Times(1);
  RunUntilIdle();
}

TEST_F(SchedulerHelperTest, ObserversNotNotifiedFor_ControlTaskRunner) {
  MockTaskObserver observer;
  scheduler_helper_->AddTaskObserver(&observer);

  scheduler_helper_->ControlTaskRunner()->PostTask(FROM_HERE,
                                                   base::Bind(&NopTask));

  EXPECT_CALL(observer, WillProcessTask(_)).Times(0);
  EXPECT_CALL(observer, DidProcessTask(_)).Times(0);
  RunUntilIdle();
}

namespace {

class MockObserver : public SchedulerHelper::Observer {
 public:
  MOCK_METHOD1(OnUnregisterTaskQueue,
               void(const scoped_refptr<TaskQueue>& queue));
  MOCK_METHOD2(OnTriedToExecuteBlockedTask,
               void(const TaskQueue& queue, const base::PendingTask& task));
};

}  // namespace

TEST_F(SchedulerHelperTest, OnUnregisterTaskQueue) {
  MockObserver observer;
  scheduler_helper_->SetObserver(&observer);

  scoped_refptr<TaskQueue> task_queue = scheduler_helper_->NewTaskQueue(
      TaskQueue::Spec(TaskQueue::QueueType::TEST));

  EXPECT_CALL(observer, OnUnregisterTaskQueue(_)).Times(1);
  task_queue->UnregisterTaskQueue();

  scheduler_helper_->SetObserver(nullptr);
}

TEST_F(SchedulerHelperTest, OnTriedToExecuteBlockedTask) {
  MockObserver observer;
  scheduler_helper_->SetObserver(&observer);

  scoped_refptr<TaskQueue> task_queue = scheduler_helper_->NewTaskQueue(
      TaskQueue::Spec(TaskQueue::QueueType::TEST)
          .SetShouldReportWhenExecutionBlocked(true));
  task_queue->SetQueueEnabled(false);
  task_queue->PostTask(FROM_HERE, base::Bind(&NopTask));

  // Trick |task_queue| into posting a DoWork. By default PostTask with a
  // disabled queue won't post a DoWork until we enable the queue.
  task_queue->SetQueueEnabled(true);
  task_queue->SetQueueEnabled(false);

  EXPECT_CALL(observer, OnTriedToExecuteBlockedTask(_, _)).Times(1);
  RunUntilIdle();

  scheduler_helper_->SetObserver(nullptr);
}

}  // namespace scheduler
}  // namespace blink


text:
Gather metrics from your [Vespa][1] system in real time to:

- Visualize and monitor Vespa state and performance
- Alert on health and availability

## Setup

The Vespa check is not included in the [Datadog Agent][2] package, so you need to install it.

### Installation

For Agent v7.21+ / v6.21+, follow the instructions below to install the Vespa check on your host. See [Use Community Integrations][3] to install with the Docker Agent or earlier versions of the Agent.

1. Run the following command to install the Agent integration:

   ```shell
   datadog-agent integration install -t datadog-vespa==<INTEGRATION_VERSION>
   ```

2. Configure your integration similar to core [integrations][4].

### Configuration

To configure the Vespa check:

1. Create a `vespa.d/` folder in the `conf.d/` folder at the root of your [Agent's configuration directory][8].
2. Create a `conf.yaml` file in the `vespa.d/` folder previously created.
3. See the [sample vespa.d/conf.yaml][10] file and copy its content in the `conf.yaml` file.
4. Edit the `conf.yaml` file to configure the `consumer`, which decides the set of metrics forwarded by the check:
   - `consumer`: The consumer to collect metrics for, either `default` or a [custom consumer][9]
     from your Vespa application's services.xml.
5. [Restart the Agent][5].

### Validation

Run the [Agent's status subcommand][6] and look for `vespa` under the Checks section.

## Data Collected

### Metrics

See [metadata.csv][7] for a list of metrics provided by this check.

### Events

The Vespa integration does not include any events.

### Service Checks

See [service_checks.json][12] for a list of service checks provided by this integration.

## Troubleshooting

Need help? Contact [Datadog support][13].

[1]: https://vespa.ai/
[2]: https://app.datadoghq.com/account/settings#agent
[3]: https://docs.datadoghq.com/agent/guide/use-community-integrations/
[4]: https://docs.datadoghq.com/getting_started/integrations/
[5]: https://docs.datadoghq.com/agent/guide/agent-commands/#start-stop-and-restart-the-agent
[6]: https://docs.datadoghq.com/agent/guide/agent-commands/#agent-status-and-information
[7]: https://github.com/DataDog/integrations-extras/blob/master/vespa/metadata.csv
[8]: https://docs.datadoghq.com/agent/guide/agent-configuration-files/#agent-configuration-directory
[9]: https://docs.vespa.ai/documentation/reference/services-admin.html#metrics
[10]: https://github.com/DataDog/integrations-extras/blob/master/vespa/datadog_checks/vespa/data/conf.yaml.example
[12]: https://github.com/DataDog/integrations-extras/blob/master/vespa/assets/service_checks.json
[13]: https://docs.datadoghq.com/help/


text:
![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/openscholar/openscholar/PublicLastTestDate.svg)
![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/openscholar/openscholar/PublicDeployment.svg)

![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/openscholar/openscholar/FairfaxLastTestDate.svg)
![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/openscholar/openscholar/FairfaxDeployment.svg)

![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/openscholar/openscholar/BestPracticeResult.svg)
![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/openscholar/openscholar/CredScanResult.svg)

[![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fapplication-workloads%2Fopenscholar%2Fopenscholar%2Fazuredeploy.json)
[![Deploy To Azure US Gov](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazuregov.svg?sanitize=true)](https://portal.azure.us/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fapplication-workloads%2Fopenscholar%2Fopenscholar%2Fazuredeploy.json)
[![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fapplication-workloads%2Fopenscholar%2Fopenscholar%2Fazuredeploy.json)

## OpenScholar template

This template deploys a OpenScholar to the ubuntu VM 16.04
* Deploys on a Ubuntu VM 16.04
* The template installs Drupal and MySQL

### Deployment steps

You can click the "deploy to Azure" button at the beginning of this document.

### Parameters to provide while deploying

+ **adminVMUsername**: Provide admin VM username
+ **adminVMPassword**: Provide admin VM password
+ **databaseName**: Provide database name for openscholar
+ **mysqlPassword**: Provide SMTP email for mail configuration

### Configuration of Openscholar

* Once the script is run, we need to install the drupal from the domain we have created.
* Access the domain that is created.
* It will redirect you to domainname.com/install.php link
* It checks if the requirements are met, if yes it takes to database configuration
* Provide the database name which you have send as second parameter, mysql user is "root" and password the one you have send as first parameter.
* Go to the next step of configuring site, where you provide the site information, Name of the site, admin username and password
* Next option is to choose an environment. There are two environments production deployment and development. Choose Production deployment
* Next is Installation type - Please choose multi-tenant install. It will install the supplement modules which are required
* Once it is done, we can visit the admin section also the front end section.
* To change the admin theme, please go to domainname.com/admin/appearance and you can change the administration theme.

### How to access the OpenScholar Site
* You can access the site using the domain/host name you provide as the paramater while deploying the template.


text:
package io.datarouter.client.memcached;

import javax.inject.Inject;
import javax.inject.Singleton;

import io.datarouter.client.memcached.client.MemcachedClientManager;
import io.datarouter.client.memcached.client.MemcachedClientNodeFactory;
import io.datarouter.client.memcached.web.MemcachedWebInspector;
import io.datarouter.storage.client.ClientType;
import io.datarouter.web.browse.DatarouterClientWebInspectorRegistry;

@Singleton
public class MemcachedClientType implements ClientType<MemcachedClientNodeFactory,MemcachedClientManager>{

	public static final String NAME = "memcached";

	@Inject
	public MemcachedClientType(DatarouterClientWebInspectorRegistry datarouterClientWebInspectorRegistry){
		datarouterClientWebInspectorRegistry.register(NAME, MemcachedWebInspector.class);
	}

	@Override
	public String getName(){
		return NAME;
	}

	@Override
	public Class<MemcachedClientNodeFactory> getClientNodeFactoryClass(){
		return MemcachedClientNodeFactory.class;
	}

	@Override
	public Class<MemcachedClientManager> getClientManagerClass(){
		return MemcachedClientManager.class;
	}

}


text:
package org.scribble.ast;

import org.scribble.sesstype.kind.ProtocolKind;

// Make a compound interaction subclass for choice/parallel etc?
public interface InteractionNode<K extends ProtocolKind> extends ProtocolKindNode<K>
{
	//Set<MessageId<?>> collectMessageIds();  // Not worth implementing this homomorphically for every case except MessageTransfer, better to use visitChildren pattern
	//Map<Role, MessageId<?>> getEnablingMessages();
}


text:
"""
Catalan-language mappings for language-dependent features of Docutils.
"""

__docformat__ = 'reStructuredText'

labels = {
      # fixed: language-dependent
      'author': u'Autor',
      'authors': u'Autors',
      'organization': u'Organitzaci\u00F3',
      'address': u'Adre\u00E7a',
      'contact': u'Contacte',
      'version': u'Versi\u00F3',
      'revision': u'Revisi\u00F3',
      'status': u'Estat',
      'date': u'Data',
      'copyright': u'Copyright',
      'dedication': u'Dedicat\u00F2ria',
      'abstract': u'Resum',
      'attention': u'Atenci\u00F3!',
      'caution': u'Compte!',
      'danger': u'PERILL!',
      'error': u'Error',
      'hint': u'Suggeriment',
      'important': u'Important',
      'note': u'Nota',
      'tip': u'Consell',
      'warning': u'Av\u00EDs',
      'contents': u'Contingut'}
"""Mapping of node class name to label text."""

bibliographic_fields = {
      # language-dependent: fixed
      u'autor': 'author',
      u'autors': 'authors',
      u'organitzaci\u00F3': 'organization',
      u'adre\u00E7a': 'address',
      u'contacte': 'contact',
      u'versi\u00F3': 'version',
      u'revisi\u00F3': 'revision',
      u'estat': 'status',
      u'data': 'date',
      u'copyright': 'copyright',
      u'dedicat\u00F2ria': 'dedication',
      u'resum': 'abstract'}
"""Catalan (lowcased) to canonical name mapping for bibliographic fields."""

author_separators = [';', ',']
"""List of separator strings for the 'Authors' bibliographic field. Tried in
order."""


text:
package main

import (
	"fmt"
	"github.com/zero-boilerplate/go-api-helpers/service"
	"path/filepath"

	service2 "github.com/ayufan/golang-kardianos-service"
)

type app struct {
	logger             service2.Logger
	watcherDoneChannel chan bool
}

func (a *app) OnStop() {
	defer recover()
	if a.watcherDoneChannel != nil {
		close(a.watcherDoneChannel)
	}
}

func (a *app) Run(logger service2.Logger) {
	a.logger = logger
	defer func() {
		if r := recover(); r != nil {
			a.logger.Errorf("Run app error: %s", getStringFromRecovery(r))
		}
	}()

	userHomeDir := getUserHomeDir()
	watchDir := filepath.Join(userHomeDir, ".script-watcher", "scripts")
	if !doesDirExist(watchDir) {
		panic(fmt.Sprintf("The watch dir '%s' does not exist", watchDir))
		return
	}

	a.scanDirForExistingFile(watchDir)
	a.startWatching(watchDir)
}

func main() {
	a := &app{}
	service.NewServiceRunnerBuilder("Script Watcher", a).WithOnStopHandler(a).WithServiceUserName_AsCurrentUser().Run()
}


text:
<?php

namespace Controller\Theme;

use RedKiteCms\Rendering\Controller\Theme\ShowThemeController as BaseShowThemeController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to show the themes panel
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Theme
 */
class ShowThemeController extends BaseShowThemeController
{
    /**
     * Show themes panel action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function showAction(Request $request, Application $app)
    {
        $options = array(
            'twig' => $app["twig"],
            'template_assets' => $app["red_kite_cms.template_assets"],
            "configuration_handler" => $app["red_kite_cms.configuration_handler"],
            "plugin_manager" => $app["red_kite_cms.plugin_manager"],
        );

        return parent::show($options);
    }
}


text:
<?php

namespace Eloquent\Composer\Configuration\Exception;

/**
 * An interface for marking exceptions that are related to Composer
 * configuration.
 */
interface ConfigurationExceptionInterface
{
}


text:
package com.github.sandorw.cubetracker.server.cards.filters;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.github.sandorw.cubetracker.server.cards.Color;
import com.github.sandorw.cubetracker.server.cards.MagicCard;
import org.immutables.value.Value;
import org.immutables.value.Value.Parameter;

/**
 * Applies a filter based on the color of the card.
 */
@Value.Immutable
@JsonSerialize(as = ImmutableColorFilter.class)
@JsonDeserialize(as = ImmutableColorFilter.class)
public abstract class ColorFilter implements SearchFilter<MagicCard> {

    @Parameter
    public abstract Color getColorFilter();

    @Override
    public final boolean accept(MagicCard card) {
        return card.getColors().contains(getColorFilter());
    }

}


text:
<?php

require_once dirname(__FILE__) . "/format.class.php";

class JPG extends AbstractFormat
{

    function getFormatHeader()
    {
        return "Content-type: image/jpg";
    }

    function create(&$image)
    {
        imagejpeg($image);
    }
}

?>


text:
include $(SRILM)/common/Makefile.common.variables

# Define variables.

# Example Library declarations files.

EXTERNAL_LIB_HEADERS = \
	$(SRCDIR)/cfuncproto.h          \
	$(SRCDIR)/option.h		\
	$(SRCDIR)/zio.h			\
	$(SRCDIR)/mkdir.h		\
	$(SRCDIR)/Boolean.h		\
	$(SRCDIR)/Debug.h		\
	$(SRCDIR)/File.h		\
	$(SRCDIR)/version.h

INTERNAL_LIB_HEADERS =

# Example Library source files.
LIB_SOURCES = 				\
	$(SRCDIR)/option.c		\
	$(SRCDIR)/zio.c			\
	$(SRCDIR)/fcheck.c		\
	$(SRCDIR)/fake-rand48.c		\
	$(SRCDIR)/Debug.cc		\
	$(SRCDIR)/File.cc		\
	$(SRCDIR)/version.c

ifeq ($(NO_TCL), )
LIB_SOURCES +=	$(SRCDIR)/tclmain.cc
endif

# Example Library object files.
LIB_OBJECTS = $(patsubst $(SRCDIR)/%.cc,$(OBJDIR)/%$(OBJ_SUFFIX),\
		$(patsubst $(SRCDIR)/%.c,$(OBJDIR)/%$(OBJ_SUFFIX),$(LIB_SOURCES)))

# Example Library.
LIBRARY = $(OBJDIR)/$(LIB_PREFIX)misc$(LIB_SUFFIX)

ADDITIONAL_INCLUDES += \
	$(TCL_INCLUDE)

ADDITIONAL_LIBRARIES += \
	$(TCL_LIBRARY) \
	$(MATH_LIBRARY)

# Example programs.
PROGRAM_NAMES = \
	ztest \
	testFile

PROGRAMS = $(PROGRAM_NAMES:%=$(BINDIR)/%$(EXE_SUFFIX))

PROGRAM_SOURCES = $(foreach prog,$(PROGRAM_NAMES),\
			$(wildcard $(SRCDIR)/$(prog).c) \
			$(wildcard $(SRCDIR)/$(prog).cc))
PROGRAM_OBJECTS = $(PROGRAM_NAMES:%=$(OBJDIR)/%$(OBJ_SUFFIX))

# Libraries to be linked with the Example programs.
LIBRARIES = $(LIBRARY) \
	    $(ADDITIONAL_LIBRARIES)

# All of the types of files.

ALL_HEADERS = $(EXTERNAL_LIB_HEADERS) \
	      $(INTERNAL_LIB_HEADERS)

ALL_SOURCES = $(LIB_SOURCES) \
	      $(PROGRAM_SOURCES)

ALL_OBJECTS = $(LIB_OBJECTS) \
	      $(PROGRAM_OBJECTS)

ALL_LIBRARIES = $(LIBRARY)

ALL_PROGRAMS = $(PROGRAMS)

ALL_PROGRAM_NAMES = $(PROGRAM_NAMES)

# Define pseudo-targets.

# Make sure the library does not get deleted if the make is interrupted.
.PRECIOUS:	$(LIBRARY)

# Define targets.

all:	libraries

$(LIBRARY):	$(LIB_OBJECTS)
	$(ARCHIVE) $(AR_OUTPUT_OPTION) $^
	$(RANLIB) $@ $(DEMANGLE_FILTER)

SRILMversion.h:	$(SRILM)/RELEASE $(SRILM)/Copyright
	echo '#define SRILM_RELEASE "'`cat $(SRILM)/RELEASE`'"' > $@
	sed -f $(SRILM)/sbin/stringify-copyright $(SRILM)/Copyright >> $@

# Variables and Targets for released system

EXPORTED_HEADERS   = $(EXTERNAL_LIB_HEADERS)
EXPORTED_LIBRARIES = $(LIBRARY)
EXPORTED_PROGRAMS  =

release:	release-headers release-libraries release-programs

depend:	SRILMversion.h

cleaner:
	rm -f SRILMversion.h

# Include common SRILM target definitions.
include $(SRILM)/common/Makefile.common.targets


text:
class ApplicationMailer < ActionMailer::Base
  default from: "vincent.corniere@gmail.com"
  layout 'mailer'
end


text:
function New-PromptText {
    <#
        .Synopsis
            Create PoshCode.Pansies.Text with variable background colors
        .Description
            Allows changing the foreground and background colors based on elevation or success.

            Tests elevation fist, and then whether the last command was successful, so if you pass separate colors for each, the Elevated*Color will be used when PowerShell is running as administrator and there is no error. The Error*Color will be used whenever there's an error, whether it's elevated or not.
        .Example
            New-PromptText { Get-Elapsed } -ForegroundColor White -BackgroundColor DarkBlue -ErrorBackground DarkRed -ElevatedForegroundColor Yellow

            This example shows the time elapsed executing the last command in White on a DarkBlue background, but switches the text to yellow if elevated, and the background to red on error.
    #>
    [CmdletBinding(DefaultParameterSetName="Error")]
    [Alias("New-PowerLineBlock")]
    [Alias("New-TextFactory")]
    param(
        # The text, object, or scriptblock to show as output
        [Alias("Text", "Object")]
        [AllowNull()][EmptyStringAsNull()]
        [Parameter(Position=0, ValueFromPipeline, ValueFromPipelineByPropertyName)] # , Mandatory=$true
        $InputObject,

        # The foreground color to use when the last command succeeded
        [Alias("Foreground", "Fg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [AllowNull()][EmptyStringAsNull()]
        [PoshCode.Pansies.RgbColor]$ForegroundColor,

        # The background color to use when the last command succeeded
        [Alias("Background", "Bg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [AllowNull()][EmptyStringAsNull()]
        [PoshCode.Pansies.RgbColor]$BackgroundColor,

        # The foreground color to use when the process is elevated (running as administrator)
        [Alias("AFg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [AllowNull()][EmptyStringAsNull()]
        [PoshCode.Pansies.RgbColor]$ElevatedForegroundColor,

        # The background color to use when the process is elevated (running as administrator)
        [Alias("ABg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [AllowNull()][EmptyStringAsNull()]
        [PoshCode.Pansies.RgbColor]$ElevatedBackgroundColor,

        # The foreground color to use when the last command failed
        [Alias("EFg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [AllowNull()][EmptyStringAsNull()]
        [PoshCode.Pansies.RgbColor]$ErrorForegroundColor,

        # The background color to use when the last command failed
        [Alias("EBg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [AllowNull()][EmptyStringAsNull()]
        [PoshCode.Pansies.RgbColor]$ErrorBackgroundColor
    )
    process {
        # Try to fix the parameter binding
        if($InputObject.InputObject) {
            $InputObject = $InputObject.InputObject
        } elseif($InputObject.Object) {
            $InputObject = $InputObject.Object
        }elseif($InputObject.Text) {
            $InputObject = $InputObject.Text
        }

        $output = [PoshCode.Pansies.Text]@{
            Object = $InputObject
        }
        # Always set the defaults first, if they're provided
        if($PSBoundParameters.ContainsKey("ForegroundColor") -and $ForegroundColor -ne $Null) {
            $output.ForegroundColor = $ForegroundColor
        }
        if($PSBoundParameters.ContainsKey("BackgroundColor") -and $BackgroundColor -ne $Null) {
            $output.BackgroundColor = $BackgroundColor
        }

        # If it's elevated, and they passed the elevated color ...
        if(Test-Elevation) {
            if($PSBoundParameters.ContainsKey("ElevatedForegroundColor") -and $ElevatedForegroundColor -ne $Null) {
                $output.ForegroundColor = $ElevatedForegroundColor
            }
            if($PSBoundParameters.ContainsKey("ElevatedBackgroundColor") -and $ElevatedBackgroundColor -ne $Null) {
                $output.BackgroundColor = $ElevatedBackgroundColor
            }
        }

        # If it failed, and they passed an error color ...
        if(!(Test-Success)) {
            if($PSBoundParameters.ContainsKey("ErrorForegroundColor") -and $ErrorForegroundColor -ne $Null) {
                $output.ForegroundColor = $ErrorForegroundColor
            }
            if($PSBoundParameters.ContainsKey("ErrorBackgroundColor") -and $ErrorBackgroundColor -ne $Null) {
                $output.BackgroundColor = $ErrorBackgroundColor
            }
        }

        $output
    }
}


text:
class SimGUI : public OIS::MouseListener, public OIS::KeyListener
{
  public:
	SimGUI( SimApp& );
	void Load();
	void Unload();
	void Update();
	void Resize( int, int );

	// OIS Event Handlers
	bool mouseMoved( const OIS::MouseEvent& );
	bool mousePressed( const OIS::MouseEvent&, OIS::MouseButtonID );
	bool mouseReleased( const OIS::MouseEvent&, OIS::MouseButtonID );
	bool keyPressed( const OIS::KeyEvent& );
	bool keyReleased( const OIS::KeyEvent& );

	// MyGUI events:
	void MenuBarWidgetClicked( MyGUI::Widget* );

  protected:
	SimApp &app;
	MyGUI::Gui *myGui;
	MyGUI::OgrePlatform *platform;
};

#endif


text:
package org.atlasapi.schedule;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.atlasapi.content.Brand;
import org.atlasapi.content.Container;
import org.atlasapi.content.Content;
import org.atlasapi.content.ContentStore;
import org.atlasapi.content.Episode;
import org.atlasapi.content.Item;
import org.atlasapi.content.ItemAndBroadcast;
import org.atlasapi.content.Series;
import org.atlasapi.entity.Id;
import org.atlasapi.entity.util.WriteException;
import org.atlasapi.entity.util.WriteResult;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * Convenience class to transform a number of schedule hierarchies into unique groups for writing.
 */
class WritableScheduleHierarchy {

    static WritableScheduleHierarchy from(List<ScheduleHierarchy> hierarchies) {
        ImmutableSet.Builder<Container> topLevelContainers = ImmutableSet.builder();
        ImmutableSet.Builder<Series> series = ImmutableSet.builder();
        Map<Series, Brand> seriesBrandIndex = Maps.newHashMap();
        Map<Id, Item> itemsIndex = Maps.newHashMapWithExpectedSize(hierarchies.size());
        ImmutableSet.Builder<Item> unidentified = ImmutableSet.builder();
        Map<Item, Container> itemPrimaryContainerIndex = Maps.newHashMap();
        Map<Item, Series> itemSeriesIndex = Maps.newHashMap();

        for (ScheduleHierarchy hierarchy : Lists.reverse(hierarchies)) {
            Optional<Container> tlc = hierarchy.getPrimaryContainer();
            if (tlc.isPresent()) {
                topLevelContainers.add(tlc.get());
            }
            Optional<Series> possibleSeries = hierarchy.getPossibleSeries();
            if (possibleSeries.isPresent() && !possibleSeries.get().equals(tlc.orNull())) {
                series.add(possibleSeries.get());
                if (tlc.isPresent() && tlc.get() instanceof Brand) {
                    seriesBrandIndex.put(possibleSeries.get(), (Brand) tlc.get());
                }
            }
            Item item = hierarchy.getItemAndBroadcast().getItem();
            if (item.getId() == null) {
                unidentified.add(item);
            } else {
                Item existing = itemsIndex.get(item.getId());
                if (existing != null) {
                    item = addBroadcast(existing, hierarchy.getItemAndBroadcast());
                }
                itemsIndex.put(item.getId(), item);
            }
            if (tlc.isPresent()) {
                itemPrimaryContainerIndex.put(item, tlc.get());
            }
            if (possibleSeries.isPresent()) {
                itemSeriesIndex.put(item, possibleSeries.get());
            }
        }
        return new WritableScheduleHierarchy(topLevelContainers.build(), series.build(),
                unidentified.addAll(itemsIndex.values()).build(),
                seriesBrandIndex, itemPrimaryContainerIndex, itemSeriesIndex
        );
    }

    private static Item addBroadcast(Item existing, ItemAndBroadcast itemAndBroadcast) {
        existing.addBroadcast(itemAndBroadcast.getBroadcast());
        return existing;
    }

    private Set<Container> topLevelContainers;
    private Set<Series> series;
    private Set<Item> items;
    private Map<Series, Brand> seriesBrandIndex;
    private Map<Item, Container> itemPrimaryContainerIndex;
    private Map<Item, Series> itemSeriesIndex;

    WritableScheduleHierarchy(Set<Container> topLevelContainers, Set<Series> series,
            Set<Item> items, Map<Series, Brand> seriesBrandIndex,
            Map<Item, Container> itemPrimaryContainerIndex, Map<Item, Series> itemSeriesIndex) {
        this.topLevelContainers = topLevelContainers;
        this.series = series;
        this.items = items;
        this.seriesBrandIndex = seriesBrandIndex;
        this.itemPrimaryContainerIndex = itemPrimaryContainerIndex;
        this.itemSeriesIndex = itemSeriesIndex;
    }

    List<WriteResult<? extends Content, Content>> writeTo(ContentStore contentStore)
            throws WriteException {
        ImmutableList.Builder<WriteResult<? extends Content, Content>> results = ImmutableList.builder();
        Map<Container, Container> tlcWritten = writePrimaryContainers(contentStore, results);
        Map<Series, Series> seriesWritten
                = writeSecondaryContainers(contentStore, results, tlcWritten);
        writeItems(contentStore, results, tlcWritten, seriesWritten);
        return results.build();
    }

    private Map<Container, Container> writePrimaryContainers(ContentStore contentStore,
            ImmutableList.Builder<WriteResult<? extends Content, Content>> results)
            throws WriteException {
        Map<Container, Container> tlcWritten = Maps.newHashMap();
        for (Container container : topLevelContainers) {
            WriteResult<Container, Content> written = contentStore.writeContent(container);
            results.add(written);
            tlcWritten.put(container, written.getResource());
        }
        return tlcWritten;
    }

    private Map<Series, Series> writeSecondaryContainers(ContentStore contentStore,
            ImmutableList.Builder<WriteResult<? extends Content, Content>> results,
            Map<Container, Container> tlcWritten) throws WriteException {
        Map<Series, Series> seriesWritten = Maps.newHashMap();
        for (Series sery : series) {
            Brand tlc = seriesBrandIndex.get(sery);
            if (tlc != null) {
                sery.setBrand((Brand) tlcWritten.get(tlc));
            }
            WriteResult<Series, Content> written = contentStore.writeContent(sery);
            results.add(written);
            seriesWritten.put(sery, written.getResource());
        }
        return seriesWritten;
    }

    private void writeItems(ContentStore contentStore,
            ImmutableList.Builder<WriteResult<? extends Content, Content>> results,
            Map<Container, Container> tlcWritten, Map<Series, Series> seriesWritten)
            throws WriteException {
        for (Item item : items) {
            Container tlc = itemPrimaryContainerIndex.get(item);
            if (tlc != null) {
                item.setContainer(tlcWritten.get(tlc));
            }
            if (item instanceof Episode) {
                Series series = itemSeriesIndex.get(item);
                if (series != null) {
                    Container writtenSeries = tlcWritten.get(series);
                    if (writtenSeries == null) {
                        writtenSeries = seriesWritten.get(series);
                    }
                    if (writtenSeries instanceof Series) {
                        ((Episode) item).setSeries((Series) writtenSeries);
                    }
                }
            }
            results.add(contentStore.writeContent(item));
        }
    }

}