text:
package io.cloudslang.content.active_directory.services.groups;

import io.cloudslang.content.active_directory.entities.CreateGroupInput;
import io.cloudslang.content.active_directory.utils.CustomSSLSocketFactory;
import io.cloudslang.content.active_directory.utils.LDAPQuery;
import io.cloudslang.content.active_directory.utils.ResultUtils;

import javax.naming.CompositeName;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import java.util.Arrays;
import java.util.Map;

import static io.cloudslang.content.constants.OutputNames.RETURN_CODE;
import static io.cloudslang.content.active_directory.constants.OutputNames.*;
import static io.cloudslang.content.active_directory.utils.ResultUtils.replaceInvalidXMLCharacters;

public class CreateGroupService {

    public Map<String, String> execute(CreateGroupInput input) {

        Map<String, String> results = ResultUtils.createNewResultsEmptyMap();

        try {
            LDAPQuery ldap = new LDAPQuery();
            //  groupCN = ldap.replaceIllegalCharactersForSAM(groupCN);
            String sAMAccountName = input.getSAMAccountName();
            String ouDN = input.getDistinguishedName();
            String groupCN = input.getGroupCommonName();

            sAMAccountName = ldap.replaceIllegalCharactersForSAM(sAMAccountName);

            if (input.getEscapeChars()) {
                ouDN = ldap.normalizeDN(ouDN, false);
                groupCN = ldap.normalizeADExpression(groupCN, false);
            }
            Name ou = new CompositeName().add(ouDN);
            Name group = new CompositeName().add("cn=" + groupCN);

            DirContext ctx;

            if (input.getProtocol().toLowerCase().trim().equals(input.getProtocol().toLowerCase())) {
                if (Boolean.valueOf(input.getTrustAllRoots())) {
                    ctx = ldap.MakeDummySSLLDAPConnection(input.getHost(), input.getUsername(), input.getPassword(),
                            input.getTimeout(), input.getTlsVersion(), input.getAllowedCiphers(),
                            input.getProxyHost(), input.getProxyPort(), input.getProxyUsername(), input.getProxyPassword());
                } else {
                    ctx = ldap.MakeSSLLDAPConnection(input.getHost(), input.getUsername(), input.getPassword(),
                            input.getTrustKeystore(), input.getTrustPassword(),
                            input.getTimeout(), input.getTlsVersion(), input.getAllowedCiphers(), input.getProxyHost(),
                            input.getProxyPort(), input.getProxyUsername(), input.getProxyPassword(), input.getX509HostnameVerifier());
                }

            } else {
                ctx = ldap.MakeLDAPConnection(input.getHost(), input.getUsername(), input.getPassword(),
                        input.getTimeout(), input.getProxyHost(), input.getProxyPort(), input.getProxyUsername(), input.getProxyPassword());
            }

            DirContext ctxOU = (DirContext) ctx.lookup(ou);

            String groupTypeValues[] = new String[]{"-2147483646", "-2147483644", "-2147483640", "2", "4", "8"};

            String groupType = input.getGroupType();

            if (groupType.isEmpty()) {
                groupType = "-2147483646"; //default value = Global Security Group
            } else {
                if (!Arrays.asList(groupTypeValues).contains(groupType))
                    throw new RuntimeException("Invalid group type.");
            }

            Attributes groupAttrs = new BasicAttributes(true);
            groupAttrs.put("objectclass", "group");
            groupAttrs.put("groupType", groupType);
            groupAttrs.put("sAMAccountName", sAMAccountName);

            ctxOU.createSubcontext(group, groupAttrs);

            String groupDN = "CN=" + groupCN + "," + ouDN;

            ctxOU.close();
            ctx.close();

            results.put(RETURN_RESULT, "Added group with CN=" + groupCN);
            results.put(RESULT_GROUP_DN, groupDN);
            results.put(RETURN_CODE, "0");

        } catch (NamingException e) {
            Exception exception = CustomSSLSocketFactory.getException();
            if (exception == null)
                exception = e;
            results.put(EXCEPTION, String.valueOf(exception));
            results.put(RETURN_RESULT, replaceInvalidXMLCharacters(exception.getMessage()));
            results.put(RETURN_CODE, "-1");
        }

        return results;
    }
}


text:
var fs = require('fs');

var model = require('./model');
var api = module.exports.api = {};

api.spit = function(params, callback){
	var extension = params.filename.split('.').pop();
	if(extension !== 'css'){
		callback( Error('invalid extension') );
		return;
	}
	model.compile(params, callback);
};

redpajama_set_name: RedPajamaGithub


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

<TITLE>
Deprecated List (IM Profile)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
    Deprecated
      Index
      Help

IM Profile

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Deprecated API

Deprecated Classes

com.siemens.icm.io.File

          Use javax.microedition.io.FileConnection instead

      Overview
      Package
      Class
      Use
      Tree
    Deprecated
      Index
      Help

IM Profile

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Submit a comment or suggestion Version 2.0 of IM Profile Specification
Java is a trademark or registered trademark of Sun Microsystems,  Inc. in the US and other countries. Copyright (c) 1993-2002 Sun Microsystems, Inc. 901 San Antonio Road,Palo Alto, California, 94303, U.S.A.  All Rights Reserved.


text:
<!DOCTYPE html>

        <meta charset="utf8">
        <title>BiologyMeetWeb</title>


text:
from rqalpha.api import *
import pandas as pd
import numpy as np
from datetime import timedelta
from pybrain.datasets import SequentialDataSet
from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure.networks import Network
from pybrain.structure.modules import LSTMLayer
from pybrain.supervised import RPropMinusTrainer

# 训练trainX和trainY,并返回神经网络net
def train(context, trainX, trainY):
    ds = SequentialDataSet(4, 1)
    for dataX, dataY in zip(trainX, trainY):
        ds.addSample(dataX, dataY)
    net = buildNetwork(4, 1, 1, hiddenclass=LSTMLayer, outputbias=False, recurrent=True)
    trainer = RPropMinusTrainer(net, dataset=ds)
    EPOCHS_PER_CYCLE = 5
    CYCLES = 5
    for i in range(CYCLES):
        trainer.trainEpochs(EPOCHS_PER_CYCLE)
    return net, trainer.testOnData()

# 更新数据集data
def load(context, ticker):
    close = history(90, '1d', 'close')[ticker]
    high = history(90, '1d', 'high')[ticker]
    low = history(90, '1d', 'low')[ticker]
    volume = history(90, '1d', 'volume')[ticker]
    data = pd.DataFrame({'close': close.values,
                         'high': high.values,
                         'low': low.values,
                         'volume': volume.values}, index=close.index)
    context.position_ratio.append([data['close'].mean(),
                                   data['high'].mean(),
                                   data['low'].mean(),
                                   data['volume'].mean()])
    context.shape_ratio.append([data['close'].std(),
                                data['high'].std(),
                                data['low'].std(),
                                data['volume'].std()])
    data['close'] = (data['close'] - context.position_ratio[-1][0]) / context.shape_ratio[-1][0]
    data['high'] = (data['high'] - context.position_ratio[-1][1]) / context.shape_ratio[-1][1]
    data['low'] = (data['low'] - context.position_ratio[-1][2]) / context.shape_ratio[-1][2]
    data['volume'] = (data['volume'] - context.position_ratio[-1][3]) / context.shape_ratio[-1][3]

    return data

# 剔除情况特殊的黑名单股,只看策略效果,排除个体问题
def filter_blacklist(context, stock_list):
    return [ticker for ticker in stock_list if ticker not in context.blacklist]

def filter_stlist(stock_list):
    return [ticker for ticker in stock_list if not is_st_stock(ticker)]

# 建模,每3个月运行一次,用过去6个月训练
def modelize(context, bar_dict):
    if context.every_3_months % 3 != 0:
        context.every_3_months += 1
        return 0
    print('-' * 65)
    print('------' + '{:-^59}'.format('modelizing'))
    context.position_ratio = []
    context.shape_ratio = []
    context.data = []
    context.net = []
    context.list = []
    templist = list(get_fundamentals(query(fundamentals.eod_derivative_indicator.market_cap)
                                     .order_by(fundamentals.eod_derivative_indicator.market_cap.asc())
                                     .limit(context.num * 5)).columns)
    context.list = filter_blacklist(context, filter_stlist(templist))[:context.num]
    names = []
    scores = []
    for ticker in context.list:
        names.append('{:<11}'.format(ticker))
        data = load(context, ticker)
        trainX = data.ix[:-1, :].values
        trainY = data.ix[1:, 0].values
        net, mse = train(context, trainX, trainY)
        context.data.append(data)
        context.net.append(net)
        scores.append('{:<11}'.format(str(mse)[:6]))
        if np.isnan(mse):
            context.blacklist.append(ticker)
            context.mflag = 0
            return 0
    context.pct = [0] * context.num
    print('------' + '{:-^59}'.format('finished'))
    print('-' * 65)
    print(' nm | ' + ' '.join(names))
    print('mse | ' + ' '.join(scores))

    context.mflag = 1  # 标记已经建模
    context.tflag = 0
    context.every_3_months += 1

