text:
namespace IronFoundry.Bosh.Utilities
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Management;
    using System.Net;
    using IronFoundry.Misc.Logging;
    using IronFoundry.Misc.Utilities;

    /*
     * TODO:
     * set ip address
       netsh interface ipv4 set address name="Local Area Connection" source=static address=%1 mask=%2 gateway=%3
       netsh interface ipv4 set dns name="Local Area Connection" source=static addr=%4
       netsh interface ipv4 add dns name="Local Area Connection" addr=%5
     */
    public class NetworkConfigurator
    {
        private static readonly TimeSpan NetworkConfiguratorWaitInterval = TimeSpan.FromSeconds(5);

        private readonly ILog log;

        private const string NetshFmt = @"interface ipv4 set address name=""{0}"" source=static address={1} mask={2} gateway={3}";
        private const string NetshFirstDnsFmt = @"interface ipv4 set dns name=""{0}"" source=static addr={1}";
        private const string NetshRestDnsFmt = @"interface ipv4 add dns name=""{0}"" addr={1}";

        public NetworkConfigurator(ILog log)
        {
            this.log = log;
            this.NetworkConfigured = GetNetworkConfigured();
        }

        public bool NetworkConfigured
        {
            get;
            private set;
        }

        /// <summary>
        /// NB: can block if error happens with "netsh" command.
        /// </summary>
        public bool ConfigureNetwork(string argIP, string argNetmask, string argGateway, IEnumerable<string> argDns)
        {
            IPAddress ip, netmask, gateway;
            var dnsAddrs = new List<IPAddress>();
            try
            {
                ip = IPAddress.Parse(argIP);
                netmask = IPAddress.Parse(argNetmask);
                gateway = IPAddress.Parse(argGateway);
                if (false == argDns.IsNullOrEmpty())
                {
                    dnsAddrs.AddRange(argDns.Select(d => IPAddress.Parse(d)));
                }
            }
            catch (FormatException ex)
            {
                throw new ArgumentException("Invalid IP argument!", ex);
            }

            ConnectionInfo ci = GetFirstEthernetConnectionInfo();

            string netshArgs = String.Format(NetshFmt, ci.NetConnectionID, ip.ToString(), netmask.ToString(), gateway.ToString());

            bool success = false;
            var exec = new ExecCmd(log, "netsh", netshArgs);
            ExecCmdResult rslt = exec.Run(5, NetworkConfiguratorWaitInterval);
            success = rslt.Success;
            if (rslt.Success)
            {
                bool firstDns = true;
                foreach (var dnsAddress in dnsAddrs)
                {
                    if (firstDns)
                    {
                        netshArgs = String.Format(NetshFirstDnsFmt, ci.NetConnectionID, dnsAddress.ToString());
                        firstDns = false;
                    }
                    else
                    {
                        netshArgs = String.Format(NetshRestDnsFmt, ci.NetConnectionID, dnsAddress.ToString());
                    }
                    exec = new ExecCmd(log, "netsh", netshArgs);
                    rslt = exec.Run(5, NetworkConfiguratorWaitInterval);
                    success = rslt.Success;
                    if (false == success)
                    {
                        break;
                    }
                }
            }

            if (success)
            {
                this.NetworkConfigured = true;
            }

            return success;
        }

        private bool GetNetworkConfigured()
        {
            /*
             * Check Win32_NetworkAdapterConfiguration - DHCPEnabled or IPAddress 169.254.X.X means not configured!
             * http://packetlife.net/blog/2008/sep/24/169-254-0-0-addresses-explained/
             */
            ConnectionInfo ci = GetFirstEthernetConnectionInfo();

            ManagementObject mo = ci.ManagementObject;
            ManagementObject adapterConfiguration = mo.GetRelated("Win32_NetworkAdapterConfiguration").Cast<ManagementObject>().First();

            bool dhcpEnabled = (bool)adapterConfiguration["DHCPEnabled"];
            bool apipaAddressPresent = ((string[])adapterConfiguration["IPAddress"]).Any(ip => ip.StartsWith("169.254."));

            return false == dhcpEnabled && false == apipaAddressPresent;
        }

        private class ConnectionInfo
        {
            public string NetConnectionID { get; set; }
            public ManagementObject ManagementObject { get; set; }
        }

        private static ConnectionInfo GetFirstEthernetConnectionInfo()
        {
            var ms = new ManagementScope(@"\root\cimv2");
            var query = new SelectQuery("Win32_NetworkAdapter",
                "AdapterTypeId = '0' AND Availability = '3' AND ConfigManagerErrorCode = '0' AND NetConnectionStatus = '2' AND NetEnabled = 'True'");
            var searcher = new ManagementObjectSearcher(ms, query);
            var managementObject = searcher.Get().Cast<ManagementObject>().First();
            return new ConnectionInfo
                {
                    NetConnectionID = (string)managementObject["NetConnectionID"],
                    ManagementObject = managementObject,
                };
        }
    }
}


text:
package sr.entityset.io.converters;

import org.joda.time.DateTime;

public interface IJodaDateTimeConverter {

	public abstract String dateTimeToString(DateTime dateValue) throws Exception;

	public abstract DateTime stringToDateTime(String stringValue) throws Exception;

}

redpajama_set_name: RedPajamaGithub


text:
#region License
// The MIT License (MIT)
// Copyright (c) 2013-2014 Hypnocube, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using System;
using System.Collections.Generic;

namespace Hypnocube.Demo.Model.Demos
{
    internal class Heartbeat : DemoBase
    {
        private List<Beat> beats;

        public Heartbeat(int w, int h) : base(w, h)
        {
        }

        public override void Update()
        {
            base.Update();

            var numBeats = 3;
            if (beats == null || numBeats != beats.Count)
            {
                beats = new List<Beat>();
                for (var i = 0; i < numBeats; ++i)
                {
                    var b = new Beat();
                    b.x = Rand.Next(Width);
                    b.dx = (Rand.Next(3) - 1.5)/3.0;
                    beats.Add(b);
                    b.h = 1.0/(numBeats)*i;
                    b.param = Rand.NextDouble();
                }
            }

            Fade(0, 0, 0, 0.04);

            foreach (var beat in beats)
            {
                var x1 = (int) (beat.x + Math.Sin(Frame/10.0*beat.param)*2);
                var x2 = (int) (beat.x + Math.Cos(Frame/13.0*beat.param)*2);
                beat.x += beat.dx;
                if (beat.x < 0 || Width <= beat.x)
                {
                    beat.dx = -beat.dx;
                    beat.x += beat.dx;
                }

                var y =
                    (int)
                        ((Math.Sin(beat.param*Frame/10.0 + Frame/20.0 /*+Math.Cos(beat.param+frame/15.0)*/) + 1)/2.0*
                         Height/2.0);

                int r, g, b;

                DrawLine(x1, y, x2, Height - 1 - y, (i, j) =>
                {
                    var dy = Math.Abs(Height/2.0 - j)/(Height/2.0);
                    dy = (dy + 1)/2*0.8;
                    HslToRgb(beat.h, dy, 0.5, out r, out g, out b);
                    MaxPixel(i, j, r, g, b);
                });

                HslToRgb(beat.h, 1.0, 0.5, out r, out g, out b);
                MaxPixel(x1, y, r, g, b);
                MaxPixel(x2, Height - 1 - y, r, g, b);

                beat.h = beat.h + 0.001;
                if (beat.h > 1) beat.h -= 1;
            }
        }

        #region Nested type: Beat

        private class Beat
        {
            public double dx;
            public double h;
            public double param;
            public double x;
        }

        #endregion
    }
}


text:
'use strict';

var fs = require('fs');

var dropOSMTableScript = fs.readFileSync( require.resolve('./dropOSMTable.sql') ).toString();

module.exports = function(db){
    console.warn('\n\t=====\n\nWARNING! Dropping OSM tables!\n\n\t=====\n');

    return new Promise(function(resolve, reject){
        db.query(dropOSMTableScript, function(err, result) {
            if(err)
                reject('Coudn\'t drop OSM table: ' + err);
            else resolve(result);
        });
    });
};


text:
import * as React from 'react';

import Bundle from './Bundle';
const  loadAppRoutes = require('bundle-loader?lazy!./AppRoutes');
const  loadGlobalComponents = require('bundle-loader?lazy!./GlobalComponents');

export default class MainContent extends React.Component<any,any> {

