text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="lt.personal_PSK_war_1.0-SNAPSHOTPU" transaction-type="JTA">
    <jta-data-source>StudentsDataSource</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties/>
  </persistence-unit>
</persistence>

redpajama_set_name: RedPajamaGithub


text:
$(function() {
  var $menuSite = $(document.getElementById('menu-site'));
  var $menuSocial = $(document.getElementById('menu-social'));

  var headroomOptions = {
    tolerance: {
      up: 0,
      down: 10
    },
    classes: {
      initial: 'sticky',
      pinned: 'in',
      unpinned: 'out',
      top: 'over',
      notTop: 'under'
    }
  };

  // Sticky menus.
  $menuSite.headroom(headroomOptions);
  $menuSocial.headroom(headroomOptions);
});


text:
import os
import re
import time
import shutil
import utils.Configuration
from utils.Configuration import ConfigurationItem

from Giraffe.template import template

class index(object):
    def __init__(self, args, kw):
        self.args = args
        self.kwargs = kw
        self.configuration = utils.Configuration.Configuration()
        self.configPath = 'config/'
        self.newConfigurationItems = {}
        self.pendingChanges = False

    def SaveConfig(self):
        backupDir = self.configPath + 'backup/' + self.filename + '/'
        if not os.path.exists(backupDir):
            os.makedirs(backupDir)

        localtime = time.localtime()
        timeString = time.strftime("%Y%m%d%H%M%S", localtime)
        fileNameParts = os.path.splitext(self.filename)
        shutil.copy(self.completeFilename, '%s%s%s' % (backupDir, timeString, fileNameParts[1]))

        self.configuration.WriteFile(self.completeFilename)

    def MergeNewConfigItemsWithExisting(self):
        for (section, configSection) in self.newConfigurationItems.items():
            if self.configuration.config[section] is None:
                self.configuration.config.AddChild(ConfigurationItem(section, ''))
            for (configId, config) in configSection.items():
                if self.configuration.config[section][config['Name']] is None:
                    self.configuration.config[section].AddChild(ConfigurationItem(config['Name'], config['Value']))
        self.newConfigurationItems = {}

    def isValidFilename(self, filename):
        return re.match("([a-zA-Z0-9\-_ \(\)]+)\.([a-zA-Z0-9\-_]+)", filename) is None

    def OutputPage(self):

        if 'filename' not in self.kwargs:
            self.filename = "SampleIniFile.ini"
        else:
            self.filename = self.kwargs['filename']

        self.completeFilename = self.configPath + self.filename
        if self.isValidFilename(self.filename) or not os.path.exists(self.completeFilename):
            return 'Invalid filename specified: ' + self.filename

        self.PopulateConfigurationFromForm()

        if self.configuration.config.children == []:
            self.configuration.LoadFile(self.completeFilename)

        self.ProcessEditButtons()

        if 'submit' in self.kwargs:
            self.MergeNewConfigItemsWithExisting()
            self.SaveConfig()

        originalConfig = utils.Configuration.Configuration()
        originalConfig.LoadFile(self.completeFilename)
        if not self.configuration.config == originalConfig.config:
            self.pendingChanges = True

        self.page = template.Load("index")
        self.page.SetVariable("ConfigFilename", self.filename)

        self.PopulateTabs()

        self.PopulateConfigurationSections()

        if 'Mode' not in self.kwargs or self.kwargs['Mode'] not in ['Simple', 'Advanced']:
            if 'CurrentMode' in self.kwargs and self.kwargs['CurrentMode'] in ['Simple', 'Advanced']:
                self.kwargs['Mode'] = self.kwargs['CurrentMode']
            else:
                self.kwargs['Mode'] = 'Simple'

        self.page.SetVariable("AdvancedMode", self.kwargs['Mode'] == 'Advanced')
        self.page.SetVariable("PendingChanges", self.pendingChanges)

        return self.page.OutputPage()

    def PopulateConfigurationFromForm(self):
        for (name, value) in self.kwargs.items():
            nameParts = name.split('=')
            if nameParts[0] == 'configuration':
                if len(nameParts) == 2:
                    self.PopulateExistingSectionsFromForm(nameParts, value)
                elif len(nameParts) == 3:
                    self.PopulateExistingConfigurationFromForm(nameParts, value)
                elif len(nameParts) == 4:
                    self.PopulateNewConfigurationFromForm(nameParts, value)

    def PopulateNewConfigurationFromForm(self, splitName, value):
        if not splitName[1] in self.newConfigurationItems:
            self.newConfigurationItems[splitName[1]] = {}
        if not splitName[3] in self.newConfigurationItems[splitName[1]]:
            self.newConfigurationItems[splitName[1]][splitName[3]] = {}
        if splitName[2] == 'NewItemName':
            self.newConfigurationItems[splitName[1]][splitName[3]]['Name'] = value.lower()
        elif splitName[2] == 'NewItemValue':
            self.newConfigurationItems[splitName[1]][splitName[3]]['Value'] = value

    def PopulateExistingSectionsFromForm(self, splitName, value):
        if self.configuration.config[splitName[1]] is None:
            self.configuration.config.AddChild(ConfigurationItem(splitName[1], ''))

    def PopulateExistingConfigurationFromForm(self, splitName, value):
        if self.configuration.config[splitName[1]] is None:
            self.configuration.config.AddChild(ConfigurationItem(splitName[1], ''))
        section = self.configuration.config[splitName[1]]
        if section is None:
            section = ConfigurationItem(splitName[1], '')
            self.configuration.config.AddChild(section)

        configItem = section[splitName[2].lower()]
        if configItem is None:
            configItem = ConfigurationItem(splitName[2].lower(), value)
            self.configuration.config[splitName[1]].AddChild(configItem)
        else:
            configItem.Value = value

    def ProcessEditButtons(self):
        for (name, value) in self.kwargs.items():
            nameParts = name.split('=')
            if nameParts[0] == 'delete':
                if len(nameParts) == 2:
                    self.configuration.config.DeleteChild(nameParts[1])
                elif len(nameParts) == 3:
                    self.configuration.config[nameParts[1]].DeleteChild(nameParts[2])

    def PopulateTabs(self):
        for configFilename in os.listdir(self.configPath):
            fileExtension = os.path.splitext(configFilename)[1]
            if fileExtension == '.ini':
                self.page.AddNest('fileTab', {
                    'Selected': True if (configFilename == self.filename) else False,
                    'Filename': configFilename
                })

    def PopulateConfigurationSections(self):
        for section in self.configuration.config:
            nextItem = 1
            nextNewItem = 1
            sectionNest = self.page.AddNest("configSection", {
                'SectionName': section.Name
            })
            for config in section:
                self.page.AddSubNest(sectionNest, "configItem", {
                    'ConfigId': str(nextItem),
                    'ConfigName': config.Name,
                    'ConfigValue': config.Value
                })
                nextItem += 1
            if section.Name in self.newConfigurationItems:
                for (newItemId, newItem) in self.newConfigurationItems[section.Name].items():
                    self.page.AddSubNest(sectionNest, "newConfigItem", {
                        'ConfigNumber': str(nextNewItem),
                        'ConfigName': newItem['Name'],
                        'ConfigValue': newItem['Value']
                    })
                    nextNewItem += 1

            if 'addItem=' + section.Name in self.kwargs:
                self.page.AddSubNest(sectionNest, "newConfigItem", {
                    'ConfigNumber': str(nextNewItem),
                    'ConfigName': '',
                    'ConfigValue': ''
                })


text:
goog.provide('shaka.util.Timer');

/**
 * A simple cancelable timer.
 * @param {Function} callback
 * @constructor
 * @struct
 */
shaka.util.Timer = function(callback) {
  /** @private {?number} */
  this.id_ = null;

  /** @private {number} */
  this.timeoutSeconds_ = 0;

  /** @private {Function} */
  this.callback_ = (function() {
    this.id_ = null;
    callback();
  }.bind(this));
};

/**
 * Cancel the timer, if it's running.
 */
shaka.util.Timer.prototype.cancel = function() {
  if (this.id_ != null) {
    clearTimeout(this.id_);
    this.id_ = null;
  }
};

/**
 * Schedule the timer, canceling any previous scheduling.
 * @param {number} seconds
 */
shaka.util.Timer.prototype.schedule = function(seconds) {
  this.cancel();
  this.timeoutSeconds_ = seconds;
  this.id_ = setTimeout(this.callback_, seconds * 1000);
};

/**
 * If the timer is running, reschedule it using the previous scheduled timeout.
 * @example
 *   If scheduled for 5 seconds, and rescheduled 3 seconds later,
 *   the timer will fire 8 seconds after the original scheduling.
 * @example
 *   If scheduled for 5 seconds, and rescheduled 6 seconds later,
 *   the timer will already have fired and will not be rescheduled.
 */
shaka.util.Timer.prototype.rescheduleIfRunning = function() {
  if (this.id_ != null) {
    this.schedule(this.timeoutSeconds_);
  }
};


text:
OSARCH="linux/386 linux/amd64 darwin/amd64 windows/386 windows/amd64"
RELEASE_WORKING_DIR=release/gocdnjs
PROJECT_ROOT=$(shell pwd)

.PHONY: gox-exists
gox-exists: ; @which gox > /dev/null 2>&1

.PHONY: ghr-exists
ghr-exists: ; @which ghr > /dev/null 2>&1

.PHONY : check-release-dependencies
check-release-dependencies: gox-exists ghr-exists

.PHONY : clean-release
clean-release:
	rm -rf $(RELEASE_WORKING_DIR)

.PHONY : check-release-tag-variable
check-release-tag-variable:
	@git tag -l | grep -P "^v$$RELEASE_TAG$$" > /dev/null || (echo v$(RELEASE_TAG) is not found in git tags. RELEAT_TAG must not be includeed 'v' prefix && exit 1)
	@echo RELEASE_TAG=$(RELEASE_TAG)

.PHONY : release
release: check-release-dependencies clean-release check-release-tag-variable
	@mkdir -p $(RELEASE_WORKING_DIR)
	git clone -b v$(RELEASE_TAG) . $(RELEASE_WORKING_DIR)
	cd $(RELEASE_WORKING_DIR)
	cd $(RELEASE_WORKING_DIR) && gox --osarch $(OSARCH) -output "dist/{{.Dir}}_$(RELEASE_TAG)_{{.OS}}_{{.Arch}}/{{.Dir}}"
	cd $(RELEASE_WORKING_DIR) && bash $(PROJECT_ROOT)/script/zip-releases.sh
	ghr -t $(GITHUB_TOKEN) v$(RELEASE_TAG) $(RELEASE_WORKING_DIR)/pkg/


text:
'use strict';

import { connect } from 'react-redux';
import AdDetail from '../components/AdDetail';

function mapStateToProps(store) {
  return {
    fetching: store.Ad.fetching,
    ad: store.Ad.ad,
  };
}