def mkt_panic():
    # 连续两天大盘跌破3个点,或者大盘跌破5个点
    mkt = history(3, '1d', 'close')['000001.XSHG']
    panic = (mkt[-1] / mkt[-2] < 0.97 and mkt[-2] / mkt[-3] < 0.97) or mkt[-1] / mkt[-2] < 0.95
    if panic:
        print('!!!!!!' + '{:!^59}'.format('panic'))
        return 1
    return 0

# 最后利用每3个月更新的模型,每天进行交易,预测涨幅超过a就买入,预测跌幅超过b则卖出
def trade(context, bar_dict):
    while context.mflag == 0: modelize(context, bar_dict)

    trash_bin = [ticker for ticker in context.portfolio.positions if ticker not in context.list]
    for ticker in trash_bin: order_target_percent(ticker, 0)

    actual_close = []
    actual_high = []
    actual_low = []
    actual_vol = []
    actual_open = []
    actual_data = []
    predict_close = []

    for i in range(context.num):
        actual_close.append(
            (history(1, '1d', 'close')[context.list[i]][0] - context.position_ratio[i][0]) / context.shape_ratio[i][0])
        actual_high.append(
            (history(1, '1d', 'high')[context.list[i]][0] - context.position_ratio[i][1]) / context.shape_ratio[i][1])
        actual_low.append(
            (history(1, '1d', 'low')[context.list[i]][0] - context.position_ratio[i][2]) / context.shape_ratio[i][2])
        actual_vol.append(
            (history(1, '1d', 'volume')[context.list[i]][0] - context.position_ratio[i][3]) / context.shape_ratio[i][3])
        actual_open.append(
            (history(1, '1m', 'close')[context.list[i]][0] - context.position_ratio[i][0]) / context.shape_ratio[i][0])
        actual_data.append([actual_close[i], actual_high[i], actual_low[i], actual_vol[i]])
        predict_close.append(context.net[i].activate(actual_data[i])[0])

    if context.tflag == 0:
        context.temp_pc = predict_close

    r = [float((pc * shape_ratio[0] + position_ratio[0]) / (ao * shape_ratio[0] + position_ratio[0]) - 1) for
         pc, ao, shape_ratio, position_ratio in
         zip(predict_close, actual_open, context.shape_ratio, context.position_ratio)]

    temp_r = [float((pc * shape_ratio[0] + position_ratio[0]) / (tpc * shape_ratio[0] + position_ratio[0]) - 1) for
              pc, tpc, shape_ratio, position_ratio in
              zip(predict_close, context.temp_pc, context.shape_ratio, context.position_ratio)]

    # The essence of this strategy
    hybrid_r = [max(ri, temp_ri, ri + temp_ri) for ri, temp_ri in zip(r, temp_r)]
    bad_hybrid_signal = sum([x <= 0 for x in hybrid_r])
    a, b = 0.00, -0.01
    panic = mkt_panic()
    for i in range(context.num):
        if panic or 0 < context.post_panic < 22 * context.num:
            context.pct[i] = 0
            context.post_panic = (1 - panic) * (context.post_panic + 1) + panic
        elif hybrid_r[i] > a:
            context.pct[i] = min(context.pct[i] + .5 / context.num, 2 / context.num)
            context.post_panic = 0
        elif hybrid_r[i] < b or bad_hybrid_signal > 3 * context.num // 5:
            context.pct[i] = max(context.pct[i] - .5 / context.num, 0)
            context.post_panic = 0

    if context.tflag == 1: print(' ac | ' + ' '.join(['{:<11}'.format(str(ac)[:6]) for ac in actual_close]))
    print('-' * 65)
    print(' ao | ' + ' '.join(['{:<11}'.format(str(ao)[:6]) for ao in actual_open]))
    print(' pc | ' + ' '.join(['{:<11}'.format(str(pc)[:6]) for pc in predict_close]))
    print('  r | ' + ' '.join(['{:<11}'.format(str(ri)[:6]) for ri in hybrid_r]))
    pct = sum([context.portfolio.positions[ticker].market_value for ticker in context.portfolio.positions]) / (
    context.portfolio.market_value + context.portfolio.cash)
    tot_pct = max(sum(context.pct), 1)
    context.pct = list(map(lambda x: x / tot_pct, context.pct))
    print('  % | ' + ' '.join(['{:<11}'.format(str(p)[:6]) for p in context.pct]))
    plot('total position', pct * 100)
    for i in range(context.num): order_target_percent(context.list[i], context.pct[i])
    context.tflag = 1
    context.temp_pc = predict_close

# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
    context.temp_pc = []
    context.every_3_months = 0
    context.tflag = 0
    context.mflag = 0
    context.position_ratio = []
    context.shape_ratio = []
    context.num = 20
    context.list = []
    context.pct = [0] * context.num
    context.net = []
    context.data = []
    context.post_panic = 0
    context.blacklist = [
        '000004.XSHE', '000546.XSHE',
        '000594.XSHE', '002352.XSHE',
        '300176.XSHE', '300260.XSHE',
        '300372.XSHE', '600137.XSHG',
        '600306.XSHG', '600656.XSHG',
    ]
    scheduler.run_monthly(modelize, 1)
    scheduler.run_daily(trade, time_rule=market_open(minute=1))

# before_trading此函数会在每天交易开始前被调用,当天只会被调用一次
def before_trading(context):
    pass

# 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
def handle_bar(context, bar_dict):
    pass


text:
function setupSamples(){

    $('#process-icon').show()
    var url = SAMPLE_DIRECTORY_ADD_PATH;
    $.ajax({
        url: url,
        type: "POST",
        data: "",
    })
        .done(function (data) {

            var resp = $.parseJSON(data);
            if (resp.success == true) {
                while (!checkUserStoreExist(resp.domain)) {
                    setTimeout(function () {
                    }, 2000);
                }
                addSampleUsers();
            } else {

                if (typeof resp.reLogin != 'undefined' && resp.reLogin == true) {
                    window.top.location.href = window.location.protocol + '//' + serverUrl + '/' + ADMIN_PORTAL_NAME + '/logout.jag';
                } else {
                    if (resp.message != null && resp.message.length > 0) {
                        message({
                            content: resp.message, type: 'error', cbk: function () {
                            }
                        });
                    } else {
                        message({
                            content: 'Error occurred while loading values for the grid.',
                            type: 'error',
                            cbk: function () {
                            }
                        });
                    }
                }
            }
        })
        .fail(function () {
            $('#process-icon').hide()
            message({content: 'Error while adding Directory. ', type: 'servererror'});
        })
        .always(function () {
        });
}

function checkUserStoreExist(domain){

    var result = false;
    var url = DIRECTORY_GET_PATH + "?domain=" + domain;
    $.ajax({
        url: url,
        type: "POST",
        async: false,
        data: "",
    })
        .done(function (data) {

            var resp = $.parseJSON(data);
            if (resp.success == false) {
                if (typeof resp.reLogin != 'undefined' && resp.reLogin == true) {
                    window.top.location.href = window.location.protocol + '//' + serverUrl + '/' + ADMIN_PORTAL_NAME + '/logout.jag';
                } else {
                    if (resp.message != null && resp.message.length > 0) {
                        message({
                            content: resp.message, type: 'error', cbk: function () {
                            }
                        });
                    } else {
                        message({
                            content: 'Error occurred while loading values for the grid.',
                            type: 'error',
                            cbk: function () {
                            }
                        });
                    }
                }
            } else {
                if(resp.return != ""){
                    result = true;
                }
            }

        })
        .fail(function () {
            $('#process-icon').hide();
            message({content: 'Error while adding Directory. ', type: 'servererror'});
        })
        .always(function () {
        });
    return result;
}

function addSampleUsers(){

    var url = SAMPLE_ADD_USERS_FINISH_PATH;
    $.ajax({
        url: url,
        type: "POST",
        data: "",
    })
        .done(function (data) {

            var resp = $.parseJSON(data);
            if (resp.success == true) {
                window.location.href = SAMPLE_USERS_LIST_PATH;
            } else {

                if (typeof resp.reLogin != 'undefined' && resp.reLogin == true) {
                    window.top.location.href = window.location.protocol + '//' + serverUrl + '/' + ADMIN_PORTAL_NAME + '/logout.jag';
                } else {
                    if (resp.message != null && resp.message.length > 0) {
                        message({
                            content: resp.message, type: 'error', cbk: function () {
                            }
                        });
                    } else {
                        message({
                            content: 'Error occurred while loading values for the grid.',
                            type: 'error',
                            cbk: function () {
                            }
                        });
                    }
                }
            }
            $('#process-icon').hide()

        })
        .fail(function () {
            $('#process-icon').hide();
            message({content: 'Error while adding Directory. ', type: 'servererror'});
        })
        .always(function () {
        });

}