  render() {
    const defaultProps = {...this.props,basePath: '/'};
    return (
      <div>
        <Bundle load={loadAppRoutes}>
          {(AppRoutes) => (AppRoutes
            ? <AppRoutes {...defaultProps} />
            : null
          )}
        </Bundle>
        <Bundle load={loadGlobalComponents}>
          {(GlobalComponents) => (GlobalComponents
            ? <GlobalComponents />
            : null
          )}
        </Bundle>
      </div>
    );
  }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>Peach.group</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

Peach API

        Package Peach ::
        Module group

[hide private]

Module group

source code

Default included Group implementations.

Author:
        Michael Eddington

Version:
        $Id: group.py 2020 2010-04-14 23:13:14Z meddingt $

        Classes
        [hide private]

        Group

      Groups allow for performing a next() call on a
        specific set of Generators allowing for more complex Fuzzing
        setups.

        GroupCompleted

      Raised when group has completed all iterations.

        GroupSequence

      A sequence of groups.

        GroupForever

      This group will take a GroupSequence and perform random mutations on
      how generators are incremented.

        GroupFixed

      Group object with a fixed number of iterations.

        GroupForeachDo

      Foreach iteration of group A do group B

         Home

         Trees

         Indices

         Help

Peach API

    Generated by Epydoc 3.0.1 on Thu Apr 15 18:19:28 2010

      http://epydoc.sourceforge.net


text:
/**
 * Extends {Object} with exists() method if method unavailable.
 * Checks whether object instance exists (is defined and not null).
 * @param  {object} obj   Object instance whose existance is being checked
 * @return {Boolean}      'true' if object defined and not null, 'false' otherwise
 * @author Tomislav Capan
 */
Object.exists = Object.exists || function(obj) {
  return 'undefined' !== typeof obj && null !== obj && 'null' !== obj;
};


text:
package org.apache.kerberos.kerb.spec.common;

import org.apache.haox.asn1.type.Asn1FieldInfo;
import org.apache.haox.asn1.type.Asn1Integer;
import org.apache.haox.asn1.type.Asn1OctetString;
import org.apache.kerberos.kerb.spec.KrbSequenceType;

import java.nio.ByteBuffer;
import java.util.Map;

/**
 KRB-TOKEN_VALUE ::= SEQUENCE {
    token-format [0] INTEGER,
    token-value  [1] OCTET STRING,
 }
 */
public class KrbToken extends KrbSequenceType {
    private static KrbTokenEncoder tokenEncoder;

    private static int TOKEN_FORMAT = 0;
    private static int TOKEN_VALUE = 1;

    private Map<String, Object> attributes;

    static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] {
            new Asn1FieldInfo(TOKEN_FORMAT, 0, Asn1Integer.class),
            new Asn1FieldInfo(TOKEN_VALUE, 1, Asn1OctetString.class)
    };

    public KrbToken() {
        super(fieldInfos);
    }

    @Override
    public void encode(ByteBuffer buffer) {
        setTokenValue(tokenEncoder.encode(this));
        super.encode(buffer);
    }

    /*
    @Override
    public void decode(ByteBuffer content) throws IOException {
        super.decode(content);
        this.attributes = tokenEncoder.decode(this);
    }
    */

    public static void setTokenEncoder(KrbTokenEncoder encoder) {
        tokenEncoder = encoder;
    }

    public TokenFormat getTokenFormat() {
        Integer value = getFieldAsInteger(TOKEN_FORMAT);
        return TokenFormat.fromValue(value);
    }

    public void setTokenFormat(TokenFormat tokenFormat) {
        setFieldAsInt(TOKEN_FORMAT, tokenFormat.getValue());
    }

    public byte[] getTokenValue() {
        return getFieldAsOctets(TOKEN_VALUE);
    }

    public void setTokenValue(byte[] tokenValue) {
        setFieldAsOctets(TOKEN_VALUE, tokenValue);
    }

    public Map<String, Object> getAttributes() {
        if (attributes == null) {
            this.attributes = tokenEncoder.decode(this);
        }
        return attributes;
    }

    public String getPrincipal() {
        return (String) attributes.get("sub");
    }

}


text:
module Fix
  module Protocol
    module Messages
      class NewOrderSingle < Message
        EXEC_INST_TYPES = {
          ok_to_cross: 'B',
          best_price: 'P'
        }.freeze

        ORDER_TYPE_TYPES = {
          market: '1',
          limit:  '2',
          stop:   '3',
          stop_limit: '4',
          previously_quoted: 'D'
        }.freeze

        TIME_IN_FORCE_TYPES = {
          day: '0',
          gtc: '1',
          ioc: '3',
          fok: '4',
          gtd: '6'
        }.freeze

        unordered :body do
          # common fields
          field :app_ver_id,      tag: 1128
          field :sender_comp_id,  tag: 49,    required: true
          field :target_comp_id,  tag: 56,    required: true
          field :msg_seq_num,     tag: 34,    required: true, type: :integer
          field :sending_time,    tag: 52,    required: true, type: :timestamp, default: proc { Time.now.utc }

          field :sender_sub_id, tag: 50
          field :deliver_to_comp_id, tag: 128
          field :cl_ord_id,     tag: 11, required: true
          field :currency,      tag: 15, required: true
          field :exec_inst,     tag: 18, required: true, mapping: EXEC_INST_TYPES
          field :handl_inst,    tag: 21
          field :order_qty,     tag: 38, required: true, type: :qty
          field :ord_type,      tag: 40, required: true, mapping: ORDER_TYPE_TYPES
          field :side,          tag: 54, required: true
          field :symbol,        tag: 55, required: true
          field :time_in_force, tag: 59, required: true, mapping: TIME_IN_FORCE_TYPES
          field :transact_time, tag: 60, required: true, type: :timestamp, default: proc { Time.now.utc }
          field :min_qty,       tag: 110, required: true, type: :qty
          field :security_type, tag: 167, required: true
          field :product,       tag: 460, required: true, type: :integer
        end
      end
    end
  end
end


text:
package org.apache.ignite.internal.processors.cache.persistence.db.wal;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.pagemem.wal.IgniteWriteAheadLogManager;
import org.apache.ignite.internal.pagemem.wal.WALIterator;
import org.apache.ignite.internal.pagemem.wal.WALPointer;
import org.apache.ignite.internal.pagemem.wal.record.WALRecord;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIO;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory;
import org.apache.ignite.internal.processors.cache.persistence.file.RandomAccessFileIOFactory;
import org.apache.ignite.internal.processors.cache.persistence.wal.FileDescriptor;
import org.apache.ignite.internal.processors.cache.persistence.wal.FileWALPointer;
import org.apache.ignite.internal.processors.cache.persistence.wal.reader.IgniteWalIteratorFactory;
import org.apache.ignite.internal.processors.cache.persistence.wal.reader.IgniteWalIteratorFactory.IteratorParametersBuilder;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Assert;
import org.junit.Test;

import static java.nio.ByteBuffer.allocate;
import static java.nio.file.StandardOpenOption.WRITE;
import static java.util.concurrent.ThreadLocalRandom.current;

/**
 *
 */