export default connect(
  mapStateToProps,
)(AdDetail);


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>numpy.core.defchararray.encode — NumPy v1.8 Manual</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="author" title="About these documents" href="../../about.html" />
    <link rel="top" title="NumPy v1.8 Manual" href="../../index.html" />
    <link rel="up" title="String operations" href="../routines.char.html" />
    <link rel="next" title="numpy.core.defchararray.join" href="numpy.core.defchararray.join.html" />
    <link rel="prev" title="numpy.core.defchararray.decode" href="numpy.core.defchararray.decode.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          next |

          previous |

NumPy v1.8 Manual »

NumPy Reference »

Routines »

String operations »

numpy.core.defchararray.encode¶

<tt class="descclassname">numpy.core.defchararray.</tt><tt class="descname">encode</tt><big>(</big>a, encoding=None, errors=None<big>)</big>[source]¶

Calls str.encode element-wise.

The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the codecs
module.

<col class="field-name" />
<col class="field-body" />

Parameters:
a : array_like of str or unicode

encoding : str, optional

The name of an encoding

errors : str, optional

Specifies how to handle encoding errors

Returns:
out : ndarray

See also

<tt class="xref py py-obj docutils literal">str.encode</tt>

Notes

The type of the result will depend on the encoding specified.

    © Copyright 2008-2009, The Scipy community.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.


text:
package org.azolla.l.ling;

import org.azolla.l.ling.cfg.Cfg0Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * The coder is very lazy, nothing to write for this ExceptionTest class
 *
 * @author 	sk@azolla.org
 * @version 1.0.0
 * @since 	ADK1.0
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({Cfg0Test.class})
public class LingTests
{

}


text:
'use strict';

const jsonPathModule = require('jsonpath'),
  { transformAndValidateMeasurements } = require('./validators');

/**
 * this decode takes either an object like
 * {
 *   "sensorID": "value",
 *   "anotherSensorID": ["value"]
 *   "sensorID3": ["value", "createdAt as ISO8601-timestamp"],
 *   "sensorID4": ["value", "createdAt as ISO8601-timestamp", "location latlng-object or array"],
 *   ...
 *
 * }
 *
 * or an Array like
 * [
 *   {"sensor":"sensorID", "value":"value"},
 *   {"sensor":"anotherSensorId", "value":"value", "createdAt": "ISO8601-timestamp"}
 *   ...
 * ]
 *
 * and transforms it into the form
 * [
 *   {"sensor_id": "sensorID", "value":"value", "createdAt": JavaScript Date Object },
 *   ...
 * ]
 *
 * When given options like {"jsonPath":"some valid JSONPath"} as second parameter,
 * it extracts the measurments json or array from the given message.
 * This is only used for MQTT so far
 */

// this method does not validate!
const handleJSONObjectMultipleValues = function (obj) {
  const outArray = [];

  // transform into Array
  for (const sensorId of Object.keys(obj)) {
    // construct measurement
    const measurement = { sensor_id: sensorId };
    let value = obj[sensorId];

    // check if the value is an array. First item is the value, second the timestamp
    if (Array.isArray(value)) {
      if (value.length === 1) { // single item measurement
        value = value[0];
      } else if (value.length === 2) { // [value,createdAt]
        measurement.createdAt = value[1];
        value = value[0];
      } else if (value.length === 3) { // [value,createdAt,location]
        measurement.location = value[2];
        measurement.createdAt = value[1];
        value = value[0];
      } else {
        throw new Error(`Array for sensorID '${sensorId}' has an illegal length`);
      }
    }
    // set the value
    measurement.value = value;
    outArray.push(measurement);
  }

  return outArray;
};

module.exports = {
  decodeMessage: function (message, { jsonPath } = {}) {
    if (message) {
      // try to decode the json, or if already a js object
      // use it as given
      let json;
      if (!(message instanceof Buffer) && typeof message === 'object') {
        json = message;
      } else {
        try {
          json = JSON.parse(message);
        } catch (err) {
          return Promise.reject(err);
        }
      }

      // use the root '$' if no jsonPath was specified
      let path = '$';
      if (jsonPath) {
        path = jsonPath;
      }
      // extract the json with jsonPath
      const result = jsonPathModule.query(json, path, 1);

      if (result && result[0]) {
        let decodedJson = result[0];
        if (!Array.isArray(decodedJson)) {
          try {
            decodedJson = handleJSONObjectMultipleValues(decodedJson);
          } catch (err) {
            return Promise.reject(err);
          }
        }

        return transformAndValidateMeasurements(decodedJson);
      }
    }

    return Promise.reject(new Error('Cannot decode empty message (json decoder)'));
  }
};


text:
import { render } from '@testing-library/react';
import { sqlParserFactory } from 'druid-query-toolkit';
import React from 'react';

import { ColumnMetadata } from '../../../utils/column-metadata';

import { ColumnTree } from './column-tree';

describe('column tree', () => {
  const parser = sqlParserFactory(['COUNT']);

  it('matches snapshot', () => {
    const columnTree = (
      <ColumnTree
        getParsedQuery={() => {
          return parser(`SELECT channel, count(*) as cnt FROM wikipedia GROUP BY 1`);
        }}
        defaultSchema="druid"
        defaultTable="wikipedia"
        columnMetadataLoading={false}
        columnMetadata={
          [
            {
              TABLE_SCHEMA: 'druid',
              TABLE_NAME: 'wikipedia',
              COLUMN_NAME: '__time',
              DATA_TYPE: 'TIMESTAMP',
            },
            {
              TABLE_SCHEMA: 'druid',
              TABLE_NAME: 'wikipedia',
              COLUMN_NAME: 'added',
              DATA_TYPE: 'BIGINT',
            },
            {
              TABLE_SCHEMA: 'druid',
              TABLE_NAME: 'wikipedia',
              COLUMN_NAME: 'addedBy10',
              DATA_TYPE: 'FLOAT',
            },
            {
              TABLE_SCHEMA: 'sys',
              TABLE_NAME: 'tasks',
              COLUMN_NAME: 'error_msg',
              DATA_TYPE: 'VARCHAR',
            },
          ] as ColumnMetadata[]
        }
        onQueryStringChange={() => {}}
      />
    );

    const { container } = render(columnTree);
    expect(container.firstChild).toMatchSnapshot();
  });
});


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Web.Http;
using Dashboard.UnitTests.RestProtocol;
using Microsoft.Azure.WebJobs.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Xunit;

namespace Dashboard.UnitTests
{
    // Test calling the REST API surface.
    // This surface area is important because the APIs are public and called by the Portal.
    // This explicitly goes through the HttpClient and tests things like serialization, rest interfaces, etc.
    [Trait("SecretsRequired", "true")]
    public class RestApiTests : IClassFixture<RestApiTests.Fixture>
    {
        private readonly Fixture _fixture;
        private readonly HttpClient _client;
        private readonly string _endpoint;

        public RestApiTests(Fixture fixture)
        {
            _fixture = fixture;
            _client = fixture.Client;
            _endpoint = fixture.Endpoint;
        }

        // test the /verison endpoint.
        [Fact]
        public async Task GetVersion()
        {
            var response = await _client.GetJsonAsync<VersionResponse>(_endpoint + "/api/version");

            var assembly = typeof(WebApiConfig).Assembly;
            AssemblyFileVersionAttribute fileVersionAttr = assembly.GetCustomAttribute<AssemblyFileVersionAttribute>();

            Assert.Equal(response.Version, fileVersionAttr.Version);
        }

        [Fact]
        public async Task GetDefinitionSkipStats()
        {
            var response = await _client.GetJsonAsync<FunctionStatisticsSegment>(_endpoint + "/api/functions/definitions?limit=100&skipstats=true");

            // Testing against specific data that we added.
            Assert.Equal(null, response.ContinuationToken);
            var x = response.Entries.ToArray();
            Assert.Equal(1, x.Length);
            Assert.Equal("alpha", x[0].functionName);
            Assert.Equal(0, x[0].successCount); // Skipped
            Assert.Equal(0, x[0].failedCount);
        }

        [Fact]
        public async Task GetDefinition()
        {
            var response = await _client.GetJsonAsync<FunctionStatisticsSegment>(_endpoint + "/api/functions/definitions?limit=100");

            // Testing against specific data that we added.
            Assert.Equal(null, response.ContinuationToken);
            var x = response.Entries.ToArray();
            Assert.Equal(1, x.Length);
            Assert.Equal("alpha", x[0].functionName);
        }

        // Pass ?host=  parameter when getting definitions to filter to a specific host.
        [Fact]
        public async Task GetDefinitionSingleHost()
        {
            var response = await _client.GetJsonAsync<FunctionStatisticsSegment>(_endpoint + "/api/functions/definitions?limit=100&host=missing");

            // Testing against specific data that we added.
            Assert.Equal(null, response.ContinuationToken);
            var x = response.Entries.ToArray();
            Assert.Equal(0, x.Length);
        }

        [Fact]
        public async Task GetTimelineInvocations()
        {
            // Lookup functions by name
            string uri = _endpoint + "/api/functions/invocations/" + FunctionId.Build(Fixture.HostName, "alpha") +
                "/timeline?limit=11&start=2001-01-01";
            var response = await _client.GetJsonAsync<TimelineResponseEntry[]>(uri);

            // This only includes completed / failed functions, not NeverFinished/Running.
            // Important that DateTimes include the 'Z' suffix, meaning UTC timezone.
            Assert.Equal(2, response.Length);
            Assert.Equal("2010-03-06T18:10:00Z", response[0].Start);
            Assert.Equal(1, response[0].TotalFail);
            Assert.Equal(0, response[0].TotalPass);
            Assert.Equal(1, response[0].TotalRun);

            Assert.Equal("2010-03-06T18:11:00Z", response[1].Start);
            Assert.Equal(0, response[1].TotalFail);
            Assert.Equal(1, response[1].TotalPass);
            Assert.Equal(1, response[1].TotalRun);
        }

        public async Task GetTimelineEmptyInvocations()
        {
            // Look in timeline range where there's no functions invocations.
            // This verifies the time range is getting parsed by the webapi and passed through.
            string uri = _endpoint + "/api/functions/invocations/" + FunctionId.Build(Fixture.HostName, "alpha") +
                "/timeline?limit=11&start=2005-01-01";
            var response = await _client.GetJsonAsync<TimelineResponseEntry[]>(uri);

            Assert.Equal(0, response.Length);
        }

        [Fact]
        public async Task GetInvocations()
        {
            // Lookup functions by name
            string uri = _endpoint + "/api/functions/definitions/" + FunctionId.Build(Fixture.HostName, "alpha") + "/invocations?limit=11";
            var response = await _client.GetJsonAsync<DashboardSegment<InvocationLogViewModel>>(uri);

            Assert.Equal(_fixture.ExpectedItems.Count, response.entries.Length);

            for (int i = 0; i < response.entries.Length; i++)
            {
                var expectedItem = _fixture.ExpectedItems[i];
                var actualItem = response.entries[i];

                AssertEqual(expectedItem, actualItem);

                Assert.Equal("alpha", actualItem.functionDisplayTitle);
            }
        }