function getSampleUsers(){
    userList = null;
    $.ajax({
        url: "/" + ADMIN_PORTAL_NAME + "/directories/get-sample-user-list",
        type: "GET",
        data: "&user=" + userName,
        success: function (data) {
            var resp = $.parseJSON(data);

            if (resp.success == false) {
                if (typeof resp.reLogin != 'undefined' && resp.reLogin == true) {
                    window.top.location.href = window.location.protocol + '//' + serverUrl + '/' + ADMIN_PORTAL_NAME + '/logout.jag';
                } else {
                    if (resp.message != null && resp.message.length > 0) {
                        message({
                            content: resp.message, type: 'error', cbk: function () {
                            }
                        });
                    } else {
                        message({
                            content: 'Error occurred while loading values for the grid.',
                            type: 'error',
                            cbk: function () {
                            }
                        });
                    }
                }
            } else {
                userList = resp;
                if (userList != null && userList.constructor !== Array) {
                    var arr = [];
                    arr[0] = userList;
                    userList = arr;
                }
                drawList();
            }
        },
        error: function (e) {
            message({
                content: 'Error occurred while loading values for the grid.', type: 'error', cbk: function () {
                }
            });
        }
    });
}

function drawList() {
    var output = "";
    if (userList != null) {
        for (var i = 0; i < userList.length; i++) {
            var table = document.getElementById("userTable").getElementsByTagName('tbody')[0];
            var row = table.insertRow(0);
            row.className = "info";
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            cell1.innerHTML = userList[i].name;
            cell2.innerHTML = '
<input id="password" class="form-control" type="password" value="'+ userList[i].password + '" placeholder="password" style="display: block;">
';
        }
    }
}

/**
 * This method will toggle password text to visible/hide status
 * @param element
 */
function togglePassword(element) {
    var relatedTextBox = $($(element).parent().find('input')[0]);
    if ($(relatedTextBox).attr('type') === "text") {
        $(relatedTextBox).attr('type', 'password');
        $($(element).find('i')[0]).removeClass('fw-view').addClass('fw-hide');
    } else if ($(relatedTextBox).attr('type') === "password") {
        $(relatedTextBox).attr('type', 'text');
        $($(element).find('i')[0]).removeClass('fw-hide').addClass('fw-view');
    }
}

function viewApplications(){
    window.location.href = "../serviceproviders";
}

function gotoUserPortal(){
    window.location.href = USER_PORTAL_LINK;
}


text:
PROG=	tip
LINKS=	${BINDIR}/tip ${BINDIR}/cu
MAN=	tip.1 cu.1
CFLAGS+=-I${.CURDIR} -DDEFBR=9600 -DDEFFS=BUFSIZ -DACULOG -DPRISTINE \
	-DCONNECT -DV831 -DVENTEL -DHAYES -DCOURIER -DT3000
WARNS?=	2
.PATH:	${.CURDIR}/../libacu
SRCS=	acu.c acutab.c cmds.c cmdtab.c cu.c hunt.c log.c partab.c \
	remote.c tip.c tipout.c uucplock.c value.c vars.c \
	biz22.c courier.c df.c dn11.c hayes.c t3000.c v3451.c v831.c ventel.c

# -- acutab is configuration dependent, and so depends on the Makefile
# -- remote.o depends on the Makefile because of DEFBR and DEFFS
# -- log.o depends on the Makefile because of ACULOG
acutab.o log.o remote.o: Makefile

.include <bsd.prog.mk>

# Dirty, rotten hack. This can be removed when we are confident that there
# is no cu(1) with the schg-bit set.
beforeinstall:
.if exists(${DESTDIR}${BINDIR}/cu)
	-@chflags noschg ${DESTDIR}${BINDIR}/cu
.endif


text:
package io.spine.testing.server.blackbox.given;

import io.spine.core.MessageId;
import io.spine.core.UserId;
import io.spine.server.commandbus.CommandDispatcher;
import io.spine.server.event.EventDispatcher;
import io.spine.testing.TestValues;
import io.spine.testing.core.given.GivenVersion;
import io.spine.testing.server.blackbox.BbProject;
import io.spine.testing.server.blackbox.BbProjectId;
import io.spine.testing.server.blackbox.BbReportId;
import io.spine.testing.server.blackbox.BbTask;
import io.spine.testing.server.blackbox.BbTaskId;
import io.spine.testing.server.blackbox.command.BbAddTask;
import io.spine.testing.server.blackbox.command.BbAssignProject;
import io.spine.testing.server.blackbox.command.BbAssignSelf;
import io.spine.testing.server.blackbox.command.BbCreateProject;
import io.spine.testing.server.blackbox.command.BbCreateReport;
import io.spine.testing.server.blackbox.command.BbFailProject;
import io.spine.testing.server.blackbox.command.BbFinalizeProject;
import io.spine.testing.server.blackbox.command.BbInitProject;
import io.spine.testing.server.blackbox.command.BbRegisterCommandDispatcher;
import io.spine.testing.server.blackbox.command.BbStartProject;
import io.spine.testing.server.blackbox.event.BbEventDispatcherRegistered;
import io.spine.testing.server.blackbox.event.BbProjectDone;
import io.spine.testing.server.blackbox.event.BbProjectFailed;
import io.spine.testing.server.blackbox.event.BbTaskAdded;
import io.spine.testing.server.blackbox.event.BbUserDeleted;
import io.spine.type.TypeUrl;

import java.util.stream.IntStream;

import static com.google.common.collect.Lists.newArrayList;
import static io.spine.base.Identifier.newUuid;
import static io.spine.protobuf.AnyPacker.pack;
import static io.spine.testing.TestValues.newUuidValue;

public class Given {

    /** Prevents instantiation of this utility class. */
    private Given() {
    }

    public static BbProjectId newProjectId() {
        return BbProjectId.generate();
    }

    public static BbAddTask addTask(BbProjectId projectId) {
        return BbAddTask.newBuilder()
                .setProjectId(projectId)
                .setTask(newTask())
                .build();
    }

    public static BbTaskAdded taskAdded(BbProjectId projectId) {
        return BbTaskAdded.newBuilder()
                .setProjectId(projectId)
                .setTask(newTask())
                .build();
    }

    private static BbTask newTask() {
        return BbTask.newBuilder()
                .setTaskId(BbTaskId.generate())
                .setTitle(newUuid())
                .build();
    }

    public static BbCreateReport createReport(BbProjectId projectId) {
        return BbCreateReport.newBuilder()
                .setReportId(newReportId())
                .addProjectId(projectId)
                .build();
    }

    private static BbReportId newReportId() {
        return BbReportId.newBuilder()
                .setId(newUuid())
                .build();
    }

    public static BbCreateProject createProject() {
        return createProject(newProjectId());
    }

    private static UserId generateUserId() {
        return UserId.newBuilder()
                .setValue(TestValues.randomString())
                .build();
    }

    public static BbCreateProject createProject(BbProjectId id) {
        return BbCreateProject.newBuilder()
                .setProjectId(id)
                .build();
    }

    public static BbAssignSelf assignSelf(BbProjectId id) {
        return BbAssignSelf.newBuilder()
                .setProjectId(id)
                .build();
    }

    public static BbInitProject initProject(BbProjectId id, boolean scrum) {
        var builder = BbInitProject.newBuilder()
                .setProjectId(id);
        // Generate a random team.
        IntStream.range(0, TestValues.random(1, 10))
                 .forEach(i -> builder.addMember(generateUserId()));
        if (scrum) {
            builder.setScrumMaster(generateUserId());
        }
        return builder.build();
    }

    public static BbStartProject startProject(BbProjectId id) {
        return BbStartProject.newBuilder()
                .setProjectId(id)
                .build();
    }

    public static BbProject createdProjectState(BbCreateProject createProject) {
        return BbProject.newBuilder()
                .setId(createProject.getProjectId())
                .setStatus(BbProject.Status.CREATED)
                .build();
    }

    public static BbAssignProject addProjectAssignee(BbProjectId projectId, UserId id) {
        return BbAssignProject.newBuilder()
                .setId(projectId)
                .setUserId(id)
                .build();
    }

    public static BbUserDeleted userDeleted(UserId id, BbProjectId... projectIds) {
        return BbUserDeleted.newBuilder()
                .setId(id)
                .addAllProject(newArrayList(projectIds))
                .build();
    }

    public static BbProjectDone projectDone(BbProjectId projectId) {
        return BbProjectDone.newBuilder()
                .setId(projectId)
                .build();
    }

    public static BbFinalizeProject finalizeProject(BbProjectId projectId) {
        return BbFinalizeProject.newBuilder()
                .setProjectId(projectId)
                .build();
    }

    public static BbFailProject failProject(BbProjectId projectId) {
        return BbFailProject.newBuilder()
                .setProjectId(projectId)
                .build();
    }

    public static BbProjectFailed projectFailed(BbProjectId projectId) {
        return BbProjectFailed.newBuilder()
                .setProjectId(projectId)
                .build();
    }

    public static MessageId someMessageId() {
        return MessageId
                .newBuilder()
                .setVersion(GivenVersion.withNumber(42))
                .setTypeUrl(TypeUrl.of(BbProjectDone.class)
                                   .value())
                .setId(pack(newUuidValue()))
                .build();
    }
}