public class IgniteWALTailIsReachedDuringIterationOverArchiveTest extends GridCommonAbstractTest {
    /** WAL segment size. */
    private static final int WAL_SEGMENT_SIZE = 10 * 1024 * 1024;

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String name) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(name);

        cfg.setDataStorageConfiguration(
            new DataStorageConfiguration()
                .setWalSegmentSize(WAL_SEGMENT_SIZE)
                .setWalSegments(2)
                .setDefaultDataRegionConfiguration(
                    new DataRegionConfiguration()
                        .setPersistenceEnabled(true)
                )
        );

        cfg.setCacheConfiguration(new CacheConfiguration(DEFAULT_CACHE_NAME));

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        super.beforeTest();

        cleanPersistenceDir();

        Ignite ig = startGrid();

        ig.cluster().active(true);

        try (IgniteDataStreamer<Integer, byte[]> st = ig.dataStreamer(DEFAULT_CACHE_NAME)){
            st.allowOverwrite(true);

            byte[] payload = new byte[1024];

            // Generate WAL segment files.
            for (int i = 0; i < 100 * 1024; i++)
                st.addData(i, payload);
        }
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        super.afterTest();

        stopAllGrids();

        cleanPersistenceDir();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStandAloneIterator() throws Exception {
        IgniteEx ig = grid();

        IgniteWriteAheadLogManager wal = ig.context().cache().context().wal();

        File walArchiveDir = U.field(wal, "walArchiveDir");

        IgniteWalIteratorFactory iteratorFactory = new IgniteWalIteratorFactory();

        doTest(wal, iteratorFactory.iterator(walArchiveDir));
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testWALManagerIterator() throws Exception {
        IgniteEx ig = grid();

        IgniteWriteAheadLogManager wal = ig.context().cache().context().wal();

        doTest(wal, wal.replay(null));
    }

    /**
     *
     * @param walMgr WAL manager.
     * @param it WAL iterator.
     * @throws IOException If IO exception.
     * @throws IgniteCheckedException If WAL iterator failed.
     */
    private void doTest(IgniteWriteAheadLogManager walMgr, WALIterator it) throws IOException, IgniteCheckedException {
        File walArchiveDir = U.field(walMgr, "walArchiveDir");

        IgniteWalIteratorFactory iteratorFactory = new IgniteWalIteratorFactory();

        List<FileDescriptor> descs = iteratorFactory.resolveWalFiles(
            new IteratorParametersBuilder()
                .filesOrDirs(walArchiveDir)
        );

        int maxIndex = descs.size() - 1;
        int minIndex = 1;

        int corruptedIdx = current().nextInt(minIndex, maxIndex);

        log.info("Corrupted segment with idx:" + corruptedIdx);

        FileWALPointer corruptedPtr = corruptedWAlSegmentFile(
            descs.get(corruptedIdx),
            new RandomAccessFileIOFactory(),
            iteratorFactory
        );

        log.info("Should fail on ptr " + corruptedPtr);

        FileWALPointer lastReadPtr = null;

        boolean exception = false;

        try (WALIterator it0 = it) {
            while (it0.hasNextX()) {
                IgniteBiTuple<WALPointer, WALRecord> tup = it0.nextX();

                lastReadPtr = (FileWALPointer)tup.get1();
            }
        }
        catch (IgniteCheckedException e) {
            if (e.getMessage().contains("WAL tail reached in archive directory, WAL segment file is corrupted")
                || e.getMessage().contains("WAL tail reached not in the last available segment"))
                exception = true;
        }

        Assert.assertNotNull(lastReadPtr);

        if (!exception) {
            fail("Last read ptr=" + lastReadPtr + ", corruptedPtr=" + corruptedPtr);
        }
    }

    /**
     *
     * @param desc WAL segment descriptor.
     * @param ioFactory IO factory.
     * @param iteratorFactory Iterator factory.
     * @return Corrupted position/
     * @throws IOException If IO exception.
     * @throws IgniteCheckedException If iterator failed.
     */
    private FileWALPointer corruptedWAlSegmentFile(
        FileDescriptor desc,
        FileIOFactory ioFactory,
        IgniteWalIteratorFactory iteratorFactory
    ) throws IOException, IgniteCheckedException {
        LinkedList<FileWALPointer> pointers = new LinkedList<>();

        try (WALIterator it = iteratorFactory.iterator(desc.file())) {
            while (it.hasNext()) {
                IgniteBiTuple<WALPointer, WALRecord> tup = it.next();

                pointers.add((FileWALPointer)tup.get1());
            }
        }

        int pointToCorrupt = current().nextInt(pointers.size());

        FileWALPointer ptr = pointers.get(pointToCorrupt);

        int offset = ptr.fileOffset();

        // 20 pointer size, 8 idx, 4 offset, 4 length.
        ByteBuffer buf = allocate(20);

        Random r = new Random();

        // Corrupt record pointer.
        r.nextBytes(buf.array());

        try (FileIO io = ioFactory.create(desc.file(), WRITE)) {
            io.write(buf, offset + 1);

            io.force(true);
        }

        return ptr;
    }
}


text:
//==============================================================================
//            Copyright (c) 2009-2014 ichess.co.il
//
//This document contains confidential information which is protected by
//copyright and is proprietary to ichess.co.il. No part
//of this document may be used, copied, disclosed, or conveyed to another
//party without prior written consent of ichess.co.il.
//==============================================================================

package com.ichess.game;

import java.util.logging.Logger;

public class Common {

    private final static Logger LOGGER = Logger.getLogger(Common.class.getName());

    public static final int GAME_KIND_REGULAR = 1;
    public static final int GAME_KIND_FISCHER = 2;
    public static final int GAME_KIND_SUICIDE = 3;
    public static final int GAME_KIND_GRASSHOPER = 4;
    public static final int GAME_KIND_MINICAPA = 5;
    public static final int GAME_KIND_FREEPLAY = 6;
    public static final int GAME_KIND_CRAZY_HOUSE = 7;
    public static final int GAME_KIND_BUG_HOUSE = 8;
    public static final int GAME_KIND_NUM = 9;
    public static final int GAME_RULES_REGULAR = 1;
    public static final int GAME_RULES_FISCHER = 2;
    public static final int GAME_RULES_SUICIDE = 3;
    public static final int GAME_RULES_FREEPLAY = 4;
    public static final int GAME_RULES_CRAZY_HOUSE = 5;
    // game rules
    public static transient final String[] GAME_RULES_TEXT = {"any", "regular", "fischer 960", "suicide", "free", "crazy house"};
    public static final int PIECE_TYPE_START = 0;
    public static final int PIECE_TYPE_PAWN = 1;
    public static final int PIECE_TYPE_KNIGHT = 2;
    public static final int PIECE_TYPE_BISHOP = 3;
    public static final int PIECE_TYPE_ROOK = 4;
    public static final int PIECE_TYPE_QUEEN = 5;
    public static final int PIECE_TYPE_KING = 6;
    public static final int PIECE_TYPE_ILLEGAL = 7;
    public static final int PIECE_TYPE_GRASSHOPER = 8;
    public static final int PIECE_TYPE_ARCHBISHOP = 9;
    public static final int PIECE_TYPE_CHANCELLOR = 10;
    public static final int PIECE_TYPE_DROP_ANY = 11;
    public static final int PIECE_TYPE_NUM = 12;
    public static final int COLOR_START = 0;
    public static final int COLOR_WHITE = 1;
    public static final int COLOR_BLACK = 2;
    public static final int COLOR_ILLEGAL = 3;
    public static final int COLOR_NUM = 4;
    public static final int CASTLE_START = 0;
    public static final int CASTLE_KING = 1;
    public static final int CASTLE_QUEEN = 2;
    public static final int CASTLE_NUM = 3;
    /**
     * A textual description of all game kinds
     */
    public static final String[] GAME_KIND_TEXT = new String[]{"Any", "Regular", "Fishcer 960", "Losing", "Grasshoppers", "Mini Capablance", "Free", "CrazyHouse", "Bug House"};
    public static final String STD_INIT_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";

    // max move number value
    public static final int MAX_MOVENUM = 10000;

    public static String getColor(int color) {
        switch (color) {
            case COLOR_WHITE:
                return "White";
            case COLOR_BLACK:
                return "Black";
            case COLOR_ILLEGAL:
                return "Random";
            default:
                return "Unknown";
        }
    }

    public static String getColorChar(int color) {
        switch (color) {
            case COLOR_WHITE:
                return "w";
            case COLOR_BLACK:
                return "b";
            case COLOR_ILLEGAL:
                return "r";
            default:
                return "u";
        }
    }

    public static boolean isBlack(int color) {
        return color == COLOR_BLACK;
    }

    public static boolean isBlackOrWhite(int color) {
        return isWhite(color) || isBlack(color);
    }

    public static boolean isWhite(int color) {
        return color == COLOR_WHITE;
    }

    public static int OtherColor(int col) {
        switch (col) {
            case COLOR_WHITE:
                return COLOR_BLACK;
            case COLOR_BLACK:
                return COLOR_WHITE;
        }
        LOGGER.warning("illegal color " + col);
        return col;
    }

    public enum BOARD_COLUMN {
        A("a"), B("b"), C("c"), D("d"), E("e"), F("f"), G("g"), H("h");

        String letter;

        BOARD_COLUMN(String letter) {
            this.letter = letter;
        }

        public String getColumnName() {
            return letter;
        }
    }
}


text:
module ApimanFilters {

    export var _module = angular.module('ApimanFilters', ['ApimanConfiguration']);

    export var checklist = _module.filter('urlEncode', function() {
        return encodeURIComponent;
    });