        [Fact]
        public async Task GetSpecificInvocation()
        {
            foreach (var expectedItem in _fixture.ExpectedItems)
            {
                var url = _endpoint + "/api/functions/invocations/" + expectedItem.id;
                var response = await _client.GetJsonAsync<FunctionInstanceDetailsViewModel>(url);

                var actualItem = response.Invocation;
                AssertEqual(expectedItem, actualItem);

                Assert.Equal("alpha ()", response.Invocation.functionDisplayTitle);

                Assert.Equal(actualItem.id, response.TriggerReason.childGuid);
            }
        }

        private static void AssertEqual(InvocationLogViewModel expectedItem, InvocationLogViewModel actualItem)
        {
            Assert.Equal(expectedItem.id, actualItem.id);
            Assert.Equal(expectedItem.whenUtc, actualItem.whenUtc);
            Assert.Equal(expectedItem.status, actualItem.status);
            if (actualItem.status != "Running")
            {
                Assert.Equal(expectedItem.duration, actualItem.duration);
            }
            else
            {
                // Compares to current time.
                var minValue = DateTime.UtcNow.AddDays(-1) - DateTime.Parse(actualItem.whenUtc);
                var totalMs = minValue.TotalMilliseconds;

                Assert.True(actualItem.duration.Value > totalMs);
            }
        }

        [Fact]
        public async Task GetLogOutput()
        {
            var item = _fixture.Data[0];

            var responseLog = await _client.GetAsync(_endpoint + "/api/log/output/" + item.FunctionInstanceId.ToString());
            Assert.Equal(HttpStatusCode.OK, responseLog.StatusCode);
            string str = await responseLog.Content.ReadAsStringAsync();
            Assert.Equal(item.LogOutput, str);
        }

        // Shared context across tests.
        // This creates HttpServer & Client to access the rest APIs.
        // It also creates some baseline logging data to test against.
        public class Fixture : IDisposable
        {
            private const string FunctionLogTableAppSettingName = "AzureWebJobsLogTableName";

            public static string HostName = "Host";

            private ILogTableProvider _provider;

            public HttpClient Client { get; private set; }
            public string Endpoint { get; private set; }

            public List<FunctionInstanceLogItem> Data {get; private set; }
            public List<InvocationLogViewModel> ExpectedItems { get; private set; }

            public Fixture()
            {
                Init().Wait();
            }

            public async Task Init()
            {
                var tableClient = GetNewLoggingTableClient();
                var tablePrefix = "logtesZZ" + Guid.NewGuid().ToString("n");
                ConfigurationManager.AppSettings[FunctionLogTableAppSettingName] = tablePrefix; // tell dashboard to use it
                _provider = LogFactory.NewLogTableProvider(tableClient, tablePrefix);
                await WriteTestLoggingDataAsync(_provider);

                var config = new HttpConfiguration();

                var container = MvcApplication.BuildContainer(config);

                WebApiConfig.Register(config);

                var server = new HttpServer(config);
                var client = new HttpClient(server);

                this.Client = client;
                this.Endpoint = "http://localhost:8080"; // ignored
            }

            public void Dispose()
            {
                DisposeAsync().Wait();
            }
            private async Task DisposeAsync()
            {
                var tables = await _provider.ListTablesAsync();
                Task[] tasks = Array.ConvertAll(tables, table => table.DeleteIfExistsAsync());
                await Task.WhenAll(tasks);
            }

            // Write logs. Return what we wrote.
            // This is baseline data. REader will verify against it exactly. This helps in aggressively catching subtle breaking changes.
            private async Task WriteTestLoggingDataAsync(ILogTableProvider provider)
            {
                ILogWriter writer = LogFactory.NewWriter(HostName, "c1", provider);

                string Func1 = "alpha";
                var time = new DateTime(2010, 3, 6, 18, 11, 20, DateTimeKind.Utc);

                List<FunctionInstanceLogItem> list = new List<FunctionInstanceLogItem>();
                List<InvocationLogViewModel> expected = new List<InvocationLogViewModel>();
                this.ExpectedItems = expected;
                this.Data = list;

                // List in reverse chronology.
                // Completed Success
                {
                    var item = new FunctionInstanceLogItem
                    {
                        FunctionInstanceId = Guid.NewGuid(),
                        FunctionName = Func1,
                        StartTime = time,
                        EndTime = time.AddMinutes(2),  // Completed
                        LogOutput = "one",
                    };
                    list.Add(item);
                    expected.Add(new InvocationLogViewModel
                    {
                        id = item.FunctionInstanceId.ToString(),
                        status = "CompletedSuccess",
                        whenUtc = "2010-03-06T18:13:20Z", // since it's completed, specifies end-time
                        duration = 120000.0
                    });
                }

                // Completed Error
                {
                    time = time.AddMinutes(-1);
                    var item = new FunctionInstanceLogItem
                    {
                        FunctionInstanceId = Guid.NewGuid(),
                        FunctionName = Func1,
                        StartTime = time,
                        EndTime = time.AddMinutes(2),
                        ErrorDetails = "some failure", // signifies failure
                        LogOutput = "two",
                    };
                    list.Add(item);
                    expected.Add(new InvocationLogViewModel
                    {
                        id = item.FunctionInstanceId.ToString(),
                        status = "CompletedFailed",
                        whenUtc = "2010-03-06T18:12:20Z", // end-time.
                        duration = 120000.0
                    });
                }

                // Still running
                {
                    time = time.AddMinutes(-1);
                    var item = new FunctionInstanceLogItem
                    {
                        FunctionInstanceId = Guid.NewGuid(),
                        FunctionName = Func1,
                        StartTime = time,  // Recent heartbeat
                        LogOutput = "two",
                    };
                    list.Add(item);
                    expected.Add(new InvocationLogViewModel
                    {
                        id = item.FunctionInstanceId.ToString(),
                        status = "Running",
                        whenUtc = "2010-03-06T18:09:20Z", // specifies start-time
                    });
                }

                // Never Finished
                {
                    time = time.AddMinutes(-1);
                    var item = new TestFunctionInstanceLogItem
                    {
                        FunctionInstanceId = Guid.NewGuid(),
                        FunctionName = Func1,
                        StartTime = time,  // Never Finished
                        LogOutput = "two",
                        OnRefresh = (me) => { me.FunctionInstanceHeartbeatExpiry = time; },// stale heartbeat
                    };
                    list.Add(item);
                    expected.Add(new InvocationLogViewModel
                    {
                        id = item.FunctionInstanceId.ToString(),
                        status = "NeverFinished",
                        whenUtc = "2010-03-06T18:08:20Z", // starttime
                        duration = null
                    });
                }

                // No heartbeat (legacy example)
                {
                    time = time.AddMinutes(-1);
                    var item = new TestFunctionInstanceLogItem
                    {
                        FunctionInstanceId = Guid.NewGuid(),
                        FunctionName = Func1,
                        StartTime = time,  // Never Finished
                        LogOutput = "two",
                        OnRefresh = (me) => { } // No heart beat
                    };
                    list.Add(item);
                    expected.Add(new InvocationLogViewModel
                    {
                        id = item.FunctionInstanceId.ToString(),
                        status = "Running",
                        whenUtc = "2010-03-06T18:07:20Z", // starttime
                    });
                }

                foreach (var item in list)
                {
                    await writer.AddAsync(item);
                }

                await writer.FlushAsync();
            }

            CloudTableClient GetNewLoggingTableClient()
            {
                string storageString = "AzureWebJobsDashboard";
                var acs = Environment.GetEnvironmentVariable(storageString);
                if (acs == null)
                {
                    Assert.True(false, "Environment var " + storageString + " is not set. Should be set to an azure storage account connection string to use for testing.");
                }

                CloudStorageAccount account = CloudStorageAccount.Parse(acs);
                var client = account.CreateCloudTableClient();
                return client;
            }

            public class TestFunctionInstanceLogItem : FunctionInstanceLogItem
            {
                public Action<TestFunctionInstanceLogItem> OnRefresh;
                public override void Refresh(TimeSpan pollingFrequency)
                {
                    OnRefresh(this);
                }
            }

        }

    }
}


text:
using Igneel;
using Igneel.Graphics;
using Igneel.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace D3D9Testing
{
    //public class TestApplication : IgneelApplication
    //{
    //    int fps = -1;
    //    float baseTime;
    //    Form1 form1;
    //    public static bool UseFrameLines =true;

    //    public Form1 Form
    //    {
    //        get { return form1; }
    //        set { form1 = value; }
    //    }

    //    public override void Initialize()
    //    {
    //        ShaderRepository.SetupD3D10_SM40();

    //        form1 = new Form1();
    //        var gfactory = new IgneelD3D10.GraphicManager10();
    //        var pFactory = new Igneel.PhysX.PXPhysicManager();
    //        var iFactory = new IgneelDirectInput.DInputManager();

    //        Engine.InitializeEngine(form1.Handle, new GraphicDeviceDesc
    //        {
    //            Adapter = 0,
    //            BackBufferWidth = form1.screen.Width,
    //            BackBufferHeight = form1.screen.Height,
    //            BackBufferFormat = Format.R8G8B8A8_UNORM_SRGB,
    //            DepthStencilFormat = Format.D24_UNORM_S8_UINT,
    //            DriverType = GraphicDeviceType.Hardware,
    //            FullScreen = false,
    //            MSAA = new Multisampling(1, 0),
    //            WindowsHandle = form1.screen.Handle,
    //            Interval = PresentionInterval.Default
    //        });
    //        Engine.Presenter = new SingleViewPresenter();
    //        Engine.Presenter.Rendering += Presenter_Rendering;
    //        form1.screen.Resize += screen_Resize;

    //        form1.InitializeTests();
    //        base.Initialize();

    //        Application.Idle += Application_Idle;
    //        Application.Run(form1);
    //    }

    //    void Application_Idle(object sender, EventArgs e)
    //    {
    //        Engine.MainLoop();
    //    }

    //    void screen_Resize(object sender, EventArgs e)
    //    {
    //        GraphicDeviceFactory.Device.ResizeBackBuffer(form1.screen.Width, form1.screen.Height);
    //        if (SceneManager.Scene != null)
    //        {
    //            SceneManager.Scene.ActiveCamera.AspectRatio = (float)form1.screen.Width / (float)form1.screen.Height;
    //            SceneManager.Scene.ActiveCamera.CommitChanges();
    //        }

    //    }

    //    void Presenter_Rendering()
    //    {
    //        if (fps == -1)
    //        {
    //            fps = 0;
    //            baseTime = Engine.Time.Time;
    //        }
    //        else
    //        {
    //            float time = Engine.Time.Time;
    //            if ((time - baseTime) > 1.0f)
    //            {
    //                form1.fpsCounter.Text = "FPS : " + fps;
    //                fps = 0;
    //                baseTime = time;
    //            }
    //            fps++;
    //        }
    //    }
    //}
}


text:
package com.opengamma.strata.pricer.fxopt;