text:
var foo = { async bar() {} };
// ArrowExpression usage to define function
var fooAgain = () => {};


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Twice.Models.Media;

namespace Twice.Tests.Models.Media
{
	[TestClass, ExcludeFromCodeCoverage]
	public class MediaExtractorRepositoryTests
	{
		[TestMethod, TestCategory( "Models.Media" )]
		public async Task AllExtractorsAreChecked()
		{
			// Arrange
			var repository = new MediaExtractorRepository();
			var e1 = new Mock<IMediaExtractor>();
			e1.Setup( e => e.CanExtract( "test" ) ).Returns( false );
			var e2 = new Mock<IMediaExtractor>();
			e2.Setup( e => e.CanExtract( "test" ) ).Returns( false );

			repository.AddExtractor( e1.Object );
			repository.AddExtractor( e2.Object );

			// Act
			await repository.ExtractMedia( "test" );

			// Assert
			e1.Verify( v => v.CanExtract( "test" ), Times.Once() );
			e2.Verify( v => v.CanExtract( "test" ), Times.Once() );
		}

		[TestMethod, TestCategory( "Models.Media" )]
		public async Task NonMatchingExtractorIsNotUsed()
		{
			// Arrange
			var repository = new MediaExtractorRepository();
			var extractor = new Mock<IMediaExtractor>();
			extractor.Setup( v => v.CanExtract( "test" ) ).Returns( false );
			extractor.Setup( v => v.GetMediaUrl( "test" ) ).Verifiable();

			repository.AddExtractor( extractor.Object );

			// Act
			await repository.ExtractMedia( "test" );

			// Assert
			extractor.Verify( v => v.CanExtract( "test" ), Times.Once() );
			extractor.Verify( v => v.GetMediaUrl( "test" ), Times.Never() );
		}

		[TestMethod, TestCategory( "Models.Media" )]
		public async Task NullIsReturnedWhenNoExtractorWasFound()
		{
			// Arrange
			var repository = new MediaExtractorRepository();

			// Act
			var url = await repository.ExtractMedia( "test" );

			// Assert
			Assert.IsNull( url );
		}

		[TestMethod, TestCategory( "Models.Media" )]
		public async Task SearchEndsWithFirstMatch()
		{
			// Arrange
			var repository = new MediaExtractorRepository();
			var e1 = new Mock<IMediaExtractor>();
			e1.Setup( e => e.CanExtract( "test" ) ).Returns( true );
			var e2 = new Mock<IMediaExtractor>();
			e2.Setup( e => e.CanExtract( "test" ) ).Returns( true );

			repository.AddExtractor( e1.Object );
			repository.AddExtractor( e2.Object );

			// Act
			await repository.ExtractMedia( "test" );

			// Assert
			e1.Verify( v => v.CanExtract( "test" ), Times.Once() );
			e2.Verify( v => v.CanExtract( "test" ), Times.Never() );
		}
	}
}


text:
#ifndef AERON_CONCURRENT_LOGBUFFER_TERM_APPENDER_H
#define AERON_CONCURRENT_LOGBUFFER_TERM_APPENDER_H

#include <functional>
#include "HeaderWriter.h"
#include "LogBufferDescriptor.h"
#include "BufferClaim.h"
#include "DataFrameHeader.h"

namespace aeron { namespace concurrent { namespace logbuffer {

/**
 * Supplies the reserved value field for a data frame header. The returned value will be set in the header as
 * Little Endian format.
 *
 * This will be called as the last action of encoding a data frame right before the length is set. All other fields
 * in the header plus the body of the frame will have been written at the point of supply.
 *
 * @param termBuffer for the message
 * @param termOffset of the start of the message
 * @param length of the message in bytes
 */
typedef std::function<std::int64_t(
    AtomicBuffer& termBuffer,
    util::index_t termOffset,
    util::index_t length)> on_reserved_value_supplier_t;

#define TERM_APPENDER_FAILED ((std::int32_t)-2)

static const on_reserved_value_supplier_t DEFAULT_RESERVED_VALUE_SUPPLIER =
    [](AtomicBuffer&, util::index_t, util::index_t) -> std::int64_t { return 0; };

class TermAppender
{
public:
    struct Result
    {
        std::int64_t termOffset;
        std::int32_t termId;
    };

    TermAppender(AtomicBuffer &termBuffer, AtomicBuffer &metaDataBuffer, const int partitionIndex) :
        m_termBuffer(termBuffer),
        m_tailBuffer(metaDataBuffer),
        m_tailOffset(LogBufferDescriptor::TERM_TAIL_COUNTER_OFFSET + (partitionIndex * sizeof(std::int64_t)))
    {
    }

    inline AtomicBuffer &termBuffer()
    {
        return m_termBuffer;
    }

    inline std::int64_t rawTailVolatile() const
    {
        return m_tailBuffer.getInt64Volatile(m_tailOffset);
    }

    inline std::int32_t claim(
        const HeaderWriter &header,
        util::index_t length,
        BufferClaim &bufferClaim,
        std::int32_t activeTermId)
    {
        const util::index_t frameLength = length + DataFrameHeader::LENGTH;
        const util::index_t alignedLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
        const std::int64_t rawTail = getAndAddRawTail(alignedLength);
        const std::int64_t termOffset = rawTail & 0xFFFFFFFF;
        const std::int32_t termId = LogBufferDescriptor::termId(rawTail);

        const std::int32_t termLength = m_termBuffer.capacity();

        checkTerm(activeTermId, termId);

        std::int64_t resultingOffset = termOffset + alignedLength;
        if (resultingOffset > termLength)
        {
            resultingOffset = handleEndOfLogCondition(m_termBuffer, termOffset, header, termLength, termId);
        }
        else
        {
            const auto frameOffset = static_cast<std::int32_t>(termOffset);
            header.write(m_termBuffer, frameOffset, frameLength, termId);
            bufferClaim.wrap(m_termBuffer, frameOffset, frameLength);
        }

        return static_cast<std::int32_t>(resultingOffset);
    }

    inline std::int32_t appendUnfragmentedMessage(
        const HeaderWriter &header,
        const AtomicBuffer &srcBuffer,
        util::index_t srcOffset,
        util::index_t length,
        const on_reserved_value_supplier_t &reservedValueSupplier,
        std::int32_t activeTermId)
    {
        const util::index_t frameLength = length + DataFrameHeader::LENGTH;
        const util::index_t alignedLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
        const std::int64_t rawTail = getAndAddRawTail(alignedLength);
        const std::int64_t termOffset = rawTail & 0xFFFFFFFF;
        const std::int32_t termId = LogBufferDescriptor::termId(rawTail);

        const std::int32_t termLength = m_termBuffer.capacity();

        checkTerm(activeTermId, termId);

        std::int64_t resultingOffset = termOffset + alignedLength;
        if (resultingOffset > termLength)
        {
            resultingOffset = handleEndOfLogCondition(m_termBuffer, termOffset, header, termLength, termId);
        }
        else
        {
            const auto frameOffset = static_cast<std::int32_t>(termOffset);
            header.write(m_termBuffer, frameOffset, frameLength, termId);
            m_termBuffer.putBytes(frameOffset + DataFrameHeader::LENGTH, srcBuffer, srcOffset, length);

            const std::int64_t reservedValue = reservedValueSupplier(m_termBuffer, frameOffset, frameLength);
            m_termBuffer.putInt64(frameOffset + DataFrameHeader::RESERVED_VALUE_FIELD_OFFSET, reservedValue);

            FrameDescriptor::frameLengthOrdered(m_termBuffer, frameOffset, frameLength);
        }

        return static_cast<std::int32_t>(resultingOffset);
    }

    template <class BufferIterator> std::int32_t appendUnfragmentedMessage(
        const HeaderWriter &header,
        BufferIterator bufferIt,
        util::index_t length,
        const on_reserved_value_supplier_t &reservedValueSupplier,
        std::int32_t activeTermId)
    {
        const util::index_t frameLength = length + DataFrameHeader::LENGTH;
        const util::index_t alignedLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
        const std::int64_t rawTail = getAndAddRawTail(alignedLength);
        const std::int64_t termOffset = rawTail & 0xFFFFFFFF;
        const std::int32_t termId = LogBufferDescriptor::termId(rawTail);

        const std::int32_t termLength = m_termBuffer.capacity();

        checkTerm(activeTermId, termId);

        std::int64_t resultingOffset = termOffset + alignedLength;
        if (resultingOffset > termLength)
        {
            resultingOffset = handleEndOfLogCondition(m_termBuffer, termOffset, header, termLength, termId);
        }
        else
        {
            const auto frameOffset = static_cast<std::int32_t>(termOffset);
            header.write(m_termBuffer, frameOffset, frameLength, termId);

            std::int32_t offset = frameOffset + DataFrameHeader::LENGTH;
            for (
                std::int32_t endingOffset = offset + length;
                offset < endingOffset;
                offset += bufferIt->capacity(), ++bufferIt)
            {
                m_termBuffer.putBytes(offset, *bufferIt, 0, bufferIt->capacity());
            }

            const std::int64_t reservedValue = reservedValueSupplier(m_termBuffer, frameOffset, frameLength);
            m_termBuffer.putInt64(frameOffset + DataFrameHeader::RESERVED_VALUE_FIELD_OFFSET, reservedValue);

            FrameDescriptor::frameLengthOrdered(m_termBuffer, frameOffset, frameLength);
        }

        return static_cast<std::int32_t>(resultingOffset);
    }