    // Checklist Filter:
    // This filter processes and formats data returned by the /status endpoint.
    export var checklist = _module.filter('checklist', function() {
        // Map the IDs to the Tab Names
        // This is used when checking if the user is on the same tab
        // defined on the checklist.
        var tabMapping = {
            'endpoint': 'impl',
            'gateways': 'impl',
            'plans': 'plans',
            'policies': 'policies'
        };

        return function(input) {
            var filtered = [];

            angular.forEach(input, function(item: ChecklistConfig) {
                if(item && item.id) {
                    // Add path for tabs with more than one path (ie: endpoint and gateways)
                    item.path = tabMapping[item.id];

                    // Check if item is completed (no need to check for this)
                    var status = (item.done === true) ? 'complete' : 'incomplete';

                    // Determine status icon class
                    item.iconClass = (item.done === true) ? 'fa fa-check-circle-o' : 'fa fa-circle-o';

                    // Determine table row class (ie: active complete, inactive incomplete)
                    item.rowClass = status;

                    filtered.push(item);
                }
            });

            return filtered;
        };
    });

    export var propsFilter = _module.filter('propsFilter', function() {
        return function(items, props) {
            var out = [];

            if (angular.isArray(items)) {
                items.forEach(function(item) {
                    var itemMatches = false;

                    var keys = Object.keys(props);
                    for (var i = 0; i < keys.length; i++) {
                        var prop = keys[i];
                        var text = props[prop].toLowerCase();
                        if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
                            itemMatches = true;
                            break;
                        }
                    }

                    if (itemMatches) {
                        out.push(item);
                    }
                });
            } else {
                // Let the output be the input untouched
                out = items;
            }

            return out;
        };
    });

    export var selectedTags = _module.filter('selectedTags', ['Logger', function(Logger) {
        return function(array, selectedTags) {
            if(array && selectedTags.length >= 1) {
                return array.filter(function(item) {
                    var itemTags = [];

                    _.map(selectedTags, function(tag) {
                        if(_.includes(item.tags, tag)) {
                            itemTags.push(tag);
                        }
                    });

                    return _.difference(selectedTags, itemTags).length === 0;
                });
            } else {
                return array;
            }
        };
    }]);

}


text:
<?php

namespace Application\Controller;

use Application\UF\Percolation\Percolation;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class PercolationController extends AbstractActionController
{
    public function indexAction()
    {
		$memoryStart = memory_get_usage(true);
		$startTime = microtime(true);
		$size = $this->params() -> fromQuery ('size', 5);
		$percolationClient = new Percolation($size);
		$percolations = [];

		while ( false === $percolationClient->percolates() )
		{
			$randomI = rand(0, $size-1);
			$randomJ = rand(0, $size-1);
			$percolationClient->open($randomI, $randomJ);

			$percolations[] = [
				'openNow' => $randomI*$size+$randomJ,
				'sites' => $percolationClient->draw(),
				'percolates' => $percolationClient->percolates(),
			];
		}
		$endTime = microtime(true);

		$memoryStop = memory_get_usage(true);
        return new ViewModel([
			'size' =>  $size,
			'percolations' => $percolations,
			'timeDelta' => $endTime - $startTime,
			'memoryUsage' =>[
				'start' => $memoryStart,
				'stop' => $memoryStop,
				'delta' => $memoryStop - $memoryStart
			]

		]);
    }

}


text:
layout: post
title: "Ibadah Khusus HUT Republik Indonesia"
date: 2014-08-17
description: Ibadah Khusus HKBP Rawamangun Edisi HUT Kemerdekaan RI.
lightbox: true
author: Andre Moreno
---

Ibadah Khusus 12:30 HKBP Rawamangun Minggu ini sedikit berbeda, karena kali ini bertepatan dengan Hari Kemerdekaan Republik Indonesia.

{{< gallery name="20140817*.jpg" />}}

Untuk melihat hasil dokumentasi nya bisa dilihat di tautan berikut ini: http://ndre.in/2eUiVcb


text:
#import "NSObject.h"

@class NSArray, NSMutableArray;

@protocol IDESchemeActionTestSummaryContainer <NSObject>
@property(readonly) NSArray *containedTestSummaries;
@property(readonly) NSMutableArray *mutableContainedTestSummaries;
@end


text:
package types

// Aggregations type.
//
// https://github.com/elastic/elasticsearch-specification/blob/4ca0cc05d3ae3fa06c2cd7be91905b656a474334/specification/_types/aggregations/AggregationContainer.ts#L105-L209
type Aggregations struct {
	AdjacencyMatrix *AdjacencyMatrixAggregation `json:"adjacency_matrix,omitempty"`
	// Aggregations Sub-aggregations for this aggregation. Only applies to bucket aggregations.
	Aggregations            map[string]Aggregations             `json:"aggregations,omitempty"`
	AutoDateHistogram       *AutoDateHistogramAggregation       `json:"auto_date_histogram,omitempty"`
	Avg                     *AverageAggregation                 `json:"avg,omitempty"`
	AvgBucket               *AverageBucketAggregation           `json:"avg_bucket,omitempty"`
	Boxplot                 *BoxplotAggregation                 `json:"boxplot,omitempty"`
	BucketCorrelation       *BucketCorrelationAggregation       `json:"bucket_correlation,omitempty"`
	BucketCountKsTest       *BucketKsAggregation                `json:"bucket_count_ks_test,omitempty"`
	BucketScript            *BucketScriptAggregation            `json:"bucket_script,omitempty"`
	BucketSelector          *BucketSelectorAggregation          `json:"bucket_selector,omitempty"`
	BucketSort              *BucketSortAggregation              `json:"bucket_sort,omitempty"`
	Cardinality             *CardinalityAggregation             `json:"cardinality,omitempty"`
	CategorizeText          *CategorizeTextAggregation          `json:"categorize_text,omitempty"`
	Children                *ChildrenAggregation                `json:"children,omitempty"`
	Composite               *CompositeAggregation               `json:"composite,omitempty"`
	CumulativeCardinality   *CumulativeCardinalityAggregation   `json:"cumulative_cardinality,omitempty"`
	CumulativeSum           *CumulativeSumAggregation           `json:"cumulative_sum,omitempty"`
	DateHistogram           *DateHistogramAggregation           `json:"date_histogram,omitempty"`
	DateRange               *DateRangeAggregation               `json:"date_range,omitempty"`
	Derivative              *DerivativeAggregation              `json:"derivative,omitempty"`
	DiversifiedSampler      *DiversifiedSamplerAggregation      `json:"diversified_sampler,omitempty"`
	ExtendedStats           *ExtendedStatsAggregation           `json:"extended_stats,omitempty"`
	ExtendedStatsBucket     *ExtendedStatsBucketAggregation     `json:"extended_stats_bucket,omitempty"`
	Filter                  *Query                              `json:"filter,omitempty"`
	Filters                 *FiltersAggregation                 `json:"filters,omitempty"`
	GeoBounds               *GeoBoundsAggregation               `json:"geo_bounds,omitempty"`
	GeoCentroid             *GeoCentroidAggregation             `json:"geo_centroid,omitempty"`
	GeoDistance             *GeoDistanceAggregation             `json:"geo_distance,omitempty"`
	GeoLine                 *GeoLineAggregation                 `json:"geo_line,omitempty"`
	GeohashGrid             *GeoHashGridAggregation             `json:"geohash_grid,omitempty"`
	GeohexGrid              *GeohexGridAggregation              `json:"geohex_grid,omitempty"`
	GeotileGrid             *GeoTileGridAggregation             `json:"geotile_grid,omitempty"`
	Global                  *GlobalAggregation                  `json:"global,omitempty"`
	Histogram               *HistogramAggregation               `json:"histogram,omitempty"`
	Inference               *InferenceAggregation               `json:"inference,omitempty"`
	IpPrefix                *IpPrefixAggregation                `json:"ip_prefix,omitempty"`
	IpRange                 *IpRangeAggregation                 `json:"ip_range,omitempty"`
	Line                    *GeoLineAggregation                 `json:"line,omitempty"`
	MatrixStats             *MatrixStatsAggregation             `json:"matrix_stats,omitempty"`
	Max                     *MaxAggregation                     `json:"max,omitempty"`
	MaxBucket               *MaxBucketAggregation               `json:"max_bucket,omitempty"`
	MedianAbsoluteDeviation *MedianAbsoluteDeviationAggregation `json:"median_absolute_deviation,omitempty"`
	Meta                    map[string]interface{}              `json:"meta,omitempty"`
	Min                     *MinAggregation                     `json:"min,omitempty"`
	MinBucket               *MinBucketAggregation               `json:"min_bucket,omitempty"`
	Missing                 *MissingAggregation                 `json:"missing,omitempty"`
	MovingAvg               *MovingAverageAggregation           `json:"moving_avg,omitempty"`
	MovingFn                *MovingFunctionAggregation          `json:"moving_fn,omitempty"`
	MovingPercentiles       *MovingPercentilesAggregation       `json:"moving_percentiles,omitempty"`
	MultiTerms              *MultiTermsAggregation              `json:"multi_terms,omitempty"`
	Nested                  *NestedAggregation                  `json:"nested,omitempty"`
	Normalize               *NormalizeAggregation               `json:"normalize,omitempty"`
	Parent                  *ParentAggregation                  `json:"parent,omitempty"`
	PercentileRanks         *PercentileRanksAggregation         `json:"percentile_ranks,omitempty"`
	Percentiles             *PercentilesAggregation             `json:"percentiles,omitempty"`
	PercentilesBucket       *PercentilesBucketAggregation       `json:"percentiles_bucket,omitempty"`
	Range                   *RangeAggregation                   `json:"range,omitempty"`
	RareTerms               *RareTermsAggregation               `json:"rare_terms,omitempty"`
	Rate                    *RateAggregation                    `json:"rate,omitempty"`
	ReverseNested           *ReverseNestedAggregation           `json:"reverse_nested,omitempty"`
	Sampler                 *SamplerAggregation                 `json:"sampler,omitempty"`
	ScriptedMetric          *ScriptedMetricAggregation          `json:"scripted_metric,omitempty"`
	SerialDiff              *SerialDifferencingAggregation      `json:"serial_diff,omitempty"`
	SignificantTerms        *SignificantTermsAggregation        `json:"significant_terms,omitempty"`
	SignificantText         *SignificantTextAggregation         `json:"significant_text,omitempty"`
	Stats                   *StatsAggregation                   `json:"stats,omitempty"`
	StatsBucket             *StatsBucketAggregation             `json:"stats_bucket,omitempty"`
	StringStats             *StringStatsAggregation             `json:"string_stats,omitempty"`
	Sum                     *SumAggregation                     `json:"sum,omitempty"`
	SumBucket               *SumBucketAggregation               `json:"sum_bucket,omitempty"`
	TTest                   *TTestAggregation                   `json:"t_test,omitempty"`
	Terms                   *TermsAggregation                   `json:"terms,omitempty"`
	TopHits                 *TopHitsAggregation                 `json:"top_hits,omitempty"`
	TopMetrics              *TopMetricsAggregation              `json:"top_metrics,omitempty"`
	ValueCount              *ValueCountAggregation              `json:"value_count,omitempty"`
	VariableWidthHistogram  *VariableWidthHistogramAggregation  `json:"variable_width_histogram,omitempty"`
	WeightedAvg             *WeightedAverageAggregation         `json:"weighted_avg,omitempty"`
}