import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.currency.CurrencyAmount;
import com.opengamma.strata.basics.currency.CurrencyPair;
import com.opengamma.strata.basics.currency.MultiCurrencyAmount;
import com.opengamma.strata.basics.value.ValueDerivatives;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.collect.array.DoubleArray;
import com.opengamma.strata.market.sensitivity.PointSensitivityBuilder;
import com.opengamma.strata.pricer.DiscountFactors;
import com.opengamma.strata.pricer.ZeroRateSensitivity;
import com.opengamma.strata.pricer.impl.option.BlackBarrierPriceFormulaRepository;
import com.opengamma.strata.pricer.impl.option.BlackOneTouchAssetPriceFormulaRepository;
import com.opengamma.strata.pricer.impl.option.BlackOneTouchCashPriceFormulaRepository;
import com.opengamma.strata.pricer.rate.RatesProvider;
import com.opengamma.strata.product.fx.ResolvedFxSingle;
import com.opengamma.strata.product.fxopt.ResolvedFxSingleBarrierOption;
import com.opengamma.strata.product.fxopt.ResolvedFxVanillaOption;
import com.opengamma.strata.product.option.SimpleConstantContinuousBarrier;

/**
 * Pricer for FX barrier option products in Black-Scholes world.
 *

 * This function provides the ability to price an {@link ResolvedFxSingleBarrierOption}.
 *

 * All of the computation is be based on the counter currency of the underlying FX transaction.
 * For example, price, PV and risk measures of the product will be expressed in USD for an option on EUR/USD.
 */
public class BlackFxSingleBarrierOptionProductPricer {

  /**
   * Default implementation.
   */
  public static final BlackFxSingleBarrierOptionProductPricer DEFAULT = new BlackFxSingleBarrierOptionProductPricer();

  /**
   * Pricer for barrier option without rebate.
   */
  private static final BlackBarrierPriceFormulaRepository BARRIER_PRICER = new BlackBarrierPriceFormulaRepository();
  /**
   * Pricer for rebate.
   */
  private static final BlackOneTouchAssetPriceFormulaRepository ASSET_REBATE_PRICER =
      new BlackOneTouchAssetPriceFormulaRepository();
  /**
   * Pricer for rebate.
   */
  private static final BlackOneTouchCashPriceFormulaRepository CASH_REBATE_PRICER =
      new BlackOneTouchCashPriceFormulaRepository();