    std::int32_t appendFragmentedMessage(
        const HeaderWriter &header,
        const AtomicBuffer &srcBuffer,
        util::index_t srcOffset,
        util::index_t length,
        util::index_t maxPayloadLength,
        const on_reserved_value_supplier_t &reservedValueSupplier,
        std::int32_t activeTermId)
    {
        const int numMaxPayloads = length / maxPayloadLength;
        const util::index_t remainingPayload = length % maxPayloadLength;
        const util::index_t lastFrameLength = (remainingPayload > 0) ?
            util::BitUtil::align(remainingPayload + DataFrameHeader::LENGTH, FrameDescriptor::FRAME_ALIGNMENT) : 0;
        const util::index_t requiredLength =
            (numMaxPayloads * (maxPayloadLength + DataFrameHeader::LENGTH)) + lastFrameLength;
        const std::int64_t rawTail = getAndAddRawTail(requiredLength);
        const std::int64_t termOffset = rawTail & 0xFFFFFFFF;
        const std::int32_t termId = LogBufferDescriptor::termId(rawTail);

        const std::int32_t termLength = m_termBuffer.capacity();

        checkTerm(activeTermId, termId);

        std::int64_t resultingOffset = termOffset + requiredLength;
        if (resultingOffset > termLength)
        {
            resultingOffset = handleEndOfLogCondition(m_termBuffer, termOffset, header, termLength, termId);
        }
        else
        {
            std::uint8_t flags = FrameDescriptor::BEGIN_FRAG;
            util::index_t remaining = length;
            auto frameOffset = static_cast<std::int32_t>(termOffset);

            do
            {
                const util::index_t bytesToWrite = std::min(remaining, maxPayloadLength);
                const util::index_t frameLength = bytesToWrite + DataFrameHeader::LENGTH;
                const util::index_t alignedLength =
                    util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);

                header.write(m_termBuffer, frameOffset, frameLength, termId);
                m_termBuffer.putBytes(
                    frameOffset + DataFrameHeader::LENGTH,
                    srcBuffer,
                    srcOffset + (length - remaining),
                    bytesToWrite);

                if (remaining <= maxPayloadLength)
                {
                    flags |= FrameDescriptor::END_FRAG;
                }

                FrameDescriptor::frameFlags(m_termBuffer, frameOffset, flags);

                const std::int64_t reservedValue = reservedValueSupplier(m_termBuffer, frameOffset, frameLength);
                m_termBuffer.putInt64(frameOffset + DataFrameHeader::RESERVED_VALUE_FIELD_OFFSET, reservedValue);

                FrameDescriptor::frameLengthOrdered(m_termBuffer, frameOffset, frameLength);

                flags = 0;
                frameOffset += alignedLength;
                remaining -= bytesToWrite;
            }
            while (remaining > 0);
        }

        return static_cast<std::int32_t>(resultingOffset);
    }

    template <class BufferIterator> std::int32_t appendFragmentedMessage(
        const HeaderWriter &header,
        BufferIterator bufferIt,
        util::index_t length,
        util::index_t maxPayloadLength,
        const on_reserved_value_supplier_t &reservedValueSupplier,
        std::int32_t activeTermId)
    {
        const int numMaxPayloads = length / maxPayloadLength;
        const util::index_t remainingPayload = length % maxPayloadLength;
        const util::index_t lastFrameLength = remainingPayload > 0 ?
            util::BitUtil::align(remainingPayload + DataFrameHeader::LENGTH, FrameDescriptor::FRAME_ALIGNMENT) : 0;
        const util::index_t requiredLength =
            (numMaxPayloads * (maxPayloadLength + DataFrameHeader::LENGTH)) + lastFrameLength;
        const std::int64_t rawTail = getAndAddRawTail(requiredLength);
        const std::int64_t termOffset = rawTail & 0xFFFFFFFF;
        const std::int32_t termId = LogBufferDescriptor::termId(rawTail);

        const std::int32_t termLength = m_termBuffer.capacity();

        checkTerm(activeTermId, termId);

        std::int64_t resultingOffset = termOffset + requiredLength;
        if (resultingOffset > termLength)
        {
            resultingOffset = handleEndOfLogCondition(m_termBuffer, termOffset, header, termLength, termId);
        }
        else
        {
            std::uint8_t flags = FrameDescriptor::BEGIN_FRAG;
            util::index_t remaining = length;
            auto frameOffset = static_cast<std::int32_t>(termOffset);
            util::index_t currentBufferOffset = 0;

            do
            {
                const util::index_t bytesToWrite = std::min(remaining, maxPayloadLength);
                const util::index_t frameLength = bytesToWrite + DataFrameHeader::LENGTH;
                const util::index_t alignedLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);

                header.write(m_termBuffer, frameOffset, frameLength, termId);

                util::index_t bytesWritten = 0;
                util::index_t payloadOffset = frameOffset + DataFrameHeader::LENGTH;
                do
                {
                    const util::index_t currentBufferRemaining = bufferIt->capacity() - currentBufferOffset;
                    const util::index_t numBytes = std::min(bytesToWrite - bytesWritten, currentBufferRemaining);

                    m_termBuffer.putBytes(payloadOffset, *bufferIt, currentBufferOffset, numBytes);

                    bytesWritten += numBytes;
                    payloadOffset += numBytes;
                    currentBufferOffset += numBytes;

                    if (currentBufferRemaining <= numBytes)
                    {
                        ++bufferIt;
                        currentBufferOffset = 0;
                    }
                }
                while (bytesWritten < bytesToWrite);

                if (remaining <= maxPayloadLength)
                {
                    flags |= FrameDescriptor::END_FRAG;
                }

                FrameDescriptor::frameFlags(m_termBuffer, frameOffset, flags);

                const std::int64_t reservedValue = reservedValueSupplier(m_termBuffer, frameOffset, frameLength);
                m_termBuffer.putInt64(frameOffset + DataFrameHeader::RESERVED_VALUE_FIELD_OFFSET, reservedValue);

                FrameDescriptor::frameLengthOrdered(m_termBuffer, frameOffset, frameLength);

                flags = 0;
                frameOffset += alignedLength;
                remaining -= bytesToWrite;
            }
            while (remaining > 0);
        }

        return static_cast<std::int32_t>(resultingOffset);
    }

private:
    AtomicBuffer &m_termBuffer;
    AtomicBuffer &m_tailBuffer;
    const util::index_t m_tailOffset;

    inline static void checkTerm(std::int32_t expectedTermId, std::int32_t termId)
    {
        if (termId != expectedTermId)
        {
            throw util::IllegalStateException(
                "action possibly delayed: expectedTermId=" + std::to_string(expectedTermId) +
                " termId=" + std::to_string(termId), SOURCEINFO);
        }
    }

    inline static std::int32_t handleEndOfLogCondition(
        AtomicBuffer &termBuffer,
        std::int64_t termOffset,
        const HeaderWriter& header,
        std::int32_t termLength,
        std::int32_t termId)
    {
        if (termOffset < termLength)
        {
            const auto offset = static_cast<std::int32_t>(termOffset);
            const std::int32_t paddingLength = termLength - offset;
            header.write(termBuffer, offset, paddingLength, termId);
            FrameDescriptor::frameType(termBuffer, offset, DataFrameHeader::HDR_TYPE_PAD);
            FrameDescriptor::frameLengthOrdered(termBuffer, offset, paddingLength);
        }

        return TERM_APPENDER_FAILED;
    }

    inline std::int64_t getAndAddRawTail(const util::index_t alignedLength)
    {
        return m_tailBuffer.getAndAddInt64(m_tailOffset, alignedLength);
    }
};

}}}

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bot. Jb. 30: 41 (1901)

#### Original name
Thelephora braunii Henn.

### Remarks
null


text:
Imports System.Text
Imports DlhSoft.Windows.Controls
Imports Microsoft.Win32
Imports System.IO
Imports DlhSoft.Windows.Data
Imports System.Collections.ObjectModel
Imports System.Windows.Threading