// NewAggregations returns a Aggregations.
func NewAggregations() *Aggregations {
	r := &Aggregations{
		Aggregations: make(map[string]Aggregations, 0),
	}

	return r
}


text:
COMPILER_ROOT = ../..
COMPILER_SUBDIR = ifa/make_prims

#
# standard header
#
include $(COMPILER_ROOT)/make/Makefile.compiler.head

#
# make_prims-specific variables
#

MAKE_PRIMS = make_prims$(EXE_SUFFIX)
MAKE_PRIMS_SVN_SRCS = \
	make_prims.cpp
MAKE_PRIMS_SRCS = $(MAKE_PRIMS_SVN_SRCS)
MAKE_PRIMS_OBJS = $(MAKE_PRIMS_SRCS:%.cpp=$(OBJ_SUBDIR)/%.o)

#
# standard subdirectory variables
#

SVN_SRCS = $(MAKE_PRIMS_SVN_SRCS)
EXECS = $(MAKE_PRIMS)

#
# rules
#

TARGETS = $(MAKE_PRIMS)

include $(COMPILER_ROOT)/make/Makefile.compiler.subdirrules

#
# target-specific rules
#

$(MAKE_PRIMS): $(CHPL_MAKE_PLATFORM)/$(MAKE_PRIMS)
	cp -f $< $@

$(CHPL_MAKE_PLATFORM)/$(MAKE_PRIMS): $(MAKE_PRIMS_OBJS)
	$(CXX) $(LDFLAGS) -o $@ $^ $(LIBS)

#
# standard footer
#
include $(COMPILER_ROOT)/make/Makefile.compiler.foot


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Topshelf.Logging;
using Topshelf.Runtime;

namespace Topshelf.Builders.Linux
{
	public class LinuxHostBuilder : RunBuilder
	{
		static readonly LogWriter _log = HostLogger.Get<LinuxHostBuilder>();

		public LinuxHostBuilder(HostEnvironment environment, HostSettings settings)
			: base(environment, settings)
		{
		}

		public override Host Build(ServiceBuilder serviceBuilder)
		{
			_log.Debug("Running as linux process.");

			return Environment.CreateServiceHost(Settings, serviceBuilder.Build(Settings));
		}
	}
}


text:
<?php

/* @Twig/Exception/traces.txt.twig */
class __TwigTemplate_426e52a7a6ad00ecb53e896cad91db5fd66d0de29fdbb8d479aeecc844bd0cdd extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_d4d3a74d22180abcd514fef91c13c4ceca5bed61b515b0cd3b72ee88830b23f5 = $this->env->getExtension("native_profiler");
        $__internal_d4d3a74d22180abcd514fef91c13c4ceca5bed61b515b0cd3b72ee88830b23f5->enter($__internal_d4d3a74d22180abcd514fef91c13c4ceca5bed61b515b0cd3b72ee88830b23f5_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@Twig/Exception/traces.txt.twig"));

        // line 1
        if (twig_length_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array()))) {
            // line 2
            $context['_parent'] = $context;
            $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array()));
            foreach ($context['_seq'] as $context["_key"] => $context["trace"]) {
                // line 3
                $this->loadTemplate("@Twig/Exception/trace.txt.twig", "@Twig/Exception/traces.txt.twig", 3)->display(array("trace" => $context["trace"]));
                // line 4
                echo "
";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['trace'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
        }

        $__internal_d4d3a74d22180abcd514fef91c13c4ceca5bed61b515b0cd3b72ee88830b23f5->leave($__internal_d4d3a74d22180abcd514fef91c13c4ceca5bed61b515b0cd3b72ee88830b23f5_prof);

    }

    public function getTemplateName()
    {
        return "@Twig/Exception/traces.txt.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  30 => 4,  28 => 3,  24 => 2,  22 => 1,);
    }
}
/* {% if exception.trace|length %}*/
/* {% for trace in exception.trace %}*/
/* {% include '@Twig/Exception/trace.txt.twig' with { 'trace': trace } only %}*/
/* */
/* {% endfor %}*/
/* {% endif %}*/
/* */


text:
import { describe, expect, it } from '@jest/globals'
import assert from 'node:assert'
import DefaultStore from './index.js'

describe('DefaultStore', () => {
  it('cannot be created without new', () => {
    assert.throws(() => DefaultStore(), /TypeError/)
  })

  it('merges in state using `setState`', () => {
    const store = new DefaultStore()
    expect(store.getState()).toEqual({})

    store.setState({
      a: 1,
      b: 2,
    })
    expect(store.getState()).toEqual({ a: 1, b: 2 })

    store.setState({ b: 3 })
    expect(store.getState()).toEqual({ a: 1, b: 3 })
  })

  it('notifies subscriptions when state changes', () => {
    let expected = []
    let calls = 0
    function listener (prevState, nextState, patch) {
      calls++
      expect([prevState, nextState, patch]).toEqual(expected)
    }

    const store = new DefaultStore()
    store.subscribe(listener)

    expected = [{}, { a: 1, b: 2 }, { a: 1, b: 2 }]
    store.setState({
      a: 1,
      b: 2,
    })

    expected = [{ a: 1, b: 2 }, { a: 1, b: 3 }, { b: 3 }]
    store.setState({ b: 3 })

    expect(calls).toBe(2)
  })
})


text:
package org.springframework.android.showcase.rest;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 * @author Roy Clarkson
 */
@Root
public class Message {

	@Element
	private long id;

	@Element
	private String subject;

	@Element
	private String text;

	public Message() {
	}

	public Message(long id, String subject, String text) {
		this.id = id;
		this.subject = subject;
		this.text = text;
	}