  /**
   * Creates an instance.
   */
  public BlackFxSingleBarrierOptionProductPricer() {
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the present value of the FX barrier option product.
   *

   * The present value of the product is the value on the valuation date.
   * It is expressed in the counter currency.
   *

   * The volatility used in this computation is the Black implied volatility at expiry time and strike.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the present value of the product
   */
  public CurrencyAmount presentValue(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    double price = price(option, ratesProvider, volatilities);
    ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption();
    return CurrencyAmount.of(underlyingOption.getCounterCurrency(), signedNotional(underlyingOption) * price);
  }

  /**
   * Calculates the price of the FX barrier option product.
   *

   * The price of the product is the value on the valuation date for one unit of the base currency
   * and is expressed in the counter currency. The price does not take into account the long/short flag.
   * See {@link #presentValue} for scaling and currency.
   *

   * The volatility used in this computation is the Black implied volatility at expiry time and strike.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the price of the product
   */
  public double price(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    validate(option, ratesProvider, volatilities);
    SimpleConstantContinuousBarrier barrier = (SimpleConstantContinuousBarrier) option.getBarrier();
    ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption();
    if (volatilities.relativeTime(underlyingOption.getExpiry()) < 0d) {
      return 0d;
    }
    ResolvedFxSingle underlyingFx = underlyingOption.getUnderlying();
    Currency ccyBase = underlyingFx.getBaseCurrencyPayment().getCurrency();
    Currency ccyCounter = underlyingFx.getCounterCurrencyPayment().getCurrency();
    CurrencyPair currencyPair = underlyingFx.getCurrencyPair();
    DiscountFactors baseDiscountFactors = ratesProvider.discountFactors(ccyBase);
    DiscountFactors counterDiscountFactors = ratesProvider.discountFactors(ccyCounter);

    double rateBase = baseDiscountFactors.zeroRate(underlyingFx.getPaymentDate());
    double rateCounter = counterDiscountFactors.zeroRate(underlyingFx.getPaymentDate());
    double costOfCarry = rateCounter - rateBase;
    double dfBase = baseDiscountFactors.discountFactor(underlyingFx.getPaymentDate());
    double dfCounter = counterDiscountFactors.discountFactor(underlyingFx.getPaymentDate());
    double todayFx = ratesProvider.fxRate(currencyPair);
    double strike = underlyingOption.getStrike();
    double forward = todayFx * dfBase / dfCounter;
    double volatility = volatilities.volatility(currencyPair, underlyingOption.getExpiry(), strike, forward);
    double timeToExpiry = volatilities.relativeTime(underlyingOption.getExpiry());
    double price = BARRIER_PRICER.price(
        todayFx, strike, timeToExpiry, costOfCarry, rateCounter, volatility, underlyingOption.getPutCall().isCall(), barrier);
    if (option.getRebate().isPresent()) {
      CurrencyAmount rebate = option.getRebate().get();
      double priceRebate = rebate.getCurrency().equals(ccyCounter) ?
          CASH_REBATE_PRICER.price(todayFx, timeToExpiry, costOfCarry, rateCounter, volatility, barrier.inverseKnockType()) :
          ASSET_REBATE_PRICER.price(todayFx, timeToExpiry, costOfCarry, rateCounter, volatility, barrier.inverseKnockType());
      price += priceRebate * rebate.getAmount() / Math.abs(underlyingFx.getBaseCurrencyPayment().getAmount());
    }
    return price;
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the present value sensitivity of the FX barrier option product.
   *

   * The present value sensitivity of the product is the sensitivity of {@link #presentValue} to
   * the underlying curves.
   *

   * The volatility is fixed in this sensitivity computation, i.e., sticky-strike.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the present value curve sensitivity of the product
   */
  public PointSensitivityBuilder presentValueSensitivityRatesStickyStrike(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption();
    if (volatilities.relativeTime(underlyingOption.getExpiry()) <= 0d) {
      return PointSensitivityBuilder.none();
    }
    ValueDerivatives priceDerivatives = priceDerivatives(option, ratesProvider, volatilities);
    ResolvedFxSingle underlyingFx = underlyingOption.getUnderlying();
    CurrencyPair currencyPair = underlyingFx.getCurrencyPair();
    double signedNotional = signedNotional(underlyingOption);
    double counterYearFraction =
        ratesProvider.discountFactors(currencyPair.getCounter()).relativeYearFraction(underlyingFx.getPaymentDate());
    ZeroRateSensitivity counterSensi = ZeroRateSensitivity.of(
        currencyPair.getCounter(),
        counterYearFraction,
        signedNotional * (priceDerivatives.getDerivative(2) + priceDerivatives.getDerivative(3)));
    double baseYearFraction =
        ratesProvider.discountFactors(currencyPair.getBase()).relativeYearFraction(underlyingFx.getPaymentDate());
    ZeroRateSensitivity baseSensi = ZeroRateSensitivity.of(
        currencyPair.getBase(),
        baseYearFraction,
        currencyPair.getCounter(),
        -priceDerivatives.getDerivative(3) * signedNotional);
    return counterSensi.combinedWith(baseSensi);
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the present value delta of the FX barrier option product.
   *

   * The present value delta is the first derivative of {@link #presentValue} with respect to spot.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the present value delta of the product
   */
  public CurrencyAmount presentValueDelta(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    double delta = delta(option, ratesProvider, volatilities);
    ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption();
    return CurrencyAmount.of(underlyingOption.getCounterCurrency(), signedNotional(underlyingOption) * delta);
  }

  /**
   * Calculates the delta of the FX barrier option product.
   *

   * The delta is the first derivative of {@link #price} with respect to spot.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the delta of the product
   */
  public double delta(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    if (volatilities.relativeTime(option.getUnderlyingOption().getExpiry()) < 0d) {
      return 0d;
    }
    ValueDerivatives priceDerivatives = priceDerivatives(option, ratesProvider, volatilities);
    return priceDerivatives.getDerivative(0);
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the present value gamma of the FX barrier option product.
   *

   * The present value gamma is the second derivative of {@link #presentValue} with respect to spot.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the present value gamma of the product
   */
  public CurrencyAmount presentValueGamma(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    double gamma = gamma(option, ratesProvider, volatilities);
    ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption();
    return CurrencyAmount.of(underlyingOption.getCounterCurrency(), signedNotional(underlyingOption) * gamma);
  }

  /**
   * Calculates the gamma of the FX barrier option product.
   *

   * The delta is the second derivative of {@link #price} with respect to spot.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the gamma of the product
   */
  public double gamma(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    ValueDerivatives priceDerivatives = priceDerivatives(option, ratesProvider, volatilities);
    return priceDerivatives.getDerivative(6);
  }

  //-------------------------------------------------------------------------
  /**
   * Computes the present value sensitivity to the black volatility used in the pricing.
   *

   * The result is a single sensitivity to the volatility used. This is also called Black vega.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the present value sensitivity
   */
  public PointSensitivityBuilder presentValueSensitivityModelParamsVolatility(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption();
    if (volatilities.relativeTime(underlyingOption.getExpiry()) <= 0d) {
      return PointSensitivityBuilder.none();
    }
    ValueDerivatives priceDerivatives = priceDerivatives(option, ratesProvider, volatilities);
    ResolvedFxSingle underlyingFx = underlyingOption.getUnderlying();
    CurrencyPair currencyPair = underlyingFx.getCurrencyPair();
    Currency ccyBase = currencyPair.getBase();
    Currency ccyCounter = currencyPair.getCounter();
    double dfBase = ratesProvider.discountFactor(ccyBase, underlyingFx.getPaymentDate());
    double dfCounter = ratesProvider.discountFactor(ccyCounter, underlyingFx.getPaymentDate());
    double todayFx = ratesProvider.fxRate(currencyPair);
    double forward = todayFx * dfBase / dfCounter;
    return FxOptionSensitivity.of(
        volatilities.getName(),
        currencyPair,
        volatilities.relativeTime(underlyingOption.getExpiry()),
        underlyingOption.getStrike(),
        forward,
        ccyCounter,
        priceDerivatives.getDerivative(4) * signedNotional(underlyingOption));
  }

  /**
   * Calculates the vega of the FX barrier option product.
   *

   * The delta is the first derivative of {@link #price} with respect to Black volatility.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the vega of the product
   */
  public double vega(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    ValueDerivatives priceDerivatives = priceDerivatives(option, ratesProvider, volatilities);
    return priceDerivatives.getDerivative(4);
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the present value theta of the FX barrier option product.
   *

   * The present value theta is the negative of the first derivative of {@link #presentValue} with time parameter.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the present value theta of the product
   */
  public CurrencyAmount presentValueTheta(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    double theta = theta(option, ratesProvider, volatilities);
    ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption();
    return CurrencyAmount.of(underlyingOption.getCounterCurrency(), signedNotional(underlyingOption) * theta);
  }

  /**
   * Calculates the theta of the FX barrier option product.
   *

   * The theta is the negative of the first derivative of {@link #price} with respect to time parameter.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the theta of the product
   */
  public double theta(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    ValueDerivatives priceDerivatives = priceDerivatives(option, ratesProvider, volatilities);
    return -priceDerivatives.getDerivative(5);
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the currency exposure of the FX barrier option product.
   *
   * @param option  the option product
   * @param ratesProvider  the rates provider
   * @param volatilities  the Black volatility provider
   * @return the currency exposure
   */
  public MultiCurrencyAmount currencyExposure(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption();
    if (volatilities.relativeTime(underlyingOption.getExpiry()) < 0d) {
      return MultiCurrencyAmount.empty();
    }
    ValueDerivatives priceDerivatives = priceDerivatives(option, ratesProvider, volatilities);
    double price = priceDerivatives.getValue();
    double delta = priceDerivatives.getDerivative(0);
    CurrencyPair currencyPair = underlyingOption.getUnderlying().getCurrencyPair();
    double todayFx = ratesProvider.fxRate(currencyPair);
    double signedNotional = signedNotional(underlyingOption);
    CurrencyAmount domestic = CurrencyAmount.of(currencyPair.getCounter(), (price - delta * todayFx) * signedNotional);
    CurrencyAmount foreign = CurrencyAmount.of(currencyPair.getBase(), delta * signedNotional);
    return MultiCurrencyAmount.of(domestic, foreign);
  }

  //-------------------------------------------------------------------------
  //  The derivatives are [0] spot, [1] strike, [2] rate, [3] cost-of-carry, [4] volatility, [5] timeToExpiry, [6] spot twice
  private ValueDerivatives priceDerivatives(
      ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    validate(option, ratesProvider, volatilities);
    SimpleConstantContinuousBarrier barrier = (SimpleConstantContinuousBarrier) option.getBarrier();
    ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption();
    double[] derivatives = new double[7];
    if (volatilities.relativeTime(underlyingOption.getExpiry()) < 0d) {
      return ValueDerivatives.of(0d, DoubleArray.ofUnsafe(derivatives));
    }
    ResolvedFxSingle underlyingFx = underlyingOption.getUnderlying();
    CurrencyPair currencyPair = underlyingFx.getCurrencyPair();
    Currency ccyBase = currencyPair.getBase();
    Currency ccyCounter = currencyPair.getCounter();
    DiscountFactors baseDiscountFactors = ratesProvider.discountFactors(ccyBase);
    DiscountFactors counterDiscountFactors = ratesProvider.discountFactors(ccyCounter);

    double rateBase = baseDiscountFactors.zeroRate(underlyingFx.getPaymentDate());
    double rateCounter = counterDiscountFactors.zeroRate(underlyingFx.getPaymentDate());
    double costOfCarry = rateCounter - rateBase;
    double dfBase = baseDiscountFactors.discountFactor(underlyingFx.getPaymentDate());
    double dfCounter = counterDiscountFactors.discountFactor(underlyingFx.getPaymentDate());
    double todayFx = ratesProvider.fxRate(currencyPair);
    double strike = underlyingOption.getStrike();
    double forward = todayFx * dfBase / dfCounter;
    double volatility = volatilities.volatility(currencyPair, underlyingOption.getExpiry(), strike, forward);
    double timeToExpiry = volatilities.relativeTime(underlyingOption.getExpiry());
    ValueDerivatives valueDerivatives = BARRIER_PRICER.priceAdjoint(
        todayFx, strike, timeToExpiry, costOfCarry, rateCounter, volatility, underlyingOption.getPutCall().isCall(), barrier);
    if (!option.getRebate().isPresent()) {
      return valueDerivatives;
    }
    CurrencyAmount rebate = option.getRebate().get();
    ValueDerivatives valueDerivativesRebate = rebate.getCurrency().equals(ccyCounter) ?
        CASH_REBATE_PRICER.priceAdjoint(todayFx, timeToExpiry, costOfCarry, rateCounter, volatility, barrier.inverseKnockType()) :
        ASSET_REBATE_PRICER.priceAdjoint(todayFx, timeToExpiry, costOfCarry, rateCounter, volatility, barrier.inverseKnockType());
    double rebateRate = rebate.getAmount() / Math.abs(underlyingFx.getBaseCurrencyPayment().getAmount());
    double price = valueDerivatives.getValue() + rebateRate * valueDerivativesRebate.getValue();
    derivatives[0] = valueDerivatives.getDerivative(0) + rebateRate * valueDerivativesRebate.getDerivative(0);
    derivatives[1] = valueDerivatives.getDerivative(1);
    for (int i = 2; i < 7; ++i) {
      derivatives[i] = valueDerivatives.getDerivative(i) + rebateRate * valueDerivativesRebate.getDerivative(i - 1);
    }
    return ValueDerivatives.of(price, DoubleArray.ofUnsafe(derivatives));
  }

  //-------------------------------------------------------------------------
  private void validate(ResolvedFxSingleBarrierOption option,
      RatesProvider ratesProvider,
      BlackFxOptionVolatilities volatilities) {

    ArgChecker.isTrue(option.getBarrier() instanceof SimpleConstantContinuousBarrier,
        "Barrier should be SimpleConstantContinuousBarrier");
    ArgChecker.isTrue(ratesProvider.getValuationDate().isEqual(volatilities.getValuationDateTime().toLocalDate()),
        "Volatility and rate data must be for the same date");
  }

  // signed notional amount to computed present value and value Greeks
  private double signedNotional(ResolvedFxVanillaOption option) {
    return (option.getLongShort().isLong() ? 1d : -1d) *
        Math.abs(option.getUnderlying().getBaseCurrencyPayment().getAmount());
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>LagrangianMultivariate</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.drip.function.rdtor1

Class LagrangianMultivariate

java.lang.Object

org.drip.function.definition.RdToR1

org.drip.function.rdtor1.LagrangianMultivariate

public class LagrangianMultivariate
extends RdToR1

LagrangianMultivariate implements an R^d To R^1 Multivariate Function along with the specified Set of
        Equality Constraints.

Author:

Lakshmi Krishnamurthy

Constructor Summary

Constructors

Constructor and Description

LagrangianMultivariate(RdToR1 RdToR1Objective,
                      RdToR1[] aRdToR1EqualityConstraint)

LagrangianMultivariate Constructor

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

int
constraintFunctionDimension()

Retrieve the Constraint Function Dimension

RdToR1[]
constraintFunctions()

Retrieve the Array of the Constraint R^d To R^1 Function Instances

int
dimension()

Retrieve the Dimension of the Input Variate

double
evaluate(double[] adblVariate)

Evaluate for the given Input Variates

double[][]
hessian(double[] adblVariate)

Evaluate The Hessian for the given Input Variates

double[]
jacobian(double[] adblVariate)

Evaluate the Jacobian for the given Input Variates

RdToR1
objectiveFunction()

Retrieve the Objective R^d To R^1 Function Instance

int
objectiveFunctionDimension()

Retrieve the Objective Function Dimension

Methods inherited from class org.drip.function.definition.RdToR1

derivative, differential, gradient, gradientModulus, gradientModulusFunction, integrate, maxima, minima, ValidateInput

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

LagrangianMultivariate

public LagrangianMultivariate(RdToR1 RdToR1Objective,
                              RdToR1[] aRdToR1EqualityConstraint)
                       throws java.lang.Exception

LagrangianMultivariate Constructor

Parameters:

RdToR1Objective - The Objective Function

aRdToR1EqualityConstraint - Array of Equality Constraint Functions

Throws:

java.lang.Exception - Thrown if the Inputs are Invalid

Method Detail

objectiveFunction

public RdToR1 objectiveFunction()

Retrieve the Objective R^d To R^1 Function Instance

Returns:

The Objective R^d To R^1 Function Instance

constraintFunctions

public RdToR1[] constraintFunctions()

Retrieve the Array of the Constraint R^d To R^1 Function Instances

Returns:

The Array of Constraint R^d To R^1 Function Instances

objectiveFunctionDimension

public int objectiveFunctionDimension()

Retrieve the Objective Function Dimension

Returns:

The Objective Function Dimension

constraintFunctionDimension

public int constraintFunctionDimension()

Retrieve the Constraint Function Dimension

Returns:

The Constraint Function Dimension

dimension

public int dimension()

Description copied from class: RdToR1

Retrieve the Dimension of the Input Variate

Specified by:

dimension in class RdToR1

Returns:

The Dimension of the Input Variate

evaluate

public double evaluate(double[] adblVariate)
                throws java.lang.Exception

Description copied from class: RdToR1

Evaluate for the given Input Variates

Specified by:

evaluate in class RdToR1

Parameters:

adblVariate - Array of Input Variates

Returns:

The Calculated Value

Throws:

java.lang.Exception - Thrown if the Evaluation cannot be done

jacobian

public double[] jacobian(double[] adblVariate)

Description copied from class: RdToR1

Evaluate the Jacobian for the given Input Variates

Overrides:

jacobian in class RdToR1

Parameters:

adblVariate - Array of Input Variates

Returns:

The Jacobian Array

hessian

public double[][] hessian(double[] adblVariate)

Description copied from class: RdToR1

Evaluate The Hessian for the given Input Variates

Overrides:

hessian in class RdToR1

Parameters:

adblVariate - Array of Input Variates

Returns:

The Hessian Matrix

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
{% load i18n %}
{% load url from future %}
var Bottom_bar = '
{% if groups %}<button id="discuss">{% trans "Discuss" %}</button><button id="click-into-group">{% trans "Group" %} >></button>{% endif %}
';
$('#wrapper').append(Bottom_bar);
$('#main-panel').css('margin-bottom', $('#bottom-bar').outerHeight() + 2);

{% if groups %}
function getAndHandleDiscussions(data_html) {
    $('#discussions-to-grp').html(data_html).css({'max-height': parseInt($(window).height() * 0.9 - $('#bottom-bar').height() - $('#discuss-to-group-caret').height() - $('#discuss-to-group-form').outerHeight())}).removeClass('hide'); // 'parseInt' to fix '.msg-main top border missing when the ul's max-height is xxx.5px'
    {% include 'group/msg_js.html' %}
}
$('#discuss').click(function() {
    var popup = $('#discuss-to-group'),
        caret = $('#discuss-to-group-caret'),
        form = $('#discuss-to-group-form'),
        path = '{{ path }}';

    // for repo.html: when get dir data with ajax
    if ($('#repo-file-list').length > 0) {
        path = cur_path;
        $('[name="path"]', form).val(path);
        // modify attachment dir name
        $('#discuss-to-group-form .att-name').html($('#cur-dir-name').html());
    }

    if (popup.hasClass('hide')) {
        popup.removeClass('hide');
        caret.removeClass('hide');
        caret.css({'left': $(this).offset().left});
        $.ajax({
            url: form.attr('action'),
            dataType: 'json',
            data: {
                'repo_id': '{{ repo.id }}',
                'path': path
            },
            success: function(data) {
                getAndHandleDiscussions(data['html']);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                var err_str = '';
                if (jqXHR.responseText) {
                    err_str = $.parseJSON(jqXHR.responseText).error;
                    feedback(err_str, 'error');
                }
            }
        });
    } else {
        popup.addClass('hide');
        caret.addClass('hide');
    }
});

$(document).click(function(e) {
    var target = e.target || event.srcElement;
    if (!$('#discuss, #discuss-to-group, #discuss-to-group-caret').is(target) && !($('#discuss, #discuss-to-group, #discuss-to-group-caret').find('*').is(target))) {
        $('#discuss-to-group, #discuss-to-group-caret').addClass('hide');
    }
});

$('#discuss-submit').click(function() {
    var form = $('#discuss-to-group-form'),
        form_id = form.attr('id');

    if (form.find('.checkbox-checked').length == 0) {
        apply_form_error(form_id, "{% trans "Please select at least 1 group." %}");
        return false;
    }

    if (!$.trim($('#discuss-to-group-form .input').val())) {
        apply_form_error(form_id, "{% trans "Please input a discussion." %}");
        return false;
    }
    form.find('.error').addClass('hide');

    var groups = [];
    form.find('.checkbox-checked .checkbox-orig').each(function() {
        groups.push($(this).val());
    });

    $.ajax({
        url: form.attr('action'),
        type: 'POST',
        dataType: 'json',
        beforeSend: prepareCSRFToken,
        traditional: true,
        data: {
            'groups': groups,
            'message': $('[name="message"]', form).val(),
            'repo_id': '{{ repo.id }}',
            'path': $('[name="path"]', form).val(),
            'attach_type': $('[name="attach_type"]', form).val()
        },
        success: function(data) {
            if(data['success']) {
                feedback(data['success'], 'success');
                getAndHandleDiscussions(data['html']);
                form.find('.input').val('');
            }
            if(data['error']) {
                feedback(data['error'], 'error');
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            var err_str = '';
            if (jqXHR.responseText) {
                err_str = $.parseJSON(jqXHR.responseText).error;
            } else {
                err_str = "{% trans "Failed. Please check the network." %}";
            }
            apply_form_error(form_id, err_str);
        }
    });
    return false;
});

$('#main').append('
{{ repo_group_str|escapejs }}

');
$('#click-into-group').click(function() {
    {% if groups|length == 1 %}
    // only one group, just turn to group page
    {% for group in groups %}
    location.href= "{% url 'group_info' group.id %}";
    {% endfor %}

    {% else %}
    // more than one group, then let user choose
    if ($('#to-group').hasClass('hide')) {
        $('#to-group, #to-group-caret').removeClass('hide');
        $('#to-group-caret').css('left', $('#click-into-group').offset().left + $('#click-into-group').width()/3);
        if ($('#to-group').offset().left > $('#click-into-group').offset().left) {
            $('#to-group').css('left', $('#click-into-group').offset().left);
        }
    } else {
        $('#to-group, #to-group-caret').addClass('hide');
    }
    {% endif %}
});
$(document).click(function(e) {
    var target = e.target || event.srcElement;
    if (!$('#click-into-group, #to-group, #to-group-caret').is(target) && !($('#to-group, #to-group-caret').find('*').is(target))) {
        $('#to-group, #to-group-caret').addClass('hide');
    }
});
{% endif %}

$(function() {
    var btn_height = $('#bottom-bar').outerHeight();
    $('#discuss-to-group-caret, #to-group-caret').css({'bottom': btn_height});
    $('#to-group, #discuss-to-group').css({'bottom': btn_height + $('.outer-caret').outerHeight()});
});


text:
#ifndef AUTOSUBSYS_WEIGHTS_H
#define AUTOSUBSYS_WEIGHTS_H

#ifndef _autosubsys_macros_h
#include <autosubsys-macros.h>
#endif

/*
 * A weight consists of a relation and an integer weight that represents
 * how much it should factor in to the binding calculations. The decomposer
 * class gets passed an array of them when it starts up, and all calculations
 * are done using that array. This makes it theoretically possible to work
 * on any relations without recompiling. In practice, since the relations
 * are installed by name in Entity.h.C, that won't work very well.
 */

struct weight {
  bool outgoing;
  int m_weight;
  int count;
};

extern weight defaultweights[NWEIGHTS];
extern int threshold;
extern int num_subsys;

#endif

/*
   START-LOG-------------------------------------------

   $Log: autosubsys-weights.h  $
   Revision 1.5 1996/04/29 13:52:22EDT kws
   Renaming 'weight' member of weight struct
 * Revision 1.2.1.2  1992/10/09  20:22:22  swu
 * *** empty log message ***
 *

   END-LOG---------------------------------------------

*/


text:
package io.virtdata.libbasics.shared.conversions.from_string;

import io.virtdata.annotations.Categories;
import io.virtdata.annotations.Category;
import io.virtdata.annotations.ThreadSafeMapper;

import java.util.function.Function;

@ThreadSafeMapper
@Categories({Category.conversion})
public class ToInt implements Function<String,Integer> {

    @Override
    public Integer apply(String input) {
        return Integer.valueOf(input);
    }
}


text:
<!---
Copyright 2015 The AMP HTML Authors. All Rights Reserved.

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.
-->

# AdvertServe

## Example

```html
<amp-ad width=300 height=250
      type="advertserve"
      data-client="tester"
      data-pid=0
      data-zid=68>
  <div placeholder>Loading ad.</div>
  <div fallback>Ad could not be loaded.</div>
</amp-ad>
```

## Configuration

For semantics of configuration, please see ad network documentation.

Supported parameters:

- data-client: client id
- data-pid: publisher id
- data-zid: zone id


text:
#include <rtthread.h>

#include "lwip/sys.h"
#include "lwip/opt.h"
#include "lwip/stats.h"
#include "lwip/err.h"
#include "arch/sys_arch.h"
#include "lwip/debug.h"
#include "lwip/netif.h"
#include "lwip/tcpip.h"
#include "netif/ethernetif.h"
#include "lwip/sio.h"

#include <string.h>

static err_t netif_device_init(struct netif *netif)
{
    struct eth_device *ethif;

    ethif = (struct eth_device *)netif->state;
    if (ethif != RT_NULL)
    {
        rt_device_t device;

        /* get device object */
        device = (rt_device_t) ethif;
        if (rt_device_init(device) != RT_EOK)
        {
            return ERR_IF;
        }

        /* copy device flags to netif flags */
        netif->flags = ethif->flags;

        return ERR_OK;
    }

    return ERR_IF;
}

static void tcpip_init_done_callback(void *arg)
{
    rt_device_t device;
    struct eth_device *ethif;
    struct ip_addr ipaddr, netmask, gw;
    struct rt_list_node* node;
    struct rt_object* object;
    struct rt_object_information *information;

    extern struct rt_object_information rt_object_container[];

    LWIP_ASSERT("invalid arg.\n",arg);

    IP4_ADDR(&gw, 0,0,0,0);
    IP4_ADDR(&ipaddr, 0,0,0,0);
    IP4_ADDR(&netmask, 0,0,0,0);

    /* enter critical */
    rt_enter_critical();

    /* for each network interfaces */
    information = &rt_object_container[RT_Object_Class_Device];
    for (node = information->object_list.next;
         node != &(information->object_list);
         node = node->next)
    {
        object = rt_list_entry(node, struct rt_object, list);
        device = (rt_device_t)object;
        if (device->type == RT_Device_Class_NetIf)
        {
            ethif = (struct eth_device *)device;

            /* leave critical */
            rt_exit_critical();

            netif_add(ethif->netif, &ipaddr, &netmask, &gw,
                      ethif, netif_device_init, tcpip_input);

            if (netif_default == RT_NULL)
                netif_set_default(ethif->netif);

#if LWIP_DHCP
            if (ethif->flags & NETIF_FLAG_DHCP)
            {
                /* if this interface uses DHCP, start the DHCP client */
                dhcp_start(ethif->netif);
            }
            else
#endif
            {
                /* set interface up */
                netif_set_up(ethif->netif);
            }

#ifdef LWIP_NETIF_LINK_CALLBACK
            netif_set_link_up(ethif->netif);
#endif

            /* enter critical */
            rt_enter_critical();
        }
    }

    /* leave critical */
    rt_exit_critical();
    rt_sem_release((rt_sem_t)arg);
}

/**
 * LwIP system initialization
 */
int lwip_system_init(void)
{
    rt_err_t rc;
    struct rt_semaphore done_sem;

    /* set default netif to NULL */
    netif_default = RT_NULL;

    rc = rt_sem_init(&done_sem, "done", 0, RT_IPC_FLAG_FIFO);

    if (rc != RT_EOK)
    {
        LWIP_ASSERT("Failed to create semaphore", 0);

        return -1;
    }

    tcpip_init(tcpip_init_done_callback, (void *)&done_sem);

    /* waiting for initialization done */
    if (rt_sem_take(&done_sem, RT_WAITING_FOREVER) != RT_EOK)
    {
        rt_sem_detach(&done_sem);

        return -1;
    }
    rt_sem_detach(&done_sem);

    /* set default ip address */
#if !LWIP_DHCP
    if (netif_default != RT_NULL)
    {
        struct ip_addr ipaddr, netmask, gw;

        IP4_ADDR(&ipaddr, RT_LWIP_IPADDR0, RT_LWIP_IPADDR1, RT_LWIP_IPADDR2, RT_LWIP_IPADDR3);
        IP4_ADDR(&gw, RT_LWIP_GWADDR0, RT_LWIP_GWADDR1, RT_LWIP_GWADDR2, RT_LWIP_GWADDR3);
        IP4_ADDR(&netmask, RT_LWIP_MSKADDR0, RT_LWIP_MSKADDR1, RT_LWIP_MSKADDR2, RT_LWIP_MSKADDR3);

        netifapi_netif_set_addr(netif_default, &ipaddr, &netmask, &gw);
    }
#endif
	return 0;
}
INIT_COMPONENT_EXPORT(lwip_system_init);

void sys_init(void)
{
    /* nothing on RT-Thread porting */
}

void lwip_sys_init(void)
{
    lwip_system_init();
}

err_t sys_sem_new(sys_sem_t *sem, u8_t count)
{
    static unsigned short counter = 0;
    char tname[RT_NAME_MAX];
    sys_sem_t tmpsem;

    RT_DEBUG_NOT_IN_INTERRUPT;

    rt_snprintf(tname, RT_NAME_MAX, "%s%d", SYS_LWIP_SEM_NAME, counter);
    counter ++;

    tmpsem = rt_sem_create(tname, count, RT_IPC_FLAG_FIFO);
    if (tmpsem == RT_NULL)
        return ERR_MEM;
    else
    {
        *sem = tmpsem;

        return ERR_OK;
    }
}

void sys_sem_free(sys_sem_t *sem)
{
    RT_DEBUG_NOT_IN_INTERRUPT;
    rt_sem_delete(*sem);
}

void sys_sem_signal(sys_sem_t *sem)
{
    rt_sem_release(*sem);
}

u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout)
{
    rt_err_t ret;
    s32_t t;
    u32_t tick;

    RT_DEBUG_NOT_IN_INTERRUPT;

    /* get the begin tick */
    tick = rt_tick_get();
    if (timeout == 0)
        t = RT_WAITING_FOREVER;
    else
    {
        /* convert msecond to os tick */
        if (timeout < (1000/RT_TICK_PER_SECOND))
            t = 1;
        else
            t = timeout / (1000/RT_TICK_PER_SECOND);
    }

    ret = rt_sem_take(*sem, t);

    if (ret == -RT_ETIMEOUT)
        return SYS_ARCH_TIMEOUT;
    else
    {
        if (ret == RT_EOK)
            ret = 1;
    }

    /* get elapse msecond */
    tick = rt_tick_get() - tick;

    /* convert tick to msecond */
    tick = tick * (1000 / RT_TICK_PER_SECOND);
    if (tick == 0)
        tick = 1;

    return tick;
}

#ifndef sys_sem_valid
/** Check if a semaphore is valid/allocated:
 *  return 1 for valid, 0 for invalid
 */
int sys_sem_valid(sys_sem_t *sem)
{
    return (int)(*sem);
}
#endif

#ifndef sys_sem_set_invalid
/** Set a semaphore invalid so that sys_sem_valid returns 0
 */
void sys_sem_set_invalid(sys_sem_t *sem)
{
    *sem = RT_NULL;
}
#endif

/* ====================== Mutex ====================== */

/** Create a new mutex
 * @param mutex pointer to the mutex to create
 * @return a new mutex
 */
err_t sys_mutex_new(sys_mutex_t *mutex)
{
    static unsigned short counter = 0;
    char tname[RT_NAME_MAX];
    sys_mutex_t tmpmutex;

    RT_DEBUG_NOT_IN_INTERRUPT;

    rt_snprintf(tname, RT_NAME_MAX, "%s%d", SYS_LWIP_MUTEX_NAME, counter);
    counter ++;

    tmpmutex = rt_mutex_create(tname, RT_IPC_FLAG_FIFO);
    if (tmpmutex == RT_NULL)
        return ERR_MEM;
    else
    {
        *mutex = tmpmutex;

        return ERR_OK;
    }
}

/** Lock a mutex
 * @param mutex the mutex to lock
 */
void sys_mutex_lock(sys_mutex_t *mutex)
{
    RT_DEBUG_NOT_IN_INTERRUPT;
    rt_mutex_take(*mutex, RT_WAITING_FOREVER);

    return;
}

/** Unlock a mutex
 * @param mutex the mutex to unlock
 */
void sys_mutex_unlock(sys_mutex_t *mutex)
{
    rt_mutex_release(*mutex);
}

/** Delete a semaphore
 * @param mutex the mutex to delete
 */
void sys_mutex_free(sys_mutex_t *mutex)
{
    RT_DEBUG_NOT_IN_INTERRUPT;

    rt_mutex_delete(*mutex);
}

#ifndef sys_mutex_valid
/** Check if a mutex is valid/allocated:
 *  return 1 for valid, 0 for invalid
 */
int sys_mutex_valid(sys_mutex_t *mutex)
{
    return (int)(*mutex);
}
#endif

#ifndef sys_mutex_set_invalid
/** Set a mutex invalid so that sys_mutex_valid returns 0
 */
void sys_mutex_set_invalid(sys_mutex_t *mutex)
{
    *mutex = RT_NULL;
}
#endif

/* ====================== Mailbox ====================== */

err_t sys_mbox_new(sys_mbox_t *mbox, int size)
{
    static unsigned short counter = 0;
    char tname[RT_NAME_MAX];
    sys_mbox_t tmpmbox;

    RT_DEBUG_NOT_IN_INTERRUPT;

    rt_snprintf(tname, RT_NAME_MAX, "%s%d", SYS_LWIP_MBOX_NAME, counter);
    counter ++;

    tmpmbox = rt_mb_create(tname, size, RT_IPC_FLAG_FIFO);
    if (tmpmbox != RT_NULL)
    {
        *mbox = tmpmbox;

        return ERR_OK;
    }

    return ERR_MEM;
}

void sys_mbox_free(sys_mbox_t *mbox)
{
    RT_DEBUG_NOT_IN_INTERRUPT;

    rt_mb_delete(*mbox);

    return;
}

/** Post a message to an mbox - may not fail
 * -> blocks if full, only used from tasks not from ISR
 * @param mbox mbox to posts the message
 * @param msg message to post (ATTENTION: can be NULL)
 */
void sys_mbox_post(sys_mbox_t *mbox, void *msg)
{
    RT_DEBUG_NOT_IN_INTERRUPT;

    rt_mb_send_wait(*mbox, (rt_uint32_t)msg, RT_WAITING_FOREVER);

    return;
}

err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg)
{
    if (rt_mb_send(*mbox, (rt_uint32_t)msg) == RT_EOK)
        return ERR_OK;

    return ERR_MEM;
}

/** Wait for a new message to arrive in the mbox
 * @param mbox mbox to get a message from
 * @param msg pointer where the message is stored
 * @param timeout maximum time (in milliseconds) to wait for a message
 * @return time (in milliseconds) waited for a message, may be 0 if not waited
           or SYS_ARCH_TIMEOUT on timeout
 *         The returned time has to be accurate to prevent timer jitter!
 */
u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout)
{
    rt_err_t ret;
    s32_t t;
    u32_t tick;

    RT_DEBUG_NOT_IN_INTERRUPT;

    /* get the begin tick */
    tick = rt_tick_get();

    if(timeout == 0)
        t = RT_WAITING_FOREVER;
    else
    {
        /* convirt msecond to os tick */
        if (timeout < (1000/RT_TICK_PER_SECOND))
            t = 1;
        else
            t = timeout / (1000/RT_TICK_PER_SECOND);
    }

    ret = rt_mb_recv(*mbox, (rt_uint32_t *)msg, t);

    if(ret == -RT_ETIMEOUT)
        return SYS_ARCH_TIMEOUT;
    else
    {
        LWIP_ASSERT("rt_mb_recv returned with error!", ret == RT_EOK);
    }

    /* get elapse msecond */
    tick = rt_tick_get() - tick;

    /* convert tick to msecond */
    tick = tick * (1000 / RT_TICK_PER_SECOND);
    if (tick == 0)
        tick = 1;

    return tick;
}

/** Wait for a new message to arrive in the mbox
 * @param mbox mbox to get a message from
 * @param msg pointer where the message is stored
 * @param timeout maximum time (in milliseconds) to wait for a message
 * @return 0 (milliseconds) if a message has been received
 *         or SYS_MBOX_EMPTY if the mailbox is empty
 */
u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg)
{
    int ret;

    ret = rt_mb_recv(*mbox, (rt_uint32_t *)msg, 0);

    if(ret == -RT_ETIMEOUT)
        return SYS_ARCH_TIMEOUT;
    else
    {
        if (ret == RT_EOK)
            ret = 1;
    }

    return ret;
}

#ifndef sys_mbox_valid
/** Check if an mbox is valid/allocated:
 *  return 1 for valid, 0 for invalid
 */
int sys_mbox_valid(sys_mbox_t *mbox)
{
    return (int)(*mbox);
}
#endif

#ifndef sys_mbox_set_invalid
/** Set an mbox invalid so that sys_mbox_valid returns 0
 */
void sys_mbox_set_invalid(sys_mbox_t *mbox)
{
    *mbox = RT_NULL;
}
#endif

/* ====================== System ====================== */

sys_thread_t sys_thread_new(const char    *name,
                            lwip_thread_fn thread,
                            void          *arg,
                            int            stacksize,
                            int            prio)
{
    rt_thread_t t;

    RT_DEBUG_NOT_IN_INTERRUPT;

    /* create thread */
    t = rt_thread_create(name, thread, arg, stacksize, prio, 20);
    RT_ASSERT(t != RT_NULL);

    /* startup thread */
    rt_thread_startup(t);

    return t;
}

sys_prot_t sys_arch_protect(void)
{
    rt_base_t level;

    /* disable interrupt */
    level = rt_hw_interrupt_disable();

    return level;
}

void sys_arch_unprotect(sys_prot_t pval)
{
    /* enable interrupt */
    rt_hw_interrupt_enable(pval);

    return;
}

void sys_arch_assert(const char *file, int line)
{
    rt_kprintf("\nAssertion: %d in %s, thread %s\n",
               line, file, rt_thread_self()->name);
    RT_ASSERT(0);
}

u32_t sys_jiffies(void)
{
    return rt_tick_get();
}

#ifdef RT_LWIP_PPP
u32_t sio_read(sio_fd_t fd, u8_t *buf, u32_t size)
{
    u32_t len;

    RT_ASSERT(fd != RT_NULL);

    len = rt_device_read((rt_device_t)fd, 0, buf, size);
    if (len <= 0)
        return 0;

    return len;
}

u32_t sio_write(sio_fd_t fd, u8_t *buf, u32_t size)
{
    RT_ASSERT(fd != RT_NULL);

    return rt_device_write((rt_device_t)fd, 0, buf, size);
}

void sio_read_abort(sio_fd_t fd)
{
    rt_kprintf("read_abort\n");
}

void ppp_trace(int level, const char *format, ...)
{
    va_list args;
    rt_size_t length;
    static char rt_log_buf[RT_CONSOLEBUF_SIZE];

    va_start(args, format);
    length = rt_vsprintf(rt_log_buf, format, args);
    rt_device_write((rt_device_t)rt_console_get_device(), 0, rt_log_buf, length);
    va_end(args);
}
#endif

/*
 * export bsd socket symbol for RT-Thread Application Module
 */
#if LWIP_SOCKET
#include <lwip/sockets.h>
RTM_EXPORT(lwip_accept);
RTM_EXPORT(lwip_bind);
RTM_EXPORT(lwip_shutdown);
RTM_EXPORT(lwip_getpeername);
RTM_EXPORT(lwip_getsockname);
RTM_EXPORT(lwip_getsockopt);
RTM_EXPORT(lwip_setsockopt);
RTM_EXPORT(lwip_close);
RTM_EXPORT(lwip_connect);
RTM_EXPORT(lwip_listen);
RTM_EXPORT(lwip_recv);
RTM_EXPORT(lwip_read);
RTM_EXPORT(lwip_recvfrom);
RTM_EXPORT(lwip_send);
RTM_EXPORT(lwip_sendto);
RTM_EXPORT(lwip_socket);
RTM_EXPORT(lwip_write);
RTM_EXPORT(lwip_select);
RTM_EXPORT(lwip_ioctl);
RTM_EXPORT(lwip_fcntl);

#if LWIP_DNS
#include <lwip/netdb.h>
RTM_EXPORT(lwip_gethostbyname);
RTM_EXPORT(lwip_gethostbyname_r);
RTM_EXPORT(lwip_freeaddrinfo);
RTM_EXPORT(lwip_getaddrinfo);
#endif

#endif

#if LWIP_DHCP
#include <lwip/dhcp.h>
RTM_EXPORT(dhcp_start);
RTM_EXPORT(dhcp_renew);
RTM_EXPORT(dhcp_stop);
#endif

#if LWIP_NETIF_API
#include <lwip/netifapi.h>
RTM_EXPORT(netifapi_netif_set_addr);
#endif


text:
* * *

[<img src="{{site.baseurl}}/img/public.png" class="pull-left img-big" alt="The power of sitespeed.io" width="150" height="150">]({{site.baseurl}}/documentation/sitespeed.io/performance-dashboard/#cost)

Sitespeed.io is Open Source and totally free. But what does it cost to have an instance of sitespeed.io up and running?

If you don't run on your own servers, we recommend running an [AWS](https://aws.amazon.com/) c4.large, storing the data at S3. On one instance you can run something like 80000+ runs per month for a total cost of $695 per year.

Look more into the details [here]({{site.baseurl}}/documentation/sitespeed.io/performance-dashboard/#cost).


text:
package org.onlab.util;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * (Somewhat) predictable ExecutorService.
 *

 * ExecutorService which behaves similar to the one created by
 * {@link Executors#newFixedThreadPool(int, ThreadFactory)},
 * but assigns command to specific thread based on
 * it's {@link PickyTask#hint()}, {@link Object#hashCode()}, or hint value explicitly
 * specified when the command was passed to this {@link PredictableExecutor}.
 */
public class PredictableExecutor
        extends AbstractExecutorService
        implements ExecutorService {

    private final List<ExecutorService> backends;

    /**
     * Creates {@link PredictableExecutor} instance.
     *
     * @param buckets number of buckets or 0 to match available processors
     * @param threadFactory {@link ThreadFactory} to use to create threads
     * @return {@link PredictableExecutor}
     */
    public static PredictableExecutor newPredictableExecutor(int buckets, ThreadFactory threadFactory)  {
        return new PredictableExecutor(buckets, threadFactory);
    }

    /**
     * Creates {@link PredictableExecutor} instance.
     *
     * @param buckets number of buckets or 0 to match available processors
     * @param threadFactory {@link ThreadFactory} to use to create threads
     */
    public PredictableExecutor(int buckets, ThreadFactory threadFactory) {
        checkArgument(buckets >= 0, "number of buckets must be non zero");
        checkNotNull(threadFactory);
        if (buckets == 0) {
            buckets = Runtime.getRuntime().availableProcessors();
        }
        this.backends = new ArrayList<>(buckets);

        for (int i = 0; i < buckets; ++i) {
            this.backends.add(backendExecutorService(threadFactory));
        }
    }

    /**
     * Creates {@link PredictableExecutor} instance with
     * bucket size set to number of available processors.
     *
     * @param threadFactory {@link ThreadFactory} to use to create threads
     */
    public PredictableExecutor(ThreadFactory threadFactory) {
        this(0, threadFactory);
    }

    /**
     * Creates a single thread {@link ExecutorService} to use in the backend.
     *
     * @param threadFactory {@link ThreadFactory} to use to create threads
     * @return single thread {@link ExecutorService}
     */
    protected ExecutorService backendExecutorService(ThreadFactory threadFactory) {
        return Executors.newSingleThreadExecutor(threadFactory);
    }

    /**
     * Executes given command at some time in the future.
     *
     * @param command the {@link Runnable} task
     * @param hint value to pick thread to run on.
     */
    public void execute(Runnable command, int hint) {
        int index = Math.abs(hint) % backends.size();
        backends.get(index).execute(command);
    }

    /**
     * Executes given command at some time in the future.
     *
     * @param command the {@link Runnable} task
     * @param hintFunction Function to compute hint value
     */
    public void execute(Runnable command, Function<Runnable, Integer> hintFunction) {
        execute(command, hintFunction.apply(command));
    }

    private static int hint(Runnable command) {
        if (command instanceof PickyTask) {
            return ((PickyTask) command).hint();
        } else {
            return Objects.hashCode(command);
        }
    }

    @Override
    public void execute(Runnable command) {
        execute(command, PredictableExecutor::hint);
    }

    @Override
    public void shutdown() {
        backends.forEach(ExecutorService::shutdown);
    }

    @Override
    public List<Runnable> shutdownNow() {
        return backends.stream()
                .map(ExecutorService::shutdownNow)
                .flatMap(List::stream)
                .collect(Collectors.toList());
    }

    @Override
    public boolean isShutdown() {
        return backends.stream().allMatch(ExecutorService::isShutdown);
    }

    @Override
    public boolean isTerminated() {
        return backends.stream().allMatch(ExecutorService::isTerminated);
    }

    /**
     * {@inheritDoc}
     *

     * Note: It'll try, but is not assured that the method will return by specified timeout.
     */
    @Override
    public boolean awaitTermination(long timeout, TimeUnit unit)
            throws InterruptedException {

        final Duration timeoutD = Duration.of(unit.toMillis(timeout), ChronoUnit.MILLIS);
        final Instant start = Instant.now();

        return backends.parallelStream()
                .filter(es -> !es.isTerminated())
                .map(es -> {
                    long timeoutMs = timeoutD.minus(Duration.between(Instant.now(), start)).toMillis();
                    try {
                        return es.awaitTermination(timeoutMs, TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return false;
                    }
                })
                .allMatch(result -> result);
    }

    @Override
    protected <T> PickyFutureTask<T> newTaskFor(Callable<T> callable) {
        return new PickyFutureTask<>(callable);
    }

    @Override
    protected <T> PickyFutureTask<T> newTaskFor(Runnable runnable, T value) {
        return new PickyFutureTask<>(runnable, value);
    }

    /**
     * {@link Runnable} also implementing {@link PickyTask}.
     */
    public static interface PickyRunnable extends PickyTask, Runnable { }

    /**
     * {@link Callable} also implementing {@link PickyTask}.
     *
     * @param <T> result type
     */
    public static interface PickyCallable<T> extends PickyTask, Callable<T> { }

    /**
     * Wraps the given {@link Runnable} into {@link PickyRunnable} returning supplied hint.
     *
     * @param runnable {@link Runnable}
     * @param hint hint value
     * @return {@link PickyRunnable}
     */
    public static PickyRunnable picky(Runnable runnable, int hint) {
        return picky(runnable, (r) -> hint);
    }

    /**
     * Wraps the given {@link Runnable} into {@link PickyRunnable} returning supplied hint.
     *
     * @param runnable {@link Runnable}
     * @param hint hint function
     * @return {@link PickyRunnable}
     */
    public static PickyRunnable picky(Runnable runnable, Function<Runnable, Integer> hint) {
        checkNotNull(runnable);
        checkNotNull(hint);
        return new PickyRunnable() {

            @Override
            public void run() {
                runnable.run();
            }

            @Override
            public int hint() {
                return hint.apply(runnable);
            }
        };
    }

    /**
     * Wraps the given {@link Callable} into {@link PickyCallable} returning supplied hint.
     *
     * @param callable {@link Callable}
     * @param hint hint value
     * @param <T> entity type
     * @return {@link PickyCallable}
     */
    public static <T> PickyCallable<T> picky(Callable<T> callable, int hint) {
        return picky(callable, (c) -> hint);
    }

    /**
     * Wraps the given {@link Callable} into {@link PickyCallable} returning supplied hint.
     *
     * @param callable {@link Callable}
     * @param hint hint function
     * @param <T> entity type
     * @return {@link PickyCallable}
     */
    public static <T> PickyCallable<T> picky(Callable<T> callable, Function<Callable<T>, Integer> hint) {
        checkNotNull(callable);
        checkNotNull(hint);
        return new PickyCallable<T>() {

            @Override
            public T call() throws Exception {
                return callable.call();
            }

            @Override
            public int hint() {
                return hint.apply(callable);
            }

        };
    }

    /**
     * Abstraction to give a task a way to express it's preference to run on
     * certain thread.
     */
    public static interface PickyTask {

        /**
         * Returns hint for choosing which Thread to run this task on.
         *
         * @return hint value
         */
        int hint();
    }

    /**
     * A {@link FutureTask} implementing {@link PickyTask}.
     *

     * Note: if the wrapped {@link Callable} or {@link Runnable} was an instance of
     * {@link PickyTask}, it will use {@link PickyTask#hint()} value, if not use {@link Object#hashCode()}.
     *
     * @param <T> result type.
     */
    public static class PickyFutureTask<T>
        extends FutureTask<T>
        implements PickyTask {

        private final Object runnableOrCallable;

        /**
         * Same as {@link FutureTask#FutureTask(Runnable, Object)}.
         *
         * @param runnable work to do
         * @param value result
         */
        public PickyFutureTask(Runnable runnable, T value) {
            super(runnable, value);
            runnableOrCallable = checkNotNull(runnable);
        }

        /**
         * Same as {@link FutureTask#FutureTask(Callable)}.
         *
         * @param callable work to be done
         */
        public PickyFutureTask(Callable<T> callable) {
            super(callable);
            runnableOrCallable = checkNotNull(callable);
        }

        @Override
        public int hint() {
            if (runnableOrCallable instanceof PickyTask) {
                return ((PickyTask) runnableOrCallable).hint();
            } else {
                return runnableOrCallable.hashCode();
            }
        }
    }
}


text:
package gov.va.medora.mdws.emrsvc;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="getPatientsByClinicResult" type="{http://mdws.medora.va.gov/EmrSvc}TaggedPatientArray" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "getPatientsByClinicResult"
})
@XmlRootElement(name = "getPatientsByClinicResponse")
public class GetPatientsByClinicResponse {

    protected TaggedPatientArray getPatientsByClinicResult;

    /**
     * Gets the value of the getPatientsByClinicResult property.
     *
     * @return
     *     possible object is
     *     {@link TaggedPatientArray }
     *
     */
    public TaggedPatientArray getGetPatientsByClinicResult() {
        return getPatientsByClinicResult;
    }

    /**
     * Sets the value of the getPatientsByClinicResult property.
     *
     * @param value
     *     allowed object is
     *     {@link TaggedPatientArray }
     *
     */
    public void setGetPatientsByClinicResult(TaggedPatientArray value) {
        this.getPatientsByClinicResult = value;
    }

}


text:
using namespace Lucene;

/// Deletes documents from an index that do not contain a term.
int main(int argc, char* argv[])
{
    if (argc == 1)
    {
        std::wcout << L"Usage: deletefiles.exe <lucene index dir> <unique_term>\n";
        return 1;
    }

    try
    {
        DirectoryPtr directory = FSDirectory::open(StringUtils::toUnicode(argv[1]));

        // we don't want read-only because we are about to delete
        IndexReaderPtr reader = IndexReader::open(directory, false);

        TermPtr term = newLucene<Term>(L"path", StringUtils::toUnicode(argv[2]));
        int32_t deleted = reader->deleteDocuments(term);

        std::wcout << L"Deleted " << deleted << L" documents containing " << term->toString() << L"\n";

        reader->close();
        directory->close();
    }
    catch (LuceneException& e)
    {
        std::wcout << L"Exception: " << e.getError() << L"\n";
        return 1;
    }

    return 0;
}