''' <summary>
''' Interaction logic for MainWindow.xaml
''' </summary>
Partial Public Class MainWindow
    Inherits Window

    Public Sub New()
        InitializeComponent()

        Dim task1 As GanttChartItem = ScheduleChartDataGrid.Items(0).GanttChartItems(0)
        task1.Start = Date.Today.Add(TimeSpan.Parse("08:00:00"))
        task1.Finish = Date.Today.Add(TimeSpan.Parse("16:00:00"))
        task1.CompletedFinish = Date.Today.Add(TimeSpan.Parse("12:00:00"))

        Dim task21 As GanttChartItem = ScheduleChartDataGrid.Items(0).GanttChartItems(1)
        task21.Start = Date.Today.AddDays(1).Add(TimeSpan.Parse("12:00:00"))
        task21.Finish = Date.Today.AddDays(2).Add(TimeSpan.Parse("16:00:00"))
        task21.AssignmentsContent = "50%"

        Dim task22 As GanttChartItem = ScheduleChartDataGrid.Items(1).GanttChartItems(0)
        task22.Start = Date.Today.AddDays(1).Add(TimeSpan.Parse("12:00:00"))
        task22.Finish = Date.Today.AddDays(2).Add(TimeSpan.Parse("16:00:00"))

        For i As Integer = 3 To 16
            Dim item As ScheduleChartItem = New ScheduleChartItem With {.Content = "Resource " & i}
            For j As Integer = 1 To (i - 1) Mod 4 + 1
                item.GanttChartItems.Add(New GanttChartItem With {.Content = "Task " & i & "." & j, .Start = Date.Today.AddDays(i + (i - 1) * (j - 1)), .Finish = Date.Today.AddDays(i * 1.2 + (i - 1) * (j - 1) + 1), .CompletedFinish = Date.Today.AddDays(i + (i - 1) * (j - 1)).AddDays(If((i + j) Mod 5 = 2, 2, 0))})
            Next j
            ScheduleChartDataGrid.Items.Add(item)
        Next i

        ' You may uncomment the next lines of code to test the component performance:
        ' for (int i = 17; i <= 1024; i++)
        ' {
        '    ScheduleChartItem item = new ScheduleChartItem { Content = "Resource " + i };
        '    for (int j = 1; j <= (i - 1) % 4 + 1; j++)
        '    {
        '        item.GanttChartItems.Add(
        '            new GanttChartItem
        '            {
        '                Content = "Task " + i + "." + j,
        '                Start = DateTime.Today.AddDays(i + (i - 1) * (j - 1)),
        '                Finish = DateTime.Today.AddDays(i * 1.2 + (i - 1) * (j - 1) + 1)
        '            });
        '    }
        '    ScheduleChartDataGrid.Items.Add(item);
        ' }

        ' Optionally, define custom schedules for resources, used when scheduling items assigned to those resources.
        ' ScheduleChartDataGrid.Items[1].Schedule = new Schedule(
        '     DayOfWeek.Tuesday, DayOfWeek.Saturday, // Working week: between Tuesday and Saturday.
        '     TimeSpan.Parse("07:00:00"), TimeSpan.Parse("15:00:00"), // Working day: between 7 AM and 3 PM.
        '     new TimeInterval[] { // Optionally, generic nonworking intervals.
        '         new TimeInterval(DateTime.Today.AddDays(14), DateTime.Today.AddDays(14).Add(TimeOfDay.MaxValue)), // Holiday: full day.
        '         new TimeInterval(DateTime.Today.AddDays(18), DateTime.Today.AddDays(20).Add(TimeSpan.Parse("12:00:00"))) // Custom time interval off: full and partial day accepted.
        '     },
        '     (date) => { // Optionally, specific nonworking intervals based on date parameter: recurrent breaks and holidays accepted.
        '         if (date.Day % 15 == 0) // First recurrence expression: on decade end days.
        '             return new DayTimeInterval[] {
        '                 new DayTimeInterval(TimeOfDay.MinValue, TimeOfDay.Parse("12:00:00")), // Large interval off: first part of day.
        '                 new DayTimeInterval(TimeOfDay.Parse("12:00:00"), TimeOfDay.Parse("12:30:00")) // Short break: fast lunch time.
        '             };
        '         else if (date.DayOfWeek != DayOfWeek.Monday) // Second recurrence expression: every day except Mondays.
        '             return new DayTimeInterval[] {
        '                 new DayTimeInterval(TimeOfDay.Parse("11:30:00"), TimeOfDay.Parse("12:30:00")) // Break: regular lunch time.
        '             };
        '         return null; // Otherwise use regular timing only.
        '     });

        ' Optionally, set AreHierarchyConstraintsEnabled to false to increase performance when you perform hierarchy validation in your application.
        ScheduleChartDataGrid.AreHierarchyConstraintsEnabled = False

        ' Initialize the control area.
        ScalesComboBox.SelectedIndex = 0
        ShowWeekendsCheckBox.IsChecked = True
    End Sub

    Private theme As String = "Generic-bright"
    Public Sub New(theme As String)
        Me.New()
        Me.theme = theme
        ApplyTemplate()
    End Sub
    Public Overrides Sub OnApplyTemplate()
        LoadTheme()
        MyBase.OnApplyTemplate()
    End Sub
    Private Sub LoadTheme()
        If theme Is Nothing OrElse theme = "Default" OrElse theme = "Aero" Then
            Return
        End If
        Dim themeResourceDictionary = New ResourceDictionary With {.Source = New Uri("/" & Me.GetType().Assembly.GetName().Name & ";component/Themes/" & theme & ".xaml", UriKind.Relative)}
        ScheduleChartDataGrid.Resources.MergedDictionaries.Add(themeResourceDictionary)
    End Sub

    ' Control area commands.
    Private Sub AddNewButton_Click(sender As Object, e As RoutedEventArgs)
        Dim item As ScheduleChartItem = New ScheduleChartItem With {.Content = "New Resource"}
        item.GanttChartItems.Add(New GanttChartItem With {.Content = "New Task", .Start = Date.Today, .Finish = Date.Today.AddDays(1)})
        ScheduleChartDataGrid.Items.Add(item)
        ScheduleChartDataGrid.SelectedItem = item
        ScheduleChartDataGrid.ScrollTo(item.GanttChartItems(0))
        ScheduleChartDataGrid.ScrollTo(item.GanttChartItems(0).Start)
    End Sub
    Private Sub InsertNewButton_Click(sender As Object, e As RoutedEventArgs)
        Dim selectedItem As ScheduleChartItem = TryCast(ScheduleChartDataGrid.SelectedItem, ScheduleChartItem)
        If selectedItem Is Nothing Then
            MessageBox.Show("Cannot insert a new item before selection as the selection is empty; you can either add a new item to the end of the list instead, or select an item first.", "Information", MessageBoxButton.OK)
            Return
        End If
        Dim item As ScheduleChartItem = New ScheduleChartItem With {.Content = "New Resource"}
        item.GanttChartItems.Add(New GanttChartItem With {.Content = "New Task", .Start = Date.Today, .Finish = Date.Today.AddDays(1)})
        ScheduleChartDataGrid.Items.Insert(selectedItem.Index, item)
        ScheduleChartDataGrid.SelectedItem = item
        ScheduleChartDataGrid.ScrollTo(item.GanttChartItems(0))
        ScheduleChartDataGrid.ScrollTo(item.GanttChartItems(0).Start)
    End Sub
    Private Sub DeleteButton_Click(sender As Object, e As RoutedEventArgs)
        Dim items As New List(Of ScheduleChartItem)()
        For Each item As ScheduleChartItem In ScheduleChartDataGrid.GetSelectedItems()
            items.Add(item)
        Next item
        If items.Count <= 0 Then
            MessageBox.Show("Cannot delete the selected item(s) as the selection is empty; select an item first.", "Information", MessageBoxButton.OK)
            Return
        End If
        items.Reverse()
        ' ScheduleChartDataGrid.BeginInit();
        For Each item As ScheduleChartItem In items
            ScheduleChartDataGrid.Items.Remove(item)
        Next item
        ' ScheduleChartDataGrid.EndInit();
    End Sub
    Private Sub SetColorButton_Click(sender As Object, e As RoutedEventArgs)
        Dim items As New List(Of ScheduleChartItem)()
        For Each item As ScheduleChartItem In ScheduleChartDataGrid.GetSelectedItems()
            items.Add(item)
        Next item
        If items.Count <= 0 Then
            MessageBox.Show("Cannot set a custom bar color to the selected item(s) as the selection is empty; select an item first.", "Information", MessageBoxButton.OK)
            Return
        End If
        For Each item As ScheduleChartItem In items
            For Each ganttChartItem As GanttChartItem In item.GanttChartItems
                GanttChartView.SetStandardBarFill(ganttChartItem, TryCast(Resources("CustomStandardBarFill"), Brush))
                GanttChartView.SetStandardBarStroke(ganttChartItem, TryCast(Resources("CustomStandardBarStroke"), Brush))
            Next ganttChartItem
        Next item
    End Sub
    Private Sub CopyButton_Click(sender As Object, e As RoutedEventArgs)
        If ScheduleChartDataGrid.GetSelectedItemCount() <= 0 Then
            MessageBox.Show("Cannot copy selected item(s) as the selection is empty; select an item first.", "Information", MessageBoxButton.OK)
            Return
        End If
        ScheduleChartDataGrid.Copy()
    End Sub
    Private Sub PasteButton_Click(sender As Object, e As RoutedEventArgs)
        ScheduleChartDataGrid.Paste()
    End Sub
    Private Sub UndoButton_Click(sender As Object, e As RoutedEventArgs)
        If ScheduleChartDataGrid.CanUndo() Then
            ScheduleChartDataGrid.Undo()
        Else
            MessageBox.Show("Currently there is no recorded action in the undo queue; perform an action first.", "Information", MessageBoxButton.OK)
        End If
    End Sub
    Private Sub RedoButton_Click(sender As Object, e As RoutedEventArgs)
        If ScheduleChartDataGrid.CanRedo() Then
            ScheduleChartDataGrid.Redo()
        Else
            MessageBox.Show("Currently there is no recorded action in the redo queue; perform an action and undo it first.", "Information", MessageBoxButton.OK)
        End If
    End Sub
    Private Sub ScaleTypeComboBox_SelectionChanged(sender As Object, e As SelectionChangedEventArgs)
        Dim selectedComboBoxItem As ComboBoxItem = TryCast(ScalesComboBox.SelectedItem, ComboBoxItem)
        Dim scalesResourceKey As String = TryCast(selectedComboBoxItem.Tag, String)
        Dim scales As ScaleCollection = TryCast(Resources(scalesResourceKey), ScaleCollection)
        ScheduleChartDataGrid.Scales = scales
    End Sub
    Private Sub ZoomCheckBox_Checked(sender As Object, e As RoutedEventArgs)
        originalZoom = ScheduleChartDataGrid.HourWidth
        ScheduleChartDataGrid.HourWidth = originalZoom * 2
    End Sub
    Private Sub ZoomCheckBox_Unchecked(sender As Object, e As RoutedEventArgs)
        ScheduleChartDataGrid.HourWidth = originalZoom
    End Sub
    Private originalZoom As Double
    Private Sub IncreaseTimelinePageButton_Click(sender As Object, e As RoutedEventArgs)
        ScheduleChartDataGrid.TimelinePageFinish += pageUpdateAmount
        ScheduleChartDataGrid.TimelinePageStart += pageUpdateAmount
    End Sub
    Private Sub DecreaseTimelinePageButton_Click(sender As Object, e As RoutedEventArgs)
        ScheduleChartDataGrid.TimelinePageFinish -= pageUpdateAmount
        ScheduleChartDataGrid.TimelinePageStart -= pageUpdateAmount
    End Sub
    Private ReadOnly pageUpdateAmount As TimeSpan = TimeSpan.FromDays(7)
    Private Sub ShowWeekendsCheckBox_Checked(sender As Object, e As RoutedEventArgs)
        ScheduleChartDataGrid.VisibleWeekStart = DayOfWeek.Sunday
        ScheduleChartDataGrid.VisibleWeekFinish = DayOfWeek.Saturday
        WorkOnWeekendsCheckBox.IsEnabled = True
    End Sub
    Private Sub ShowWeekendsCheckBox_Unchecked(sender As Object, e As RoutedEventArgs)
        WorkOnWeekendsCheckBox.IsChecked = False
        WorkOnWeekendsCheckBox.IsEnabled = False
        ScheduleChartDataGrid.VisibleWeekStart = DayOfWeek.Monday
        ScheduleChartDataGrid.VisibleWeekFinish = DayOfWeek.Friday
    End Sub
    Private Sub WorkOnWeekendsCheckBox_Checked(sender As Object, e As RoutedEventArgs)
        ScheduleChartDataGrid.WorkingWeekStart = DayOfWeek.Sunday
        ScheduleChartDataGrid.WorkingWeekFinish = DayOfWeek.Saturday
    End Sub
    Private Sub WorkOnWeekendsCheckBox_Unchecked(sender As Object, e As RoutedEventArgs)
        ScheduleChartDataGrid.WorkingWeekStart = DayOfWeek.Monday
        ScheduleChartDataGrid.WorkingWeekFinish = DayOfWeek.Friday
    End Sub
    Private Sub PrintButton_Click(sender As Object, e As RoutedEventArgs)
        ScheduleChartDataGrid.Print("ScheduleChartDataGrid Sample Document")
    End Sub
    Private Sub ExportImageButton_Click(sender As Object, e As RoutedEventArgs)
        ScheduleChartDataGrid.Export(CType(Sub()
                                               Dim saveFileDialog As SaveFileDialog = New SaveFileDialog With {.Title = "Export Image To", .Filter = "PNG image files|*.png"}
                                               If Not saveFileDialog.ShowDialog().Equals(True) Then
                                                   Return
                                               End If
                                               Dim bitmapSource As BitmapSource = ScheduleChartDataGrid.GetExportBitmapSource(96 * 2)
                                               Using stream As Stream = saveFileDialog.OpenFile()
                                                   Dim pngBitmapEncoder As New PngBitmapEncoder()
                                                   pngBitmapEncoder.Frames.Add(BitmapFrame.Create(bitmapSource))
                                                   pngBitmapEncoder.Save(stream)
                                               End Using
                                           End Sub, Action))
    End Sub
End Class


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace MCEBuddy.GUI
{
    /// <summary>
    /// A slightly extended version of the standard ListView.
    /// It has two additional properties to draw an insertion line before or after an item.
    /// </summary>
    public class ListViewEx : ListView
    {
        // from WinUser.h
        private const int WM_PAINT = 0x000F;

        public ListViewEx()
        {
            // Reduce flicker
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        }

        private int _LineBefore = -1;
        /// <summary>
        /// If set to a value >= 0, an insertion line is painted before the item with the given index.
        /// </summary>
        public int LineBefore
        {
            get { return _LineBefore; }
            set { _LineBefore = value; }
        }

        private int _LineAfter = -1;
        /// <summary>
        /// If set to a value >= 0, an insertion line is painted after the item with the given index.
        /// </summary>
        public int LineAfter
        {
            get { return _LineAfter; }
            set { _LineAfter = value; }
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            // We have to take this way (instead of overriding OnPaint()) because the ListView is just a wrapper
            // around the common control ListView and unfortunately does not call the OnPaint overrides.
            if (m.Msg == WM_PAINT)
            {
                try
                {
                    if (LineBefore >= 0 && LineBefore < Items.Count)
                    {
                        Rectangle rc = Items[LineBefore].GetBounds(ItemBoundsPortion.Entire);
                        DrawInsertionLine(rc.Left, rc.Right, rc.Top);
                    }
                    if (LineAfter >= 0 && LineBefore < Items.Count)
                    {
                        Rectangle rc = Items[LineAfter].GetBounds(ItemBoundsPortion.Entire);
                        DrawInsertionLine(rc.Left, rc.Right, rc.Bottom);
                    }
                }
                catch { }
            }
        }

        /// <summary>
        /// Draw a line with insertion marks at each end
        /// </summary>
        /// <param name="X1">Starting position (X) of the line</param>
        /// <param name="X2">Ending position (X) of the line</param>
        /// <param name="Y">Position (Y) of the line</param>
        private void DrawInsertionLine(int X1, int X2, int Y)
        {
            using (Graphics g = this.CreateGraphics())
            {
                g.DrawLine(Pens.Red, X1, Y, X2 - 1, Y);

                Point[] leftTriangle = new Point[3] {
                            new Point(X1,      Y-4),
                            new Point(X1 + 7,  Y),
                            new Point(X1,      Y+4)
                        };
                Point[] rightTriangle = new Point[3] {
                            new Point(X2,     Y-4),
                            new Point(X2 - 8, Y),
                            new Point(X2,     Y+4)
                        };
                g.FillPolygon(Brushes.Red, leftTriangle);
                g.FillPolygon(Brushes.Red, rightTriangle);
            }
        }
    }
}


text:
require(File.expand_path(File.dirname(__FILE__)+'/../helpers_benchmark.rb'))
require 'statsample'
require 'benchmark'

def create_dataset(vars,cases)
  ran = Distribution::Normal.rng
  ds  = Daru::DataFrame.new(
    vars.times.inject({}) do |ac,v|
      ac["x#{v}".to_sym] = Daru::Vector.new_with_size(cases) {ran.call}
      ac
    end
  )
end

def prediction_pairwise(vars,cases)
	Statsample::Bivariate.prediction_pairwise(vars,cases) / 10
end
def prediction_optimized(vars,cases)
	Statsample::Bivariate.prediction_optimized(vars,cases) / 10
end

if !File.exists?("correlation_matrix.ds") or File.mtime(__FILE__) > File.mtime("correlation_matrix.ds")
reps=100 #number of repetitions
ds_sizes=[5,10,30,50,100,150,200,500,1000]
ds_vars=[3,4,5,10,20,30,40]
#ds_sizes=[5,10]
#ds_vars=[3,5,20]
rs = Daru::DataFrame.new({}, order: [:cases, :vars, :time_optimized, :time_pairwise])

ds_sizes.each do |cases|
  ds_vars.each do |vars|
      ds = create_dataset(vars,cases)
      time_optimized= Benchmark.realtime do
        reps.times {
        Statsample::Bivariate.correlation_matrix_optimized(ds)
        ds.clear_gsl
        }
      end

      time_pairwise= Benchmark.realtime do
        reps.times { Statsample::Bivariate.correlation_matrix_pairwise(ds) }
      end

      puts "Cases:#{cases}, vars:#{vars} -> opt:%0.3f (%0.3f) | pair: %0.3f (%0.3f)" % [time_optimized, prediction_optimized(vars,cases), time_pairwise, prediction_pairwise(vars,cases)]

      rs.add_row(Daru::Vector.new({
        :cases          => cases,
        :vars           => vars,
        :time_optimized => Math.sqrt(time_optimized*1000),
        :time_pairwise  =>Math.sqrt(time_pairwise*1000)
        })
      )
    end
  end
else
  rs=Statsample.load("correlation_matrix.ds")
end

rs[:c_v] = rs.collect {|row| row[:cases]*row[:vars]}

rs.update
rs.save("correlation_matrix.ds")
Statsample::Excel.write(rs,"correlation_matrix.xls")

rb = ReportBuilder.new(:name=>"Correlation matrix analysis")

rb.add(Statsample::Regression.multiple(rs[:cases,:vars,:time_optimized,:c_v],:time_optimized, :digits=>6))
rb.add(Statsample::Regression.multiple(rs[:cases,:vars,:time_pairwise,:c_v],:time_pairwise, :digits=>6))

rb.save_html("correlation_matrix.html")


text:
from pathpicker.key_bindings import KeyBindings

KEY_BINDINGS_FOR_TEST_CONFIG_CONTENT: str = "[bindings]\nr = rspec\ns = subl\n"
KEY_BINDINGS_FOR_TEST: KeyBindings = KeyBindings(
    [
        ("r", "rspec"),
        ("s", "subl"),
    ]
)


text:
/*
 * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
 */
package org.ligoj.app.http.proxy;

import java.io.IOException;

import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

/**
 * HTML proxying test of {@link HtmlProxyFilter} class ..
 */
class HtmlProxyFilterTest {

	/**
	 * Test forward without locale.
	 */
	@Test
	void testUseCaseForwardNoLocale() throws IOException, ServletException {
		checkForwardTo("/index.html", "/index.html", "");
	}

	/**
	 * Test forward from root URL.
	 */
	@Test
	void testUseCaseForwardRoot() throws IOException, ServletException {
		checkForwardTo("/", "/index.html", "");
	}

	/**
	 * Test forward from not index/login URL.
	 */
	@Test
	void testUseCaseForwardNotRoot() throws IOException, ServletException {
		checkForwardTo("/any.html", "/any.html", "");
	}

	/**
	 * Test forward from login URL.
	 */
	@Test
	void testUseCaseForwardLogin() throws IOException, ServletException {
		checkForwardTo("/login.html", "/login.html", "");
	}

	/**
	 * Test forward from root, without context URL.
	 */
	@Test
	void testUseCaseForwardRoot2() throws IOException, ServletException {
		checkForwardTo("", "/index.html", "");
	}

	/**
	 * Test use case forward.
	 */
	private void checkForwardTo(final String from, final String to, final String suffix) throws IOException, ServletException {
		final HtmlProxyFilter htmlProxyFilter = new HtmlProxyFilter();
		htmlProxyFilter.setSuffix(suffix);

		final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
		final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
		Mockito.when(request.getServletPath()).thenReturn(from);
		final RequestDispatcher requestDispatcher = Mockito.mock(RequestDispatcher.class);
		Mockito.when(request.getRequestDispatcher(to)).thenReturn(requestDispatcher);
		Mockito.when(request.getDispatcherType()).thenReturn(DispatcherType.REQUEST);
		htmlProxyFilter.doFilter(request, response, null);
		Mockito.verify(requestDispatcher, Mockito.atLeastOnce()).forward(request, response);
		Mockito.validateMockitoUsage();
	}

}


text:
/*
* Author: Alexander Miller
* Date: 10/13/2014
*/

#include <iostream>
#include <thread>
#include <vector>
#include <chrono>

using namespace std;
using namespace std::chrono;

vector<thread> threads;
vector<long long> inputVector;
bool developer = true;
int numPrimes;

class PrimeNumber
{
	long long initValue;		// the number being prime factored
	vector<long long> factors;  // all of the factor values
public:
	void setInitValue(long long n)
	{
		initValue = n;
	}
	void addToVector(long long m)
	{
		factors.push_back(m);
	}
	void setVector(vector<long long> m)
	{
		factors = m;
	}
	long long getInitValue()
	{
		return initValue;
	}
	vector<long long> getVector()
	{
		return factors;
	}
};

vector<PrimeNumber> primes;

// find primes recursively and have them returned in vectors
vector<long long> getPrimes(long long n, vector<long long> vec)
{
	if (n % 2 == 0)
	{
		return vec.push_back(2), getPrimes(n / 2, vec); //cause recursion
	}

	if (n % 3 == 0)
	{
		return vec.push_back(3), getPrimes(n / 3, vec); //cause recursion
	}

	double sqrt_of_n = sqrt(n);

	for (int i = 5; i <= sqrt_of_n; i = i + 2)
	{
		if (n % i == 0)
		{
			return vec.push_back(i), getPrimes(n / i, vec); //cause recursion
		}
	}

	// pick up the last prime factorization number
	vec.push_back(n);

	//return the finished vector
	return vec;
}

void getUserInput()
{
	long long input = -1;
	cout << "Enter all of the numbers to find their prime factors. Enter 0 to compute" << endl;
	do
	{
		cin >> input;
		if (input >= 9223372036854775807)
		{
			cout << "Sorry but that number is too large. Please try a smaller number" << endl;
			cin >> input;
		}

		if (input == 0)
		{
			break;
		}

		inputVector.push_back(input);
	} while (input != 0);
}

int main()
{
	vector<long long> temp1;   // empty vector
	vector<long long> result1; // temp vector

	if (developer == false)
	{
		getUserInput();
	}
	else
	{
		cout << "developer mode active" << endl;
		cout << endl;

		long long m1 = 781859189285709554;
		long long m2 = 782050905290201849;
		long long m3 = 349956174030208996;
		long long m4 = 869723665327180202;

		inputVector.push_back(m1);
		inputVector.push_back(m2);
		inputVector.push_back(m3);
		inputVector.push_back(m4);
	}

	high_resolution_clock::time_point time1 = high_resolution_clock::now();

	if (inputVector.size() % 4 == 0)
	{
		// finding out the points in the array to optimize the run time
		int fourth = inputVector.size() / 4;
		int half = inputVector.size() / 2;
		int threeFourth = half + fourth;

		// give each thread a number to comput within the recursive function
		for (int i = 0; i < fourth; i++)
		{
			threads.push_back(thread([&]{
				PrimeNumber prime;
				prime.setInitValue(inputVector.at(i));
				prime.setVector(result1 = getPrimes(inputVector.at(i), temp1));
				primes.push_back(prime);
			}));
		}

		// give each thread a number to comput within the recursive function
		for (int i = fourth; i < half; i++)
		{
			threads.push_back(thread([&]{
				PrimeNumber prime;
				prime.setInitValue(inputVector.at(i));
				prime.setVector(result1 = getPrimes(inputVector.at(i), temp1));
				primes.push_back(prime);
			}));
		}

		// give each thread a number to comput within the recursive function
		for (int i = half; i < threeFourth; i++)
		{
			threads.push_back(thread([&]{
				PrimeNumber prime;
				prime.setInitValue(inputVector.at(i));
				prime.setVector(result1 = getPrimes(inputVector.at(i), temp1));
				primes.push_back(prime);
			}));
		}

		// give each thread a number to comput within the recursive function
		for (int i = threeFourth; i < inputVector.size(); i++)
		{
			threads.push_back(thread([&]{
				PrimeNumber prime;
				prime.setInitValue(inputVector.at(i));
				prime.setVector(result1 = getPrimes(inputVector.at(i), temp1));
				primes.push_back(prime);
			}));
		}

	}
	else
	{
		// give each thread a number to comput within the recursive function
		for (int i = 0; i < inputVector.size(); i++)
		{
			threads.push_back(thread([&]{
				PrimeNumber prime;
				prime.setInitValue(inputVector.at(i));
				prime.setVector(result1 = getPrimes(inputVector.at(i), temp1));
				primes.push_back(prime);
			}));
		}
	}

	// allow all of the threads to join back together.
	for (auto& th : threads)
	{
		th.join();
	}

	high_resolution_clock::time_point time2 = high_resolution_clock::now();

	// print all of the information
	for (int i = 0; i < primes.size(); i++)
	{
		cout << "Factorization of: " << primes.at(i).getInitValue() << endl;
		vector<long long> temp = primes.at(i).getVector();
		cout << "Prime: ";
		for (int m = 0; m < temp.size(); m++)
		{
			cout << temp.at(m) << " ";
			numPrimes++;
		}
		cout << endl;
		cout << endl;
	}

	cout << endl;

	cout << "There are " << numPrimes << " Primes" <<  endl;

	cout << endl;

	// so the running time
	auto duration = duration_cast<microseconds>(time2 - time1).count();

	cout << "Duration in seconds: " << (duration / 1000000.0) << endl;

	return 0;
}