	public void setId(long id) {
		this.id = id;
	}

	public long getId() {
		return this.id;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getSubject() {
		return this.subject;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getText() {
		return this.text;
	}

	public String toString() {
		return "[Id:] " + this.getId() + " [Subject:] " + this.getSubject() + " [Text:] " + this.getText();
	}

}


text:
package com.intellij.psi.impl.smartPointers;

import com.intellij.lang.Language;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Segment;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;

/**
* User: cdr
*/
class FileElementInfo implements SmartPointerElementInfo {
  protected final VirtualFile myVirtualFile;
  protected final Project myProject;
  protected final Language myLanguage;

  public FileElementInfo(@NotNull PsiFile file) {
    this(file.getProject(), file.getVirtualFile(), file.getLanguage());
  }
  protected FileElementInfo(@NotNull Project project, VirtualFile virtualFile) {
    this(project, virtualFile, null);
  }

  protected FileElementInfo(@NotNull Project project, VirtualFile virtualFile, Language lang) {
    myVirtualFile = virtualFile;
    myProject = project;
    myLanguage = lang;
  }

  @Override
  public Document getDocumentToSynchronize() {
    return null;
  }

  @Override
  public void fastenBelt(int offset, RangeMarker[] cachedRangeMarker) {
  }

  @Override
  public void unfastenBelt(int offset) {
  }

  @Override
  public PsiElement restoreElement() {
    return SelfElementInfo.restoreFileFromVirtual(myVirtualFile, myProject, myLanguage);
  }

  @Override
  public PsiFile restoreFile() {
    PsiElement element = restoreElement();
    return element == null ? null : element.getContainingFile(); // can be directory
  }

  @Override
  public int elementHashCode() {
    return myVirtualFile.hashCode();
  }

  @Override
  public boolean pointsToTheSameElementAs(@NotNull SmartPointerElementInfo other) {
    if (other instanceof FileElementInfo) {
      return Comparing.equal(myVirtualFile, ((FileElementInfo)other).myVirtualFile);
    }
    if (other instanceof SelfElementInfo || other instanceof ClsElementInfo) {
      // optimisation: SelfElementInfo need psi (parsing) for element restoration and apriori could not reference psi file
      return false;
    }
    return Comparing.equal(restoreElement(), other.restoreElement());
  }

  @Override
  public VirtualFile getVirtualFile() {
    return myVirtualFile;
  }

  @Override
  public Segment getRange() {
    return new TextRange(0, (int)myVirtualFile.getLength());
  }

  @NotNull
  @Override
  public Project getProject() {
    return myProject;
  }

  @Override
  public void cleanup() {

  }
}


text:
//
//
//package org.apache.airavata.xbaya.interpreter;
//
//import java.io.IOException;
//import java.net.URISyntaxException;
//import java.net.URL;
//import java.util.UUID;
//
////import org.apache.airavata.registry.api.AiravataRegistry2;
//import org.apache.airavata.workflow.model.exceptions.WorkflowException;
//import org.apache.airavata.workflow.model.wf.Workflow;
//import org.apache.airavata.xbaya.XBayaConfiguration;
//import org.apache.airavata.xbaya.interpreter.utils.WorkflowTestUtils;
//import org.apache.airavata.xbaya.interpretor.SSWorkflowInterpreterInteractorImpl;
//import org.apache.airavata.xbaya.interpretor.StandaloneNotificationSender;
//import org.apache.airavata.xbaya.interpretor.WorkflowInterpreter;
//import org.apache.airavata.xbaya.interpretor.WorkflowInterpreterConfiguration;
//import org.junit.Rule;
//import org.junit.Test;
//import org.junit.rules.MethodRule;
//import org.junit.rules.TestWatchman;
//import org.junit.runners.model.FrameworkMethod;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//public class CrossProductWorkflowTest {
//    final Logger logger = LoggerFactory.getLogger(CrossProductWorkflowTest.class);
//
//    @Rule
//    public MethodRule watchman = new TestWatchman() {
//        public void starting(FrameworkMethod method) {
//            logger.info("{} being run...", method.getName());
//        }
//    };
//
//    @Test
//    public void testScheduleDynamically() throws IOException, URISyntaxException, WorkflowException {
//        logger.info("Running CrossProductWorkflowTest...");
//        URL systemResource = this.getClass().getClassLoader().getSystemResource("LevenshteinDistance.xwf");
//        Workflow workflow = new Workflow(WorkflowTestUtils.readWorkflow(systemResource));
//        XBayaConfiguration conf = WorkflowTestUtils.getConfiguration();
////        AiravataRegistry2 registry = conf.getJcrComponentRegistry()==null? null:conf.getJcrComponentRegistry().getExperimentCatalog();
////		WorkflowInterpreterConfiguration workflowInterpreterConfiguration = new WorkflowInterpreterConfiguration(workflow, UUID.randomUUID().toString(),conf.getMessageBoxURL(), conf.getBrokerURL(), registry, conf, null,null,true);
//		WorkflowInterpreterConfiguration workflowInterpreterConfiguration = new WorkflowInterpreterConfiguration(workflow,
//                UUID.randomUUID().toString(),conf.getMessageBoxURL(), conf.getBrokerURL(), conf.getAiravataAPI(), conf, null,null,true);
//		workflowInterpreterConfiguration.setNotifier(new StandaloneNotificationSender(workflowInterpreterConfiguration.getTopic(),workflowInterpreterConfiguration.getWorkflow()));
//
//        WorkflowInterpreter interpretor = new WorkflowInterpreter(workflowInterpreterConfiguration,new SSWorkflowInterpreterInteractorImpl());
//        interpretor.scheduleDynamically();
//    }
//}


text:
(function() {
  var Configuration, createRequester, debug, exec, fs, http, join, merge, mkdirp, rm_rf, serve, swap, touch;

  fs = require("fs");

  http = require("http");

  ({exec} = require("child_process"));

  ({join} = require("path"));

  ({Configuration} = require("../.."));

  exports.merge = merge = function(...objects) {
    var i, key, len, object, result, value;
    result = {};
    for (i = 0, len = objects.length; i < len; i++) {
      object = objects[i];
      for (key in object) {
        value = object[key];
        result[key] = value;
      }
    }
    return result;
  };

  exports.createConfiguration = function(env = {}) {
    return new Configuration(merge({}, env));
  };

  exports.rm_rf = rm_rf = function(path, callback) {
    return exec(`rm -rf ${path}`, callback);
  };

  exports.mkdirp = mkdirp = function(path, callback) {
    return exec(`mkdir -p ${path}`, callback);
  };

  exports.touch = touch = function(path, callback) {
    return exec(`touch ${path}`, callback);
  };

  exports.swap = swap = function(path1, path2, callback) {
    var unswap;
    unswap = function(callback) {
      return swap(path2, path1, callback);
    };
    return exec(`mv ${path1} ${path1}.swap;\nmv ${path2} ${path1};\nmv ${path1}.swap ${path2}`, function(err) {
      return callback(err, unswap);
    });
  };

  exports.debug = debug = function() {
    if (process.env.DEBUG) {
      return console.error.apply(console, arguments);
    }
  };

  exports.serve = serve = function(server, callback) {
    return server.listen(0, function() {
      var port, request;
      port = server.address().port;
      debug(`server listening on port ${port}`);
      request = createRequester(server.address().port);
      return callback(request, function(callback) {
        debug(`server on port ${port} is closing`);
        server.close();
        return callback();
      }, server);
    });
  };

  exports.createRequester = createRequester = function(port) {
    return function(method, path, headers, callback) {
      var data, request;
      if (!callback) {
        callback = headers;
      }
      request = http.request({method, path, port, headers});
      if (data = headers.data) {
        delete headers.data;
        request.write(data);
      }
      request.end();
      debug(`client requesting ${method} ${path} on port ${port}`);
      return request.on("response", function(response) {
        var body;
        body = "";
        response.on("data", function(chunk) {
          debug(`client received ${chunk.length} bytes from server on port ${port}`);
          return body += chunk.toString("utf8");
        });
        return response.on("end", function() {
          debug(`client disconnected from server on port ${port}`);
          return callback(body, response);
        });
      });
    };
  };

}).call(this);


text:
package org.sagebionetworks.web.client.widget.entity.act;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

public interface UserBadgeListView extends IsWidget {

	public interface Presenter {
		void deleteSelected();

		void selectNone();

		void selectAll();
	}

	void setPresenter(Presenter presenter);

	void setSelectionOptionsVisible(boolean visible);

	void addUserBadge(Widget widget);

	void clearUserBadges();

	void setCanDelete(boolean canDelete);
}


text:
//------------------------------------------------------------------------------
// Copyright (c) 2016 by contributors. 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.
//------------------------------------------------------------------------------

/*
Author: Chao Ma (mctt90@gmail.com)

This file tests ffm_loss.h
*/

#include "gtest/gtest.h"

#include "src/loss/ffm_loss.h"
#include "src/reader/reader.h"
#include "src/reader/parser.h"
#include "src/data/data_structure.h"
#include "src/data/model_parameters_in_column.h"
#include "src/data/hyper_parameters.h"

namespace f2m {

const std::string kTestfilename = "/tmp/Criteo.txt.train";
const index_t kFeatureNum = 9999 + 1;
const int iteration_num = 10000;
const int kNumSamples = 100;
const int K = 10;
const int kField = 17;

TEST(CalcGrad, RealDataSetTestInmem) {
  index_t num_param = kFeatureNum + kFeatureNum * K * kField;
  // Parser
  Parser* parser_ffm = new FFMParser;
  // Reader
  InmemReader reader;
  reader.Initialize(kTestfilename, kNumSamples, parser_ffm, FFM);
  // Model
  Model model(num_param, SGD, true); // using guassian distribution
  // Gradient
  Gradient* grad = new DenseGrad;
  grad->Initialize(num_param);
  // DMatrix
  DMatrix* matrix = NULL;
  // FFMLoss
  FFMLoss loss;
  HyperParam hyper_param;
  hyper_param.max_feature = kFeatureNum;
  hyper_param.num_factor = K;
  hyper_param.num_field = kField;
  loss.Initialize(hyper_param);
  // Calc gradient
  for (int i = 0; i < iteration_num; ++i) {
    int record_num = reader.Samples(matrix);
    if (record_num == 0) {
      --i;
      reader.GoToHead();
      continue;
    }
    CHECK_EQ(record_num, kNumSamples);
    loss.CalcGrad(matrix, &model, grad);
    // TODU(yuze): test the index
    grad->Reset();
    if (i % 1000 == 0) LOG(INFO) << i / 1000;
  }
}

TEST(CalcGrad, RealDataSetTestOndisk) {
  index_t num_param = kFeatureNum + kFeatureNum * K * kField;
  // Parser
  Parser* parser_ffm = new FFMParser;
  // Reader
  OndiskReader reader;
  reader.Initialize(kTestfilename, kNumSamples, parser_ffm, FFM);
  // Model
  Model model(num_param, SGD, true); // using guassian distribution
  // Gradient
  Gradient* grad = new DenseGrad;
  grad->Initialize(num_param);
  // DMatrix
  DMatrix* matrix = NULL;
  // FFMLoss
  FFMLoss loss;
  HyperParam hyper_param;
  hyper_param.max_feature = kFeatureNum;
  hyper_param.num_factor = K;
  hyper_param.num_field = kField;
  loss.Initialize(hyper_param);
  // Calc gradient
  for (int i = 0; i < iteration_num; ++i) {
    int record_num = reader.Samples(matrix);
    if (record_num == 0) {
      --i;
      reader.GoToHead();
      continue;
    }
    CHECK_EQ(record_num, kNumSamples);
    loss.CalcGrad(matrix, &model, grad);
    // TODU(yuze): test the index
    grad->Reset();
    if (i % 1000 == 0) LOG(INFO) << i / 1000;
  }
}

TEST(CalcGrad, RealDataSetTestAsync) {
  index_t num_param = kFeatureNum + kFeatureNum * K * kField;
  // Parser
  Parser* parser_ffm = new FFMParser;
  // Reader
  OndiskReaderAsync reader;
  reader.Initialize(kTestfilename, kNumSamples, parser_ffm, FFM);
  // Model
  Model model(num_param, SGD, true); // using guassian distribution
  // Gradient
  Gradient* grad = new DenseGrad;
  grad->Initialize(num_param);
  // DMatrix
  DMatrix* matrix = NULL;
  // FFMLoss
  FFMLoss loss;
  HyperParam hyper_param;
  hyper_param.max_feature = kFeatureNum;
  hyper_param.num_factor = K;
  hyper_param.num_field = kField;
  loss.Initialize(hyper_param);
  // Calc gradient
  for (int i = 0; i < iteration_num; ++i) {
    int record_num = reader.Samples(matrix);
    CHECK_EQ(record_num, kNumSamples);
    loss.CalcGrad(matrix, &model, grad);
    // TODU(yuze): test the index
    grad->Reset();
    if (i % 1000 == 0) LOG(INFO) << i / 1000;
  }
}

} // namespace f2m


text:
function Rect(x, y, w, h) {
  this.x = x; this.y = y;
  this.w = w; this.h = h;
}

Rect.prototype.fitsIn = function(outer) {
  return outer.w >= this.w && outer.h >= this.h;
};

Rect.prototype.sameSizeAs = function(other) {
  return this.w === other.w && this.h === other.h;
};

function Atlas(x, y, w, h) {
  if (arguments.length === 1) {
    this.canvas = x;
    x = y = 0;
    w = this.canvas.width;
    h = this.canvas.height;
  }
  if (arguments.length === 2) {
    w = x; h = y; x = y = 0;
  }
  this.left = this.right = null;
  this.rect = new Rect(x, y, w, h);
  this.filled = false;
  this.tilepad = false;
  this._cache = [];
  this._uvcache = Object.create(null);
}
module.exports = function() {
  if (arguments.length === 1) { return new Atlas(arguments[0]); }
  if (arguments.length === 2) { return new Atlas(arguments[0], arguments[1]); }
  return new Atlas(arguments[0], arguments[1], arguments[2], arguments[3]);
};
module.exports.Atlas = Atlas;
module.exports.Rect = Rect;

// pack image/rect to the atlas
Atlas.prototype.pack = function(rect) {
  this._cache = [];
  this._uvcache = [];
  rect = this._toRect(rect);

  if (this.img && this.tilepad) {
    rect = this._tilepad(rect);
  }

  if (this.left !== null) {
    return this._ontoCanvas(this.left.pack(rect) || this.right.pack(rect));
  }
  // if atlas filled or wont fit
  if (this.filled || !rect.fitsIn(this.rect)) {
    return false;
  }
  // if this atlas has been filled
  if (rect.sameSizeAs(this.rect)) {
    this.filled = true;
    return this._ontoCanvas(this);
  }
  if ((this.rect.w - rect.w) > (this.rect.h - rect.h)) {
    this.left = new Atlas(this.rect.x, this.rect.y, rect.w, this.rect.h);
    this.right = new Atlas(this.rect.x + rect.w, this.rect.y, this.rect.w - rect.w, this.rect.h);
  } else {
    this.left = new Atlas(this.rect.x, this.rect.y, this.rect.w, rect.h);
    this.right = new Atlas(this.rect.x, this.rect.y + rect.h, this.rect.w, this.rect.h - rect.h);
  }
  return this._ontoCanvas(this.left.pack(rect));
};

Atlas.prototype.expand = function(rect) {
  var self = this;
  rect = this._toRect(rect);

  if (this.img && this.tilepad) {
    rect = this._tilepad(rect);
  }

  var atlas;
  if (this.rect.w < this.rect.h) {
    atlas = new Atlas(0, 0, this.rect.w + rect.w, this.rect.h);
    atlas.right = new Atlas(this.rect.w, 0, rect.w, this.rect.h);
    atlas.left = this;
  } else {
    atlas = new Atlas(0, 0, this.rect.w, this.rect.h + rect.h);
    atlas.right = new Atlas(0, this.rect.h, this.rect.w, rect.h);
    atlas.left = this;
  }

  ['canvas', 'context', 'img'].forEach(function(p) {
    if (self[p]) {
      atlas[p] = self[p];
      self[p] = null;
    }
  });

  // resize canvas
  if (atlas.canvas) {
    if (!atlas.context) {
      atlas.context = atlas.canvas.getContext('2d');
    }
    var old = atlas.context.getImageData(0, 0, atlas.canvas.width, atlas.canvas.height);
    atlas.canvas.width = atlas.rect.w;
    atlas.canvas.height = atlas.rect.h;
    atlas.context.putImageData(old, 0, 0);
  }

  return (atlas.pack(rect) === false) ? atlas.expand(rect) : atlas;
};

Atlas.prototype.index = function() {
  var self = this;
  if (self._cache.length > 0) {
    return self._cache;
  }
  (function loop(atlas) {
    if (atlas.left !== null) {
      loop(atlas.left);
      loop(atlas.right);
    } else if (atlas.rect.name) {
      self._cache.push(atlas.rect);
    }
  }(self));
  return self._cache;
};

Atlas.prototype.uv = function(w, h) {
  var self = this;
  if (self._uvcache.length > 0) {
    return self._uvcache;
  }
  w = w || self.rect.w;
  h = h || self.rect.h;
  var isPad = this.tilepad;
  (function loop(atlas) {
    if (atlas.left !== null) {
      loop(atlas.left);
      loop(atlas.right);
    } else if (typeof atlas.rect.name !== 'undefined') {
      var p = (isPad) ? atlas.rect.w / 4 : 0;
      self._uvcache[atlas.rect.name] = [
        [atlas.rect.x + p, atlas.rect.y + p],
        [(atlas.rect.x + p) + (atlas.rect.w - (p * 2)), atlas.rect.y + p],
        [(atlas.rect.x + p) + (atlas.rect.w - (p * 2)), (atlas.rect.y + p) + (atlas.rect.h - (p * 2))],
        [(atlas.rect.x + p), (atlas.rect.y + p) + (atlas.rect.h - (p * 2))],
      ].map(function(uv) {
        if (uv[0] !== 0) {
          uv[0] = uv[0] / w;
        }
        if (uv[1] !== 0) {
          uv[1] = uv[1] / h;
        }
        return uv;
      });
    }
  }(self));
  return self._uvcache;
};

Atlas.prototype.json = function(input) {
  var self = this;
  if (input) {
    if (typeof input === 'string') input = JSON.parse(input);
    return (function loop(obj) {
      if (!obj || !obj.rect) return;
      var atlas = new Atlas(obj.rect.x, obj.rect.y, obj.rect.w, obj.rect.h);
      if (obj.left) atlas.left = loop(obj.left);
      if (obj.right) atlas.right = loop(obj.right);
      return atlas;
    }(input));
  } else {
    return JSON.stringify(function loop(atlas) {
      var obj = {
        left: null, right: null,
        rect: atlas.rect, filled: atlas.filled
      };
      if (atlas.left !== null) {
        obj.left = loop(atlas.left);
        obj.right = loop(atlas.right);
      }
      return obj;
    }(self), null, 2);
  }
};

// Pads the image by tiling itself around itself
Atlas.prototype._tilepad = function(rect) {
  var img = this.img;
  if (!img) return rect;

  var p = img.width / 2;

  var canvas = document.createElement('canvas');
  canvas.name = img.name || img.src;
  canvas.id = img.id || '';
  canvas.width = img.width + img.width;
  canvas.height = img.height + img.height;
  var ctx = canvas.getContext('2d');

  var pattern = ctx.createPattern(img, 'repeat');
  ctx.fillStyle = pattern;
  ctx.translate(p, p);
  ctx.fillRect(-p, -p, canvas.width + p, canvas.height + p);
  ctx.translate(-p, -p);

  this.img = canvas;

  return new Rect(rect.x, rect.y, this.img.width, this.img.height);
};

// if has an image and canvas, draw to the canvas as we go
Atlas.prototype._ontoCanvas = function(node) {
  if (node && this.img && this.canvas) {
    if (!this.context) {
      this.context = this.canvas.getContext('2d');
    }
    this.context.clearRect(node.rect.x, node.rect.y, node.rect.w, node.rect.h);
    this.context.drawImage(this.img, node.rect.x, node.rect.y, node.rect.w, node.rect.h);
    node.rect.name = this.img.id || this.img.name || this.img.src || null;
  }
  return node;
};

// make sure we're always working with rects
Atlas.prototype._toRect = function(rect) {
  // if rect is an image
  if (rect.nodeName && rect.nodeName === 'IMG') {
    this.img = rect;
    rect = new Rect(rect.x, rect.y, rect.width, rect.height);
  }
  // if rect is an object
  if (!(rect instanceof Rect)) {
    rect = new Rect(rect.x || 0, rect.y || 0, rect.w || rect.width, rect.h || rect.height);
  }
  return rect;
};

Atlas.prototype._debug = function() {
  if (!this.canvas) { return; }
  var context = this.canvas.getContext('2d');
  this.index().forEach(function(rect) {
    context.lineWidth = 1;
    context.strokeStyle = 'red';
    context.strokeRect(rect.x, rect.y, rect.w, rect.h);
  });
};


text:
package br.com.softplan.security.zap.api;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.softplan.security.zap.api.exception.ZapClientException;
import br.com.softplan.security.zap.api.model.AnalysisInfo;
import br.com.softplan.security.zap.zaproxy.clientapi.core.ApiResponse;
import br.com.softplan.security.zap.zaproxy.clientapi.core.ApiResponseElement;
import br.com.softplan.security.zap.zaproxy.clientapi.core.ClientApi;
import br.com.softplan.security.zap.zaproxy.clientapi.core.ClientApiException;

/**
 * Helper to be used by classes that make calls to the ZAP API.
 *
 * @author pdsec
 */
public class ZapHelper {

	private static final Logger LOGGER = LoggerFactory.getLogger(ZapHelper.class);

	private static final String ZAP_SUCCESS_RESPONSE = "OK";
	private static final String ZAP_DEFAULT_CONTEXT_NAME = "Default Context";

	public static String extractResponse(ApiResponse response) {
		return ((ApiResponseElement) response).getValue();
	}

	public static void validateResponse(ApiResponse response, String operationDescription) {
		String responseValue = extractResponse(response);
		if (!responseValue.equals(ZAP_SUCCESS_RESPONSE)) {
			String message = "ZAP API did not respond '" + ZAP_SUCCESS_RESPONSE + "' during the following operation: "
					 + operationDescription + ". Actual response: " + responseValue;
			LOGGER.error(message);
			throw new ZapClientException(message);
		}
	}

	public static void includeInContext(ClientApi api, String apiKey, AnalysisInfo analysisInfo) {
		String[] context = analysisInfo.getContext();
		LOGGER.debug("Including target '{}' in context.", Arrays.toString(context));

		try {
			for (String contextUrl : context) {
				if (isContextUrlRelative(contextUrl)) {
					contextUrl = resolveContextUrl(contextUrl, analysisInfo);
				}
				ApiResponse response = api.context.includeInContext(apiKey, ZAP_DEFAULT_CONTEXT_NAME, "\\Q" + contextUrl + "\\E.*");
				validateResponse(response, "Include target in context.");
			}
		} catch (ClientApiException e) {
			LOGGER.error("Error including target in context.", e);
			throw new ZapClientException(e);
		}
	}

	private static boolean isContextUrlRelative(String contextUrl) {
		return !contextUrl.startsWith("http");
	}

	private static String resolveContextUrl(String contextUrl, AnalysisInfo analysisInfo) {
		String activeScanStartingPointUrl = analysisInfo.getActiveScanStartingPointUrl();
		if (activeScanStartingPointUrl.endsWith("/")) {
			activeScanStartingPointUrl = activeScanStartingPointUrl.substring(0, activeScanStartingPointUrl.length()-1);
		}
		if (contextUrl.startsWith("/")) {
			contextUrl = contextUrl.substring(1);
		}
		return activeScanStartingPointUrl + "/" + contextUrl;
	}

	public static void setTechnologiesInContext(ClientApi api, String apiKey, AnalysisInfo analysisInfo) {
		String technologies = analysisInfo.getTechnologiesSeparatedByComma();
		if (technologies == null) {
			return;
		}
		LOGGER.debug("Setting technologies in context: {}.", technologies);

		try {
			ApiResponse responseFromExcludingTechnologies = api.context.excludeAllContextTechnologies(apiKey, ZAP_DEFAULT_CONTEXT_NAME);
			validateResponse(responseFromExcludingTechnologies, "Exclude all context technologies.");

			ApiResponse responseFromIncludingTechnologies = api.context.includeContextTechnologies(apiKey, ZAP_DEFAULT_CONTEXT_NAME, technologies);
			validateResponse(responseFromIncludingTechnologies, "Exclude all context technologies.");
		} catch (ClientApiException e) {
			LOGGER.error("Error setting technologies in context.", e);
			throw new ZapClientException(e);
		}
	}

	private ZapHelper() {}

}