text:
package org.efaps.esjp.sales.payment;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Return;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.db.AttributeQuery;
import org.efaps.db.Context;
import org.efaps.db.Instance;
import org.efaps.db.InstanceQuery;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.PrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.SelectBuilder;
import org.efaps.esjp.ci.CIContacts;
import org.efaps.esjp.ci.CISales;
import org.efaps.esjp.common.file.FileUtil;
import org.efaps.esjp.common.jasperreport.EFapsTextReport;
import org.efaps.esjp.erp.util.ERP;
import org.efaps.util.EFapsException;
import org.joda.time.DateTime;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 */
@EFapsUUID("6d915d6b-fdbe-4bb0-8133-588a0ce3613f")
@EFapsApplication("eFapsApp-Sales")
public abstract class PaymentDetractionReport4Acquirer_Base
{
    private static String MASTER_INDICATOR = "*";
    private static String FILE_EXTENSION = "TXT";
    private static String FILE_STARTCHAR = "D";

    public Return execute(final Parameter _parameter)
        throws EFapsException
    {
        return new EFapsTextReport()
        {
            BigDecimal totalAmount = BigDecimal.ZERO;

            @Override
            protected File getEmptyFile4TextReport()
                throws EFapsException
            {
                final String companyTaxNum = ERP.COMPANY_TAX.get();

                final String name = buildName4TextReport(PaymentDetractionReport4Acquirer_Base.FILE_STARTCHAR,
                                companyTaxNum, getSequenceNumber(_parameter));
                final File file = new FileUtil().getFile(name, PaymentDetractionReport4Acquirer_Base.FILE_EXTENSION);
                return file;
            }

            @Override
            protected void addHeaderDefinition(final Parameter _parameter,
                                               final List<ColumnDefinition> _columnsList)
                throws EFapsException
            {
                _columnsList.add(new ColumnDefinition("", 1, 0, null, null, " ", Type.STRINGTYPE, "%1$1s"));
                _columnsList.add(new ColumnDefinition("", 11, 0, null, null, " ", Type.STRINGTYPE, "%1$11s"));
                _columnsList.add(new ColumnDefinition("", 35, 0, null, null, " ", Type.STRINGTYPE, "%1$-35s"));
                _columnsList.add(new ColumnDefinition("", 6, 0, null, null, " ", Type.STRINGTYPE, "%1$-6s"));
                final DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Context.getThreadContext()
                                .getLocale());
                format.setMaximumIntegerDigits(13);
                format.setMaximumFractionDigits(2);
                format.setMinimumIntegerDigits(13);
                format.setMinimumFractionDigits(2);
                format.setGroupingUsed(false);
                format.setRoundingMode(RoundingMode.HALF_UP);
                _columnsList.add(new ColumnDefinition("", 15, 2, false, format, "0", Type.NUMBERTYPE, null));
            }

            @Override
            protected List<Object> getHeaderData(final Parameter _parameter)
                throws EFapsException
            {
                final List<Object> ret = new ArrayList<>();
                final String companyName = ERP.COMPANY_NAME.get();
                final String companyTaxNum = ERP.COMPANY_TAX.get();
                ret.add(PaymentDetractionReport4Acquirer_Base.MASTER_INDICATOR);
                ret.add(companyTaxNum);
                ret.add(companyName);
                ret.add(getSequenceNumber(_parameter));
                ret.add(this.totalAmount);

                return ret;
            }

            @Override
            protected void addColumnDefinition(final Parameter _parameter,
                                               final List<ColumnDefinition> _columnsList)
                throws EFapsException
            {
                // without '-' is align to right
                _columnsList.add(new ColumnDefinition("", 11, 0, null, null, " ", Type.STRINGTYPE, "%1$11s"));
                // with '-' is align to left
                _columnsList.add(new ColumnDefinition("", 9, 0, null, null, " ", Type.STRINGTYPE, "%1$-9s"));
                _columnsList.add(new ColumnDefinition("", 3, 0, null, null, " ", Type.STRINGTYPE, "%1$-3s"));
                _columnsList.add(new ColumnDefinition("", 11, 0, null, null, " ", Type.STRINGTYPE, "%1$11s"));

                final DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Context.getThreadContext()
                                .getLocale());
                format.setMaximumIntegerDigits(13);
                format.setMaximumFractionDigits(2);
                format.setMinimumIntegerDigits(13);
                format.setMinimumFractionDigits(2);
                format.setGroupingUsed(false);
                format.setRoundingMode(RoundingMode.HALF_UP);
                _columnsList.add(new ColumnDefinition("", 15, 2, false, format, "0", Type.NUMBERTYPE, null));
                _columnsList.add(new ColumnDefinition("", 2, 0, null, null, " ", Type.STRINGTYPE, "%1$-2s"));
                _columnsList.add(new ColumnDefinition("", 6, 0, null, new SimpleDateFormat("yyyyMM"),
                                " ", Type.DATETYPE, "%1$-6s"));
                /*
                 * final SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMdd"); _columnsList.add(new
                 * ColumnDefinition("", 6, 0, null, format2, "\\s", Type.DATETYPE, "%1$-6s"));
                 */
            }

            @Override
            protected List<List<Object>> createDataSource(final Parameter _parameter)
                throws EFapsException
            {
                final List<List<Object>> lst = new ArrayList<>();
                final Instance instance = _parameter.getInstance();
                final PrintQuery print = new PrintQuery(instance);
                print.addAttribute(CISales.BulkPaymentDetraction.BulkDefinitionId);
                print.execute();

                final QueryBuilder queryBldrDef = new QueryBuilder(CISales.BulkPaymentDefinition2Contact);
                queryBldrDef.addWhereAttrEqValue(CISales.BulkPaymentDefinition2Contact.FromLink,
                                print.<Long>getAttribute(CISales.BulkPaymentDetraction.BulkDefinitionId));
                final MultiPrintQuery multiDef = queryBldrDef.getPrint();
                multiDef.addAttribute(CISales.BulkPaymentDefinition2Contact.ToLink,
                                CISales.BulkPaymentDefinition2Contact.AccountNumber);
                multiDef.execute();
                final Map<Long, String> map = new HashMap<>();
                while (multiDef.next()) {
                    final Long contactId = multiDef.<Long>getAttribute(CISales.BulkPaymentDefinition2Contact.ToLink);
                    final String accNum = multiDef
                                    .<String>getAttribute(CISales.BulkPaymentDefinition2Contact.AccountNumber);
                    map.put(contactId, accNum);
                }

                final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.BulkPaymentDetraction2PaymentDocument);
                attrQueryBldr.addWhereAttrEqValue(CISales.BulkPaymentDetraction2PaymentDocument.FromLink, instance);
                final AttributeQuery attrQuery = attrQueryBldr
                                .getAttributeQuery(CISales.BulkPaymentDetraction2PaymentDocument.ToLink);

                final QueryBuilder attrQueryBldr2 = new QueryBuilder(CISales.PaymentDetractionOut);
                attrQueryBldr2.addWhereAttrInQuery(CISales.PaymentDetractionOut.ID, attrQuery);
                final AttributeQuery attrQuery2 = attrQueryBldr2.getAttributeQuery(CISales.PaymentDetractionOut.ID);

                final QueryBuilder queryBldr = new QueryBuilder(CISales.Payment);
                queryBldr.addWhereAttrInQuery(CISales.Payment.TargetDocument, attrQuery2);
                final MultiPrintQuery multi = queryBldr.getPrint();
                final SelectBuilder selProvTaxNum = new SelectBuilder().linkto(CISales.Payment.TargetDocument)
                                .linkto(CISales.PaymentDetractionOut.Contact).clazz(CIContacts.ClassOrganisation)
                                .attribute(CIContacts.ClassOrganisation.TaxNumber);
                final SelectBuilder selProvId = new SelectBuilder().linkto(CISales.Payment.TargetDocument)
                                .linkto(CISales.PaymentDetractionOut.Contact).id();
                final SelectBuilder selOperType = new SelectBuilder().linkto(CISales.Payment.TargetDocument)
                                .linkfrom(CISales.BulkPaymentDetraction2PaymentDocument,
                                                CISales.BulkPaymentDetraction2PaymentDocument.ToLink)
                                .linkto(CISales.BulkPaymentDetraction2PaymentDocument.OperationType)
                                .attribute(CISales.AttributeDefinitionOperationType.Value);
                final SelectBuilder selServType = new SelectBuilder().linkto(CISales.Payment.TargetDocument)
                                .linkfrom(CISales.BulkPaymentDetraction2PaymentDocument,
                                                CISales.BulkPaymentDetraction2PaymentDocument.ToLink)
                                .linkto(CISales.BulkPaymentDetraction2PaymentDocument.ServiceType)
                                .attribute(CISales.AttributeDefinitionOperationType.Value);
                final SelectBuilder selDocDate = new SelectBuilder().linkto(CISales.Payment.CreateDocument)
                                .attribute(CISales.DocumentSumAbstract.Date);
                multi.addSelect(selProvTaxNum, selProvId, selOperType, selServType, selDocDate);
                multi.addAttribute(CISales.Payment.Amount);
                multi.execute();
                while (multi.next()) {
                    final List<Object> rowLst = new ArrayList<>();
                    final String provTaxNum = multi.<String>getSelect(selProvTaxNum);
                    final BigDecimal amount = multi.<BigDecimal>getAttribute(CISales.Payment.Amount);
                    this.totalAmount = this.totalAmount.add(amount);
                    final Long provId = multi.<Long>getSelect(selProvId);
                    final String accNum = map.get(provId);
                    final String operType = multi.<String>getSelect(selOperType);
                    final String servType = multi.<String>getSelect(selServType);
                    final DateTime docDate = multi.<DateTime>getSelect(selDocDate);
                    rowLst.add(provTaxNum);
                    rowLst.add("");
                    rowLst.add(servType);
                    rowLst.add(accNum);
                    rowLst.add(amount);
                    rowLst.add(operType);
                    rowLst.add(docDate);
                    lst.add(rowLst);
                }

                return lst;
            }
        }.getTextReport(_parameter);
    }

    protected String getSequenceNumber(final Parameter _parameter)
        throws EFapsException
    {
        String ret = "";
        final Instance instance = _parameter.getInstance();
        final PrintQuery print = new PrintQuery(instance);
        print.addAttribute(CISales.BulkPaymentDetraction.Date,
                        CISales.BulkPaymentDetraction.DueDate);
        print.execute();
        final DateTime dateFrom = print.<DateTime>getAttribute(CISales.BulkPaymentDetraction.Date);

        final QueryBuilder queryBldr = new QueryBuilder(CISales.BulkPaymentDetraction);
        queryBldr.addWhereAttrGreaterValue(CISales.BulkPaymentDetraction.Date,
                        new DateTime(dateFrom.getYear(), 1, 1, 0, 0, 0).minusSeconds(1));
        queryBldr.addWhereAttrLessValue(CISales.BulkPaymentDetraction.Date, dateFrom);
        final String year = new SimpleDateFormat("yy").format(dateFrom.toDate());
        final InstanceQuery query = queryBldr.getQuery();
        query.execute();
        final Integer num = query.getValues().size() + 1;
        final Formatter formatter = new Formatter();
        ret = formatter.format("%1$2s%2$04d", year, num).toString();
        formatter.close();

        return ret;
    }
}


text:
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <inttypes.h>
#include <stdio.h>
#include <termios.h>
#include <errno.h>
#include <sys/queue.h>

#include <rte_common.h>
#include <rte_memory.h>
#include <rte_eal.h>
#include <rte_branch_prediction.h>
#include <rte_launch.h>
#include <rte_log.h>
#include <rte_per_lcore.h>
#include <rte_lcore.h>
#include <rte_ring.h>
#include <rte_debug.h>
#include <rte_mempool.h>
#include <rte_string_fns.h>

#include <cmdline_rdline.h>
#include <cmdline_parse.h>
#include <cmdline_parse_string.h>
#include <cmdline_socket.h>
#include <cmdline.h>
#include "mp_commands.h"

/**********************************************************/

struct cmd_send_result {
	cmdline_fixed_string_t action;
	cmdline_fixed_string_t message;
};

static void cmd_send_parsed(void *parsed_result,
		__rte_unused struct cmdline *cl,
		__rte_unused void *data)
{
	void *msg = NULL;
	struct cmd_send_result *res = parsed_result;

	if (rte_mempool_get(message_pool, &msg) < 0)
		rte_panic("Failed to get message buffer\n");
	strlcpy((char *)msg, res->message, STR_TOKEN_SIZE);
	if (rte_ring_enqueue(send_ring, msg) < 0) {
		printf("Failed to send message - message discarded\n");
		rte_mempool_put(message_pool, msg);
	}
}

cmdline_parse_token_string_t cmd_send_action =
	TOKEN_STRING_INITIALIZER(struct cmd_send_result, action, "send");
cmdline_parse_token_string_t cmd_send_message =
	TOKEN_STRING_INITIALIZER(struct cmd_send_result, message, NULL);

cmdline_parse_inst_t cmd_send = {
	.f = cmd_send_parsed,  /* function to call */
	.data = NULL,      /* 2nd arg of func */
	.help_str = "send a string to another process",
	.tokens = {        /* token list, NULL terminated */
			(void *)&cmd_send_action,
			(void *)&cmd_send_message,
			NULL,
	},
};

/**********************************************************/

struct cmd_quit_result {
	cmdline_fixed_string_t quit;
};

static void cmd_quit_parsed(__rte_unused void *parsed_result,
			    struct cmdline *cl,
			    __rte_unused void *data)
{
	quit = 1;
	cmdline_quit(cl);
}

cmdline_parse_token_string_t cmd_quit_quit =
	TOKEN_STRING_INITIALIZER(struct cmd_quit_result, quit, "quit");

cmdline_parse_inst_t cmd_quit = {
	.f = cmd_quit_parsed,  /* function to call */
	.data = NULL,      /* 2nd arg of func */
	.help_str = "close the application",
	.tokens = {        /* token list, NULL terminated */
		(void *)&cmd_quit_quit,
		NULL,
	},
};

/**********************************************************/

struct cmd_help_result {
	cmdline_fixed_string_t help;
};

static void cmd_help_parsed(__rte_unused void *parsed_result,
			    struct cmdline *cl,
			    __rte_unused void *data)
{
	cmdline_printf(cl, "Simple demo example of multi-process in RTE\n\n"
			"This is a readline-like interface that can be used to\n"
			"send commands to the simple app. Commands supported are:\n\n"
			"- send [string]\n" "- help\n" "- quit\n\n");
}

cmdline_parse_token_string_t cmd_help_help =
	TOKEN_STRING_INITIALIZER(struct cmd_help_result, help, "help");

cmdline_parse_inst_t cmd_help = {
	.f = cmd_help_parsed,  /* function to call */
	.data = NULL,      /* 2nd arg of func */
	.help_str = "show help",
	.tokens = {        /* token list, NULL terminated */
		(void *)&cmd_help_help,
		NULL,
	},
};

/****** CONTEXT (list of instruction) */
cmdline_parse_ctx_t simple_mp_ctx[] = {
		(cmdline_parse_inst_t *)&cmd_send,
		(cmdline_parse_inst_t *)&cmd_quit,
		(cmdline_parse_inst_t *)&cmd_help,
	NULL,
};

redpajama_set_name: RedPajamaGithub


text:
namespace {

    TEST(PainterTest, CanDrawSomething) {
        langlab::MockTurtle turtle;
        EXPECT_CALL(turtle, PenDown()).Times(::testing::AtLeast(1));
        EXPECT_CALL(turtle, PenUp()).Times(::testing::AtLeast(1));

        langlab::Painter painter;

        EXPECT_TRUE(painter.paint(turtle));
    }

    int main(int argc, char **argv) {
        ::testing::InitGoogleTest(&argc, argv);
        return RUN_ALL_TESTS();
    }

}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>C.P. Bracken | My bits</title>
    <link>http://lpantano.github.io/author/c.p.-bracken/</link>
      <atom:link href="http://lpantano.github.io/author/c.p.-bracken/index.xml" rel="self" type="application/rss+xml" />
    <description>C.P. Bracken</description>
    <generator>Wowchemy (https://wowchemy.com)</generator><language>en-us</language><lastBuildDate>Wed, 01 Jan 2014 00:00:00 +0000</lastBuildDate>
    <image>
      <url>http://lpantano.github.io/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_512x512_fill_lanczos_center_3.png</url>
      <title>C.P. Bracken</title>
      <link>http://lpantano.github.io/author/c.p.-bracken/</link>
    </image>

    <item>
      <title>Regulation of miRNA strand selection: follow the leader?</title>
      <link>http://lpantano.github.io/publication/meijer-2014/</link>
      <pubDate>Wed, 01 Jan 2014 00:00:00 +0000</pubDate>
      <guid>http://lpantano.github.io/publication/meijer-2014/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
<?php
/**
 * @package WordPress
 * @subpackage Andrea
 */
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>

<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<title><?php wp_title(); ?> <?php bloginfo('name'); ?></title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php if ( is_singular() && get_option( 'thread_comments' ) ) wp_enqueue_script( 'comment-reply' ); ?>
<?php wp_head(); ?>
<?php $options = andrea_get_theme_options(); ?>

<body <?php body_class( $options['layout_choice'] ); ?>>

		<?php if ( '' != get_header_image() ) : ?>
			<a href="<?php bloginfo( 'url' ); ?>/"><img src="<?php header_image(); ?>" alt="" />
		<?php endif; ?>

<a href="<?php bloginfo( 'url' ); ?>/"><?php bloginfo( 'name' ); ?>   <?php bloginfo( 'description' ); ?>

		<?php wp_nav_menu( array( 'container' => false, 'theme_location' => 'primary' ) ); ?>

<a href="<?php bloginfo( 'rss2_url' ); ?>"><?php _e( 'RSS Feed', 'andrea' ); ?>


text:
package org.woehlke.twitterwall.oodm.service;

import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.junit4.SpringRunner;
import org.woehlke.twitterwall.configuration.properties.TestdataProperties;
import org.woehlke.twitterwall.oodm.model.HashTag;
import org.woehlke.twitterwall.oodm.model.entities.Entities;
import org.woehlke.twitterwall.oodm.model.transients.HashTagCounted;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HashTagServiceTest implements DomainObjectMinimalServiceTest,DomainServiceWithTaskTest {

    private static final Logger log = LoggerFactory.getLogger(HashTagServiceTest.class);

    @Autowired
    private HashTagService hashTagService;

    @Autowired
    private TestdataProperties testdataProperties;

    @Test
    public void test000areDependenciesLoaded() throws Exception {
        Assert.assertNotNull(hashTagService);
        Assert.assertNotNull(testdataProperties);
    }

    @Commit
    @Test
    public void test001fetchTestData() throws Exception {
        String msg = "fetchTestData: ";
        int page=1;
        int size=1;
        Pageable pageRequest = new PageRequest(page,size);
        Page<HashTag> myPage = hashTagService.getAll(pageRequest);
        if(myPage.getTotalElements()>0){
            HashTag myHashTag = myPage.getContent().iterator().next();
            Assert.assertNotNull(msg,myHashTag);
            Assert.assertNotNull(msg,myHashTag.getText());
            log.debug(msg+" found: "+myHashTag.getText());
        } else {
            log.debug(msg+" found: myPage.getTotalElements() == 0");
        }
    }

    @Commit
    @Test
    public void test002findByText() throws Exception {
        String msg = "findByText: ";
        int page=1;
        int size=1;
        Pageable pageRequest = new PageRequest(page,size);
        Page<HashTag> myPage = hashTagService.getAll(pageRequest);
        HashTag myHashTag = myPage.getContent().iterator().next();
        String myHashTagText = myHashTag.getText();
        HashTag myHashTagResult = hashTagService.findByText(myHashTagText);
        Assert.assertEquals(myHashTag.getId(),myHashTagResult.getId());
        Assert.assertEquals(myHashTag.getUniqueId(),myHashTagResult.getUniqueId());
        Assert.assertEquals(myHashTag.getUniqueId(),myHashTagResult.getUniqueId());
        log.debug(msg+" found: "+myHashTagResult.getText());
    }

    /**
     * @throws Exception
     *
     * @see org.woehlke.twitterwall.oodm.model.HashTag
     * @see Entities
     * @see org.woehlke.twitterwall.oodm.model.transients.mapper.CountAllTweets2HashTagsRowMapper#SQL_COUNT_ALL_TWEET_2_HASHTAG
     * @see org.woehlke.twitterwall.oodm.repositories.custom.impl.HashTagRepositoryImpl#countAllTweet2HashTag(Pageable)
     * @see org.woehlke.twitterwall.oodm.service.impl.HashTagServiceImpl#getHashTagsTweets(Pageable)
     */
    @Commit
    @Test
    public void test003getHashTagsTweets() throws Exception {
        String msg = "getHashTagsTweets: ";
        int page=1;
        int size=30;
        Pageable pageRequestTweets = new PageRequest(page,size);
        Page<HashTagCounted> hashTagsTweets = hashTagService.getHashTagsTweets(pageRequestTweets);
        for(HashTagCounted counted:hashTagsTweets){
            log.debug(msg+" hashTagsTweets: "+counted.getText());
        }
    }

    /**
     * @throws Exception
     *
     * @see org.woehlke.twitterwall.oodm.model.HashTag
     * @see Entities
     * @see org.woehlke.twitterwall.oodm.model.transients.mapper.CountAllUsers2HashTagsRowMapper#SQL_COUNT_ALL_USER_2_HASHTAG
     * @see org.woehlke.twitterwall.oodm.repositories.custom.impl.HashTagRepositoryImpl#countAllUser2HashTag(Pageable)
     * @see org.woehlke.twitterwall.oodm.service.impl.HashTagServiceImpl#getHashTagsUsers(Pageable)
     */
    @Commit
    @Test
    public void test004getHashTagsUsers() throws Exception {
        String msg = "getHashTagsUsers: ";
        int page=1;
        int size=30;
        Pageable pageRequestUsers = new PageRequest(page,size);
        Page<HashTagCounted> hashTagsUsers = hashTagService.getHashTagsUsers(pageRequestUsers);
        for(HashTagCounted counted:hashTagsUsers){
            log.debug(msg+" hashTagsUsers: "+counted.getText());
        }
    }

    @Commit
    @Test
    @Override
    public void test050findById() throws Exception {

    }

    @Commit
    @Test
    @Override
    public void test051getAll() throws Exception {

    }

    @Commit
    @Test
    @Override
    public void test052count() throws Exception {

    }

    @Commit
    @Test
    @Override
    public void test053findByUniqueId() throws Exception {

    }

    @Commit
    @Test
    @Override
    public void test100store() throws Exception {

    }

    @Commit
    @Test
    @Override
    public void test101create() throws Exception {

    }

    @Commit
    @Test
    @Override
    public void test102update() throws Exception {

    }
}


text:
function [p] = ispsd(A)
%ISPSD  Check for positive-definiteness.
%
% usage
%   ispsd = ISPSD(A)
%
% input
%   A = matrix (need not be symmetric,
%               remember though that only symmetric part determines
%               sign-definiteness, anti-symmetric/symplectic part is
%               conservative, i.e., Hamiltonian)
%
% output
%   ispsd = 1:if positive-definite | 0:otherwise
%
% tip
%   use ispsd(-A) to check for negative definiteness
%
% 2013.01.23 (c) Ioannis Filippidis
%
% See also check_psd, chol.

if ~issquare(A)
    p = 0;
    return
end

if ~issymmetric(A)
    warning('Checking for PSD matrix which is not symmetric.')
end

if exist('chol', 'file') && (exist('OCTAVE_VERSION') == 0)
    [tilde, notpsd] = chol(A);
    p = ~notpsd;
else
    % do it the hard way
    % (testing with Freemat, which does not have chol)
    if ~all(eig(A) >= 0)
        p = 0;
    else
        p = 1;
    end
end


text:
<?php

namespace NumPHP\LinAlg\LinAlg;

use NumPHP\Core\NumArray;
use NumPHP\Core\NumPHP;
use NumPHP\LinAlg\Exception\InvalidArgumentException;
use NumPHP\LinAlg\Exception\SingularMatrixException;
use NumPHP\LinAlg\LinAlg;

/**
 * Class LinearSystem
 *
 * @package   NumPHP\LinAlg\LinAlg
 * @author    Gordon Lesti <info@gordonlesti.com>
 * @copyright 2014-2015 Gordon Lesti (https://gordonlesti.com/)
 * @license   http://opensource.org/licenses/MIT The MIT License (MIT)
 * @link      http://numphp.org/
 * @since     1.0.0
 */
abstract class LinearSystem
{
    /**
     * Solves a linear system
     *
     * @param NumArray $squareMatrix matrix of size n*n
     * @param NumArray $numArray     vector of size n or matrix of size n*m
     *
     * @throws \NumPHP\LinAlg\Exception\SingularMatrixException will be thrown, if
     * `$squareMatrix` is singular
     * @throws \NumPHP\LinAlg\Exception\InvalidArgumentException will be thrown, if
     * linear system of `$squareMatrix` and `$numArray` can not be solved
     *
     * @return NumArray
     *
     * @since 1.0.0
     */
    public static function solve(NumArray $squareMatrix, NumArray $numArray)
    {
        if (!Helper::isNotSingularMatrix($squareMatrix)) {
            throw new SingularMatrixException(sprintf("First Argument has to be a not singular square matrix"));
        }
        if (!Helper::isVector($numArray) && !Helper::isMatrix($numArray)) {
            throw new InvalidArgumentException(
                sprintf(
                    "Second argument has to be a vector or a matrix, NumArray with dimension %d given",
                    $numArray->getNDim()
                )
            );
        }
        $shape1 = $squareMatrix->getShape();
        $shape2 = $numArray->getShape();
        if ($shape1[0] !== $shape2[0]) {
            throw new InvalidArgumentException(
                sprintf(
                    "Can not solve a linear system with matrix (%s) and matrix (%s)",
                    implode(', ', $shape1),
                    implode(', ', $shape2)
                )
            );
        }

        /**
         * The result of LinAlg::lud is a array with three NumArrays
         *
         * @var NumArray $pMatrix
         * @var NumArray $lMatrix
         * @var NumArray $uMatrix
         */
        list($pMatrix, $lMatrix, $uMatrix) = LinAlg::lud($squareMatrix);

        $yNumArray = self::forwardSubstitution($lMatrix, $pMatrix->getTranspose()->dot($numArray));
        $zNumArray = self::backSubstitution($uMatrix, $yNumArray);

        return $zNumArray;
    }

    /**
     * Forward Substitution solves a linear system with a lower triangular matrix of
     * size n*n and a vector of size n or matrix of size n*m
     *
     * @param NumArray $lMatrix   lower triangular matrix of size n*n
     * @param NumArray $numArray  vector of size n or matrix of size n*m
     *
     * @return NumArray
     *
     * @since 1.0.0
     */
    protected static function forwardSubstitution(NumArray $lMatrix, NumArray $numArray)
    {
        $shape = $numArray->getShape();
        if (Helper::isVector($numArray)) {
            $xVector = NumPHP::zerosLike($numArray);

            for ($i = 0; $i < $shape[0]; $i++) {
                $slice = sprintf('0:%d', $i);
                $sum = $lMatrix->get($i, $slice)->dot($xVector->get($slice));
                $xVector->set(
                    $i,
                    $numArray->get($i)->sub($sum)->div($lMatrix->get($i, $i))
                );
            }

            return $xVector;
        }
        // $numArray is a matrix
        $copy = clone $numArray;

        for ($i = 0; $i < $shape[1]; $i++) {
            $copy->set(':', $i, self::forwardSubstitution($lMatrix, $copy->get(':', $i)));
        }

        return $copy;
    }

    /**
     * Back Substitution solves a linear system with a upper triangular matrix of
     * size n*n and a vector of size n or a matrix of size n*m
     *
     * @param NumArray $uMatrix   upper triangular matrix of size n*n
     * @param NumArray $numArray  vector of size n or matrix of size n*m
     *
     * @return NumArray
     *
     * @since 1.0.0
     */
    protected static function backSubstitution(NumArray $uMatrix, NumArray $numArray)
    {
        $shape = $numArray->getShape();
        if (Helper::isVector($numArray)) {
            $xVector = NumPHP::zerosLike($numArray);

            for ($i = $shape[0]-1; $i >= 0; $i--) {
                $slice = sprintf("%d:%d", $i+1, $shape[0]);
                $sum = $uMatrix->get($i, $slice)->dot($xVector->get($slice));
                $xVector->set(
                    $i,
                    $numArray->get($i)->sub($sum)->div($uMatrix->get($i, $i))
                );
            }

            return $xVector;
        }
        // $numArray is a matrix
        $copy = clone $numArray;

        for ($i = 0; $i < $shape[1]; $i++) {
            $copy->set(':', $i, self::backSubstitution($uMatrix, $copy->get(':', $i)));
        }

        return $copy;
    }
}


text:
package org.apache.nifi.processors.rethinkdb;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.gson.Gson;
import com.rethinkdb.net.Connection;

public class TestGetRethinkDB {
    private static final String DOCUMENT_ID = "id1";
    private TestRunner runner;
    private AbstractRethinkDBProcessor mockGetRethinkDB;
    private Map<String,Object> document;

    @Before
    public void setUp() throws Exception {
        mockGetRethinkDB = new GetRethinkDB() {
            @Override
            protected Connection makeConnection() {
                return null;
            }

            @Override
            protected Map<String,Object> getDocument(String id, String readMode) {
                return document;
            }
        };
        runner = TestRunners.newTestRunner(mockGetRethinkDB);
        runner.setProperty(GetRethinkDB.DB_NAME, "test");
        runner.setProperty(GetRethinkDB.DB_HOST, "host1");
        runner.setProperty(GetRethinkDB.DB_PORT, "1234");
        runner.setProperty(GetRethinkDB.USERNAME, "u1");
        runner.setProperty(GetRethinkDB.PASSWORD, "p1");
        runner.setProperty(GetRethinkDB.TABLE_NAME, "t1");
        runner.setProperty(GetRethinkDB.CHARSET, "UTF-8");
        runner.setProperty(GetRethinkDB.READ_MODE, "single");
        runner.setProperty(GetRethinkDB.RETHINKDB_DOCUMENT_ID, "${rethinkdb.id}");
        runner.setProperty(GetRethinkDB.MAX_DOCUMENTS_SIZE, "1 KB");
        runner.assertValid();
    }

    @After
    public void tearDown() throws Exception {
        runner = null;
    }

    @Test
    public void testDefaultValid() {
        runner.assertValid();
    }

    @Test
    public void testBlankHost() {
        runner.setProperty(GetRethinkDB.DB_HOST, "");
        runner.assertNotValid();
    }

    @Test
    public void testEmptyPort() {
        runner.setProperty(GetRethinkDB.DB_PORT, "");
        runner.assertNotValid();
    }

    @Test
    public void testEmptyDBName() {
        runner.setProperty(GetRethinkDB.DB_NAME, "");
        runner.assertNotValid();
    }

    @Test
    public void testEmptyUsername() {
        runner.setProperty(GetRethinkDB.USERNAME, "");
        runner.assertNotValid();
    }

    @Test
    public void testEmptyPassword() {
        runner.setProperty(GetRethinkDB.PASSWORD, "p1");
        runner.assertValid();
    }

    @Test
    public void testCharsetUTF8() {
        runner.setProperty(GetRethinkDB.CHARSET, "UTF-8");
        runner.assertValid();
    }

    @Test
    public void testCharsetBlank() {
        runner.setProperty(GetRethinkDB.CHARSET, "");
        runner.assertNotValid();
    }
    @Test
    public void testZeroMaxDocumentSize() {
        runner.setProperty(GetRethinkDB.MAX_DOCUMENTS_SIZE, "0");
        runner.assertNotValid();
    }

    @Test
    public void testBlankReadMode() {
        runner.setProperty(GetRethinkDB.READ_MODE, "");
        runner.assertNotValid();
    }

    @Test
    public void testSizeGreaterThanThreshold() {
        runner.setProperty(GetRethinkDB.MAX_DOCUMENTS_SIZE, "1 B");
        runner.assertValid();
        document = new HashMap<>();
        document.put("hello", "rethinkdb");

        HashMap<String,String> props = new HashMap<>();
        props.put("rethinkdb.id", DOCUMENT_ID);

        runner.enqueue(new byte[]{}, props);
        runner.run(1,true,true);
        runner.assertAllFlowFilesTransferred(AbstractRethinkDBProcessor.REL_FAILURE, 1);
        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(AbstractRethinkDBProcessor.REL_FAILURE);
        assertNotNull(flowFiles.get(0).getAttribute(AbstractRethinkDBProcessor.RETHINKDB_ERROR_MESSAGE));
    }

    @Test
    public void testNotFound() {
        runner.setProperty(AbstractRethinkDBProcessor.MAX_DOCUMENTS_SIZE, "1 B");
        runner.assertValid();

        HashMap<String,String> props = new HashMap<>();
        props.put("rethinkdb.id", DOCUMENT_ID);

        runner.enqueue(new byte[]{}, props);

        runner.run(1,true,true);

        runner.assertAllFlowFilesTransferred(AbstractRethinkDBProcessor.REL_NOT_FOUND, 1);
        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(AbstractRethinkDBProcessor.REL_NOT_FOUND);
        assertNotNull(flowFiles.get(0).getAttribute(AbstractRethinkDBProcessor.RETHINKDB_ERROR_MESSAGE));
        flowFiles.get(0).assertAttributeEquals(AbstractRethinkDBProcessor.RETHINKDB_ERROR_MESSAGE,"Document with id '" + DOCUMENT_ID + "' not found");
    }

    @Test
    public void testBlankId() {
        runner.setProperty(AbstractRethinkDBProcessor.MAX_DOCUMENTS_SIZE, "1 B");
        runner.assertValid();
        runner.setProperty(GetRethinkDB.RETHINKDB_DOCUMENT_ID, "${rethinkdb.id}");
        Map<String,String> props = new HashMap<>();

        runner.enqueue(new byte[]{},props);
        runner.run(1,true,true);
        runner.assertAllFlowFilesTransferred(AbstractRethinkDBProcessor.REL_FAILURE, 1);
        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(AbstractRethinkDBProcessor.REL_FAILURE);
        assertNotNull(flowFiles.get(0).getAttribute(AbstractRethinkDBProcessor.RETHINKDB_ERROR_MESSAGE));
        flowFiles.get(0).assertAttributeEquals(AbstractRethinkDBProcessor.RETHINKDB_ERROR_MESSAGE,GetRethinkDB.DOCUMENT_ID_EMPTY_MESSAGE);
    }

    @Test
    public void testNullId() {
        runner.setProperty(AbstractRethinkDBProcessor.MAX_DOCUMENTS_SIZE, "1 B");
        runner.assertValid();
        runner.setProperty(GetRethinkDB.RETHINKDB_DOCUMENT_ID, "${rethinkdb.id}");
        Map<String,String> props = new HashMap<>();
        props.put("rethinkdb.id", null);
        runner.enqueue(new byte[]{},props);
        runner.run(1,true,true);
        runner.assertAllFlowFilesTransferred(AbstractRethinkDBProcessor.REL_FAILURE, 1);
        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(AbstractRethinkDBProcessor.REL_FAILURE);
        assertNotNull(flowFiles.get(0).getAttribute(AbstractRethinkDBProcessor.RETHINKDB_ERROR_MESSAGE));
        flowFiles.get(0).assertAttributeEquals(AbstractRethinkDBProcessor.RETHINKDB_ERROR_MESSAGE,GetRethinkDB.DOCUMENT_ID_EMPTY_MESSAGE);
    }

    @Test
    public void testValidSingleMessage() {
        runner.setProperty(AbstractRethinkDBProcessor.MAX_DOCUMENTS_SIZE, "1 MB");
        runner.assertValid();
        document = new HashMap<>();
        document.put("hello", "rethinkdb");

        HashMap<String,String> props = new HashMap<>();
        props.put("rethinkdb.id", DOCUMENT_ID);

        runner.enqueue(new byte[]{}, props);

        runner.run(1,true,true);
        runner.assertAllFlowFilesTransferred(AbstractRethinkDBProcessor.REL_SUCCESS, 1);
        Gson gson = new Gson();

        String json = gson.toJson(document);

        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(AbstractRethinkDBProcessor.REL_SUCCESS);
        flowFiles.get(0).assertContentEquals(json.toString());
        assertNull(flowFiles.get(0).getAttribute(AbstractRethinkDBProcessor.RETHINKDB_ERROR_MESSAGE));

    }

    @Test
    public void testGetThrowsException() {
        mockGetRethinkDB = new GetRethinkDB() {
            @Override
            protected Connection makeConnection() {
                return null;
            }

            @Override
            protected Map<String,Object> getDocument(String id, String readMode) {
                throw new RuntimeException("testException");
            }
        };

        runner = TestRunners.newTestRunner(mockGetRethinkDB);
        runner.setProperty(AbstractRethinkDBProcessor.DB_NAME, "test");
        runner.setProperty(AbstractRethinkDBProcessor.DB_HOST, "host1");
        runner.setProperty(AbstractRethinkDBProcessor.DB_PORT, "1234");
        runner.setProperty(AbstractRethinkDBProcessor.USERNAME, "u1");
        runner.setProperty(AbstractRethinkDBProcessor.PASSWORD, "p1");
        runner.setProperty(AbstractRethinkDBProcessor.TABLE_NAME, "t1");
        runner.setProperty(AbstractRethinkDBProcessor.CHARSET, "UTF-8");
        runner.setProperty(GetRethinkDB.READ_MODE, "single");

        runner.setProperty(AbstractRethinkDBProcessor.MAX_DOCUMENTS_SIZE, "1 KB");
        runner.setProperty(GetRethinkDB.RETHINKDB_DOCUMENT_ID, DOCUMENT_ID);

        runner.assertValid();

        HashMap<String,String> props = new HashMap<>();
        props.put("rethinkdb.id", DOCUMENT_ID);

        runner.enqueue(new byte[]{}, props);

        runner.run(1,true,true);
        runner.assertAllFlowFilesTransferred(PutRethinkDB.REL_FAILURE, 1);

        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(AbstractRethinkDBProcessor.REL_FAILURE);
        assertNotNull(flowFiles.get(0).getAttribute(AbstractRethinkDBProcessor.RETHINKDB_ERROR_MESSAGE));
        flowFiles.get(0).assertAttributeEquals(AbstractRethinkDBProcessor.RETHINKDB_ERROR_MESSAGE,"testException");
   }
}


text:
<?php

namespace Codeburner\Router;

/**
 * Create paths based on registered routes.
 *
 * @author Alex Rohleder <contato@alexrohleder.com.br>
 */

class Path
{

    /**
     * @var Collector
     */

    protected $collector;

    /**
     * Link constructor.
     *
     * @param Collector $collector
     */

    public function __construct(Collector $collector)
    {
        $this->collector = $collector;
    }

    /**
     * Generate a path to a route named by $name.
     *
     * @param string $name
     * @param array $args
     *
     * @throws \BadMethodCallException
     * @return string
     */

    public function to($name, array $args = [])
    {
        $route = $this->collector->findNamedRoute($name);
        $parser = $this->collector->getParser();
        $pattern = $route->getPattern();

        preg_match_all("~" . $parser::DYNAMIC_REGEX . "~x", $pattern, $matches, PREG_SET_ORDER);

        foreach ((array) $matches as $key => $match) {
            if (!isset($args[$match[1]])) {
                throw new \BadMethodCallException("Missing argument '{$match[1]}' on creation of link for '{$name}' route.");
            }

            $pattern = str_replace($match[0], $args[$match[1]], $pattern);
        }

        return $pattern;
    }

}


text:
extern crate postgres;
extern crate time;
extern crate rustc_serialize;

use nickel::{Nickel, JsonBody, FormBody};
use nickel::status::StatusCode;
use postgres::{Connection, SslMode};
use std::collections::HashMap;
use rustc_serialize::json::{Json, ToJson};
use std::collections::BTreeMap;

#[derive(RustcDecodable, RustcEncodable)]
struct BatteryData {
    machine_id: String
}

//impl ToJson for BatteryData {
    //fn to_json(&self) -> Json {
        //let mut map = BTreeMap::new();
        //map.insert("machine_id".to_string(), self.machine_id.to_json());
        //Json::Object(map)
    //}
//}

fn init_routing(server: &mut nickel::Nickel){
    server.utilize(router! {
        get "/" => |request, response| {
            "Hello world!"
        }
        post "/insert/:table_name" => |req, res| {
            //let bdata = try_with!(response, {
                //request.json_as::<HashMap>().map_err(|e| (StatusCode::BadRequest, e))
            //});
            //let form_body = try_with!(res, req.form_body());
            let form_body = req.form_body().unwrap();
            //let table_name = req.param("table_name").unwrap();
            //table_name
            println!("{:?}", form_body.get("hello"));
            format!("{:?}", form_body)
        }
    });
}

fn start_server(){
    let mut server = Nickel::new();
    init_routing(&mut server);
    server.listen("127.0.0.1:6767");
}

fn init_database(){
    let conn = Connection::connect("postgres://livia:postgrespass@localhost/livia", SslMode::None).unwrap();

    conn.execute("CREATE EXTENSION IF NOT EXISTS hstore", &[]).unwrap();
    conn.execute("CREATE TABLE IF NOT EXISTS table_metadata (
                id              SERIAL PRIMARY KEY,
                name            TEXT UNIQUE NOT NULL,
                creation_time   TIMESTAMP NOT NULL,
                battery_mapping HSTORE NOT NULL
            )", &[]).unwrap();

    let mut battery_mapping = HashMap::new();
    battery_mapping.insert("machine_id".to_string(), Some("i32".to_string()));
    battery_mapping.insert("time".to_string(), Some("Timespec".to_string()));
    battery_mapping.insert("percent".to_string(), Some("i32".to_string()));

    let name = "battery_data";
    let now = time::get_time();

    conn.execute("INSERT INTO table_metadata
                 (name, creation_time, battery_mapping)
                 VALUES ($1, $2, $3)
                 ON CONFLICT DO NOTHING",
                 &[&name, &now, &battery_mapping]).unwrap();

    conn.execute("CREATE TABLE IF NOT EXISTS battery_data (
                id              SERIAL PRIMARY KEY,
                machine_id      INT NOT NULL,
                time            TIMESTAMP NOT NULL,
                percent         INT NOT NULL
            )", &[]).unwrap();
}

fn main() {
    init_database();
    start_server();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/content"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="@color/kampr_green"
  android:orientation="vertical"
  android:padding="10dp" >

  <TextView
    android:id="@+id/login_logo"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:background="@drawable/login_logo" />

  <EditText
    android:id="@+id/login_username"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:layout_marginTop="50dp"
    android:autoText="true"
    android:background="@color/white"
    android:hint="Username or Email"
    android:minHeight="40dp"
    android:padding="5dp"
    android:textColor="@color/kampr_dark_green"
    android:textColorHint="@color/kampr_light_green"
    android:textSize="18sp"
    android:textStyle="bold" />

  <EditText
    android:id="@+id/login_password"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:background="@color/white"
    android:hint="Password"
    android:inputType="textPassword"
    android:minHeight="40dp"
    android:padding="5dp"
    android:textColor="@color/kampr_dark_green"
    android:textColorHint="@color/kampr_light_green"
    android:textSize="18sp"
    android:textStyle="bold" />

  <Button
    android:id="@+id/login_submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="10dp"
    android:background="@color/kampr_dark_green"
    android:minHeight="60dp"
    android:minWidth="64dp"
    android:paddingLeft="40dp"
    android:paddingRight="40dp"
    android:text="Login"
    android:textColor="@color/white"
    android:textColorHint="@color/white"
    android:textStyle="bold" />

  <TextView
    android:id="@+id/sign_up_link"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:gravity="center"
    android:text="Don't have an account? Sign up on Forrst"
    android:textColor="@color/white"
    android:textSize="16sp" />

</LinearLayout>


text:
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions/predicates/is_debugger_present.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/debug_output_backend.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/sources/record_ostream.hpp>

#if defined(BOOST_WINDOWS)

namespace logging = boost::log;
namespace expr = boost::log::expressions;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;

//[ example_sinks_debugger
// Complete sink type
typedef sinks::synchronous_sink< sinks::debug_output_backend > sink_t;

void init_logging()
{
    boost::shared_ptr< logging::core > core = logging::core::get();

    // Create the sink. The backend requires synchronization in the frontend.
    boost::shared_ptr< sink_t > sink(new sink_t());

    // Set the special filter to the frontend
    // in order to skip the sink when no debugger is available
    sink->set_filter(expr::is_debugger_present());

    core->add_sink(sink);
}
//]

int main(int, char*[])
{
    init_logging();

    src::logger lg;
    BOOST_LOG(lg) << "Hello world!";

    return 0;
}

#else

int main(int, char*[])
{
    return 0;
}

#endif


text:
package util

import xml.NodeSeq
import net.liftweb.json._

/**
 *
 * @author Manuel Bernhardt <bernhardt.manuel@gmail.com>
 */

object Json {

  /**
   * Turns a scala XML node into a JSON string
   *
   * @param xml the input xml document
   * @param escapeNamespaces escapes XML namespace declarations
   * @param removeNamespacePrefix removes the XML namespace prefix
   * @param sequences paths of objects that should only contain arrays
   * @return a string formatted as JSON
   */
  def toJson(xml: NodeSeq, escapeNamespaces: Boolean = false, removeNamespacePrefix: Boolean = false, sequences: Seq[List[String]] = List.empty): JValue = {

    // because lift-json doesn't group XML nodes that have the same name under an array if there's more than one potential group, we do it ourselves here
    // NOTE: lift-json is flattening leaf elements, i.e. considering
    // <foo id="1">x</foo> -> {"a":{"foo":{"foo":"x","id":"1"}}} vs
    // <foo id="1">x</foo> -> {"a":{"foo":"x","id":"1"}}
    // the second case happens.
    // this is leading to trouble if you've got more than one "id" on the same level, e.g.
    // <foo id="1">x</foo><bar id="2">bla</bar> -> {"a":{"foo":"x","bar":"bla","id":["1","2"]}}
    // actually in the original transformation, "1" gets lost, thanks to our systematic grouping we keep it - but it is confusing nonetheless
    val json = groupingTraversal(Xml.toJson(xml))

    // when we are given a set of paths of JObjects for which all children should have arrays as values, mutate accordingly
    var mutated = json
    for (s <- sequences) {
      val value = s.foldLeft(mutated) { _ \ _ } match {
        case JObject(obj: List[JField]) =>
          JObject(obj.map(f => JField(f.name, if (f.value.isInstanceOf[JArray]) f.value else JArray(f.value :: Nil))))
        case other => other
      }
      mutated = mutated.replace(s, value)
    }

    // escape the namespace prefixes so that the JSON values can be easily accessed
    val js = if (escapeNamespaces || removeNamespacePrefix) {
      mutated.transform {
        case JField(name, v) if escapeNamespaces && !removeNamespacePrefix && name.contains(":") => JField(name.replaceAll(":", "_"), v)
        case JField(name, v) if removeNamespacePrefix && name.contains(":") => JField(name.substring(name.indexOf(":") + 1), v)
      }
    } else {
      mutated
    }

    js
  }

  def renderToJson(xml: NodeSeq, escapeNamespaces: Boolean = false, sequences: Seq[List[String]] = List.empty): String = {
    compact(render(toJson(xml, escapeNamespaces, sequences = sequences)))

  }

  private def groupingTraversal(node: JValue): JValue = node match {
    case JObject(obj: Seq[JField]) =>
      val capturedOrder = obj.map(_.name).zipWithIndex.toMap[String, Int]
      val groupedFields = obj.groupBy(_.name)
      val grouped = groupedFields map {
        g =>
          if (g._2.length > 1) {
            JField(g._1, JArray(g._2.map(f => f.value)).map(groupingTraversal(_)))
          } else {
            JField(g._1, g._2.head.value.map(groupingTraversal(_)))
          }
      }
      val reordered = grouped.toList.sortWith((one, two) => capturedOrder(one.name) < capturedOrder(two.name))
      JObject(reordered)
    case other @ _ => other
  }

}


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

    <title>Monitor Project – JDepend Report Metrics</title>

    <link rel="stylesheet" href="./css/print.css" type="text/css" media="print" />
        <meta name="Date-Revision-yyyymmdd" content="20180816" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

                                 Last Published: 2018-08-16
               | Version: 4.0.2

Overview

                  Introduction

Project Documentation

                  Project Information

                  Project Reports

                  JavaDocs

                  Surefire Report

                  Checkstyle

            JDepend

                  Source Xref

                  Test Source Xref

                  Tag List

Metric Results
[ summary ] [ packages ] [ cycles ] [ explanations ]

The following document contains the results of a JDepend metric analysis. The various metrics are defined at the bottom of this document.

Summary
[ summary ] [ packages ] [ cycles ] [ explanations ]

Package
TC
CC
AC
Ca
Ce
A
I
D
V

com.github.vfro
1
1
0
0
2
0.0%
100.0%
0.0%
1

Packages
[ summary ] [ packages ] [ cycles ] [ explanations ]

com.github.vfro

Afferent Couplings
Efferent Couplings
Abstractness
Instability
Distance

0
2
0.0%
100.0%
0.0%

Abstract Classes
Concrete Classes
Used by Packages
Uses Packages

None
com.github.vfro.Monitor$TimeTracker

None
java.lang
java.util.concurrent

Cycles
[ summary ] [ packages ] [ cycles ] [ explanations ]

There are no cyclic dependencies.

Explanation
[ summary ] [ packages ] [ cycles ] [ explanations ]

The following explanations are for quick reference and are lifted directly from the original JDepend documentation.

Term
Description

Number of Classes
The number of concrete and abstract classes (and interfaces) in the package is an indicator of the extensibility of the package.

Afferent Couplings
The number of other packages that depend upon classes within the package is an indicator of the package's responsibility.

Efferent Couplings
The number of other packages that the classes in the package depend upon is an indicator of the package's independence.

Abstractness
The ratio of the number of abstract classes (and interfaces) in the analyzed package to the total number of classes in the analyzed package. The range for this metric is 0 to 1, with A=0 indicating a completely concrete package and A=1 indicating a completely abstract package.

Instability
The ratio of efferent coupling (Ce) to total coupling (Ce / (Ce + Ca)). This metric is an indicator of the package's resilience to change. The range for this metric is 0 to 1, with I=0 indicating a completely stable package and I=1 indicating a completely instable package.

Distance
The perpendicular distance of a package from the idealized line A + I = 1. This metric is an indicator of the package's balance between abstractness and stability. A package squarely on the main sequence is optimally balanced with respect to its abstractness and stability. Ideal packages are either completely abstract and stable (x=0, y=1) or completely concrete and instable (x=1, y=0). The range for this metric is 0 to 1, with D=0 indicating a package that is coincident with the main sequence and D=1 indicating a package that is as far from the main sequence as possible.

Cycles
Packages participating in a package dependency cycle are  in a deadly embrace with respect to reusability and their  release cycle. Package dependency cycles can be easily identified by reviewing the textual reports of dependency cycles. Once these dependency cycles have been identified with JDepend, they can be broken by employing various object-oriented techniques.

        ©            2011-2018

                       - Privacy Policy.
        Apache Maven, Maven, Apache, the Apache feather logo, and the Apache Maven project logos are trademarks of The Apache Software Foundation.


text:
r"""Heteroscedastic GP BatchEnsemble L/32.

"""
# pylint: enable=line-too-long

import ml_collections
from experiments import common_fewshot  # local file import from baselines.jft

def get_config():
  """Config."""
  config = ml_collections.ConfigDict()

  config.dataset = 'jft/entity:1.0.0'
  config.val_split = 'test[:49511]'  # aka tiny_test/test[:5%] in task_adapt
  config.train_split = 'train'  # task_adapt used train+validation so +64167
  config.num_classes = 18291
  config.init_head_bias = -10.0    # ~= ln(1/18k) ~= ln(1/num_classes)

  config.trial = 0
  config.batch_size = 4096
  config.num_epochs = 7

  pp_common = '|value_range(-1, 1)'
  pp_common += f'|onehot({config.num_classes})'
  # To use ancestor 'smearing', use this line instead:
  # pp_common += f'|onehot({config.num_classes}, key='labels_extended', key_result='labels')  # pylint: disable=line-too-long
  pp_common += '|keep(["image", "labels"])'
  config.pp_train = 'decode_jpeg_and_inception_crop(224)|flip_lr' + pp_common
  config.pp_eval = 'decode|resize_small(256)|central_crop(224)' + pp_common
  config.shuffle_buffer_size = 250_000  # Per host, so small-ish is ok.

  config.log_training_steps = 5000
  config.log_eval_steps = 10000
  config.checkpoint_steps = 15000
  config.checkpoint_timeout = 10

  # Model section
  config.model = ml_collections.ConfigDict()
  config.model.patches = ml_collections.ConfigDict()
  config.model.patches.size = [32, 32]
  config.model.hidden_size = 1024
  config.model.transformer = ml_collections.ConfigDict()
  config.model.transformer.attention_dropout_rate = 0.
  config.model.transformer.dropout_rate = 0.
  config.model.transformer.mlp_dim = 4096
  config.model.transformer.num_heads = 16
  config.model.transformer.num_layers = 24
  config.model.classifier = 'token'  # Or 'gap'
  config.model.representation_size = 1024

  # Heteroscedastic
  config.model.multiclass = False
  config.model.temperature = 0.2
  config.model.mc_samples = 100
  config.model.num_factors = 50
  config.model.param_efficient = True

  # BatchEnsemble
  config.model.transformer.be_layers = (21, 22, 23)
  config.model.transformer.ens_size = 3
  config.model.transformer.random_sign_init = -0.5

  # GP
  config.model.use_gp = False
  # Use momentum-based (i.e., non-exact) covariance update for pre-training.
  # This is because the exact covariance update can be unstable for pretraining,
  # since it involves inverting a precision matrix accumulated over 300M data.
  config.model.covmat_momentum = .999
  config.model.ridge_penalty = 1.
  # No need to use mean field adjustment for pretraining.
  config.model.mean_field_factor = -1.

  # Optimizer section
  config.optim_name = 'Adam'
  config.optim = ml_collections.ConfigDict()
  config.optim.weight_decay = 0.1
  config.optim.beta1 = 0.9
  config.optim.beta2 = 0.999
  config.weight_decay = None  # No explicit weight decay
  config.grad_clip_norm = 1.0  # setting from mark's rec
  config.lr = ml_collections.ConfigDict()
  config.lr.base = 6e-4  # LR has to be lower for larger models!
  config.lr.warmup_steps = 10_000
  config.lr.decay_type = 'linear'
  config.lr.linear_end = 1e-5

  # Few-shot eval section
  config.fewshot = common_fewshot.get_fewshot()
  config.fewshot.representation_layer = 'pre_ens_logits'
  config.fewshot.log_steps = 100_000
  return config

def get_sweep(hyper):
  return hyper.product([
      hyper.chainit([
          hyper.product([
              hyper.sweep('config.model.use_gp', [False]),
              hyper.sweep('config.model.transformer.random_sign_init',
                          [0.5, -0.5]),
              hyper.sweep('config.model.mc_samples', [100, 500]),
              hyper.sweep('config.grad_clip_norm', [1.0, 2.5]),
              hyper.sweep('config.model.temperature', [0.2, 0.35, 1.0]),
          ]),
          # hyper.product([
          #     hyper.sweep('config.model.use_gp', [True]),
          #     hyper.sweep('config.lr.base', [3e-4, 4e-4, 6e-4]),
          #     hyper.sweep('config.model.transformer.random_sign_init',
          #                 [0.5, -0.5]),
          #     hyper.sweep('config.model.temperature', [0.2, 0.35, 1.0]),
          # ]),
      ])
  ])


text:
<?php

/**
 * The DomeController class controls the DomeController daemon
 */
class DomeController {

	private $dbconn;
	private $schedule_instance = null;

	public function __construct() {
		$this->dbconn = ColoreDBConnector::getInstance();
	}

	/**
	 * Gets an instance of the Scheduler, maintaining a single instance. (Faux Singleton)
	 */
	private function GetSchedulerInstance() {
		if( $this->schedule_instance == null )
			$this->schedule_instance = new CSchedule();

		return $this->schedule_instance;
	}

	public function AuthenticateController( ColoreRequestHelper &$cro ) {
		// Bail if authenticated
		if( $cro->getSessionProperty( 'authenticated' ) ) {
			$cro->insertLogic( array( 'class' => __CLASS__, 'method' => 'UpdateController' ) );
			return;
		}

		// Set default
		$cro->setSessionProperty( 'authenticated', false );

		// Import request properties
		$request_properties = $cro->getRequestProperties();

		// Check input
		if( ! isset( $request_properties['controller_name'] ) || ! isset( $request_properties['timestamp'] ) || ! isset( $request_properties['hash'] ) ) {
			$cro->setRenderProperty( 'message', 'problem' );
			$cro->setRenderProperty( 'authenticated', 'error1' );
			return false;
		}

		// Set up query
		$controller_query = array(
				'action' => 'select',
				'table' => 'controllers',
				'fields' => array(
						'*' => true,
				),
				'criteria' => array(
						'name' => $request_properties['controller_name'],
				),
		);

		// Execute query
		$controller_info = $this->dbconn->mappedQuery( $controller_query );

		// Check for valid controller information
		if( ! $controller_info || ! is_array( $controller_info ) || ! isset( $controller_info['secret'] ) ) {
			$cro->setRenderProperty( 'authenticated', false );
			$cro->setRenderProperty( 'message', 'Error in controller lookup' );
			return false;
		}

		// Recreate the message hash
		$message_hash = hash_hmac( 'sha256', sprintf( "%s%s%s", $controller_info['name'], $request_properties['timestamp'], $controller_info['secret'] ), $controller_info['secret'] );

		// Check if hash matches, else bail
		if( $message_hash != $request_properties['hash'] ) {
			$cro->setRenderProperty( 'authenticated', false );
			$cro->setRenderProperty( 'error', 'Error verifying controller' );
			return false;
		}

		// Set session info
		$cro->setSessionProperty( 'controller_info', $controller_info );
		$cro->setSessionProperty( 'authenticated', true );

		// Set render info
		$cro->setRenderProperty( 'authenticated', true );

		// Update controller
		$cro->insertLogic( array( 'class' => __CLASS__, 'method' => 'UpdateController' ) );
	}

	public function UpdateController( ColoreRequest &$cro ) {
		$cro->controller_info = $cro->getSessionProperty( 'controller_info' );

		// update query
		$update_query = array(
			'action' => 'update',
			'table' => 'controllers',
			'fields' => array(
				'last_active' => date( "Y-m-d H:i:s" ),
			),
			'criteria' => array(
				'id' => $cro->controller_info['id'],
			),
		);

		$res = $this->dbconn->mappedQuery( $update_query );
	}

	public function GetControllerState( ColoreRequestHelper &$cro ) {
		$controller_info = $cro->getSessionProperty( 'controller_info' );

		// Set up query
		$controller_state_query = array(
				'action' => 'select',
				'table' => 'controllers',
				'fields' => array(
						'mode' => true,
						'script_name' => true,
				),
				'criteria' => array(
						'id' => $controller_info['id'],
				),
		);

		// Execute query
		$controller_state_result = $this->dbconn->mappedQuery( $controller_state_query );

		// Check result, bail on fail
		if( ! is_array( $controller_state_result ) || ! isset( $controller_state_result['mode'] ) ) {
			$cro->setRenderProperty( 'error', 'Error looking up controller state' );
			return false;
		}

		// Set state for rendering
		$cro->setRenderProperty( 'mode', $controller_state_result['mode'] );
		$cro->setRenderProperty( 'script_name', $controller_state_result['script_name'] );

		if( $controller_state_result['mode'] == 0 )
			return;

		// Check the current schedule
		$schedule_data = $this->GetSchedule();

		if( $schedule_data && is_array( $schedule_data ) && isset( $schedule_data['type'] ) ) {
			$cro->setRenderProperty( 'mode', $schedule_data['type'] );
			$cro->setRenderProperty( 'script_name', $schedule_data['options'] );
		}

		// Check for current event
		$event_data = $this->GetEvent();

		// If we have valid event data, override the current state
		if( $event_data && is_array( $event_data ) && isset( $event_data['id'] ) ) {
			$cro->setRenderProperty( 'mode', $event_data['type'] );
			$cro->setRenderProperty( 'script_name', $event_data['options'] );
		}

	}

	public function GetControllerTask( ColoreRequestHelper &$cro ) {
		error_log( sprintf( "%s: %s", __METHOD__, __LINE__ ) );
		// Get controller info
		$controller_info = $cro->getSessionProperty( 'controller_info' );

		// TODO: Schedule
		error_log( sprintf( "%s/%d: %s", __METHOD__, __LINE__, print_r( $this->GetScheduledShow(), true ) ) );

		// Check for current event
		$event_data = $this->GetEvent();

		// If we have valid event data, return the result
		if( $event_data && is_array( $event_data ) && isset( $event_data['id'] ) ) {
			// If we receive a type 0 event, then override the controller state
			$cro->setRenderProperty( 'mode', $event_data['type'] );
			if( $event_data['type'] == 0 ) {
				return;
			} else if( $event_data['type'] == 2 ) {
				$cro->setRenderProperty( 'script_name', $event_data['options'] );
				return;
			} else if( $event_data['type'] != 1 ) {
				// If we receive invalid input, bail.
				return false;
			}
		}

		error_log( sprintf( "%s: %s", __METHOD__, __LINE__ ) );

		// If in animation playback mode, then lookup the current animation
		if( $cro->getRenderProperty( 'mode' ) == 1 ) {
			error_log( sprintf( "%s: Checking for animation", __METHOD__ ) );
			$scheduler = $this->GetSchedulerInstance();
			$animation_info = $scheduler->GetNextScheduleAnimation();
			if( $animation_info && is_array( $animation_info ) && isset( $animation_info['source'] ) ) {
				error_log( sprintf( "%s: Found animation", __METHOD__ ) );

				// Render the animation data
				$animation_data = $this->GetRenderedAnimation( $animation_info['source'] );

				// If successful, then set render properties and return - else fall back
				if( $animation_data ) {
					// Set script_name to domeplayer
					$cro->setRenderProperty( 'script_name', "domeplayer.py" );
					$cro->setRenderProperty( 'id', $animation_info['id'] );
					$cro->setRenderProperty( 'data', base64_encode( $animation_data ) );
					return;
				} else {
					error_log( sprintf( "%s: Animation render failed", __METHOD__ ) );
				}
			} else {
				error_log( sprintf( "%s: No animation found", __METHOD__ ) );
			}
		}

		error_log( sprintf( "%s: %s", __METHOD__, __LINE__ ) );

		// If not blacked out and a script was not set, then get the current controller's default script
		if( $cro->getRenderProperty( 'mode' ) != 0 && ! $cro->getRenderProperty( 'script_name' ) ) {
			// Make query
			$script_query = array(
					'action' => 'select',
					'table' => 'controllers',
					'fields' => array(
							'script_name' => true,
					),
					'criteria' => array(
							'id' => $controller_info['id'],
					),
			);

			$script_result = $this->dbconn->mappedQuery( $script_query );

			if( is_array( $script_result ) && isset( $script_result['script_name'] ) ) {
				$cro->setRenderProperty( 'script_name', $script_result['script_name'] );
				$cro->setRenderProperty( 'id', null );
				$cro->setRenderProperty( 'data', null );
			} else {
				$cro->setRenderProperty( 'script_name', "gradient.py" );
			}
		}

		error_log( sprintf( "%s: %s", __METHOD__, __LINE__ ) );

	}

	private function GetRenderedAnimation( $source ) {
		error_log( sprintf( "%s: Executing for: %s", __METHOD__, $source ) );
		global $config;

		$curl_obj = curl_init( $config['renderd']['url'] );

		if( ! $curl_obj )
			return false;

		$post_fields = array(
				'sequence' => $source
		);

		curl_setopt( $curl_obj, CURLOPT_POST, 1);
		curl_setopt( $curl_obj, CURLOPT_POSTFIELDS, sprintf( 'sequence=%s', $source ) );
		curl_setopt( $curl_obj, CURLOPT_RETURNTRANSFER, true );

		$response = curl_exec( $curl_obj );
		curl_close( $curl_obj );

		if( $response === FALSE ){
			error_log( curl_error( $curl_obj ) );
			return false;
		}

		error_log( sprintf( "%s: Received: %s", __METHOD__, $response ) );

		$responseData = json_decode($response, TRUE);

		error_log( sprintf( "%s: Received: %s", __METHOD__, print_r( $responseData, 1 ) ) );

		if( $responseData && is_array( $responseData ) && isset( $responseData['sequence'] ) && isset( $responseData['result'] ) && $responseData['result'] == "OK" ) {
			return $responseData['sequence'];
		} else {
			return false;
		}
	}

	public function GetEvent() {
		error_log( sprintf( "%s: Checking...", __METHOD__ ) );
		// Simple query
		$query = "SELECT id, type, options FROM events WHERE now() BETWEEN start AND end AND active = 1 ORDER BY start ASC";

		// Do query
		$res = $this->dbconn->query( $query );

		// If we have a valid result, return it.
		if( $res && $res->rowCount() == 1 ) {
			return $res->fetch();
		} else {
			return false;
		}
	}

	public function GetSchedule() {
		error_log( sprintf( "%s: Checking...", __METHOD__ ) );
		$query = strftime( "SELECT * FROM schedule WHERE day = %u AND '%T' BETWEEN TIMESTAMP( start ) AND TIMESTAMP( end ) ORDER BY day ASC, start ASC, end ASC LIMIT 1" );

		// Do query
		$res = $this->dbconn->query( $query );

		// If we have a valid result, return it.
		if( $res && $res->rowCount() == 1 ) {
			return $res->fetch();
		} else {
			return false;
		}
	}

	public function GetScheduledShow() {
// 		$cro->setRenderProperty( 'hasNewShow', false );
		$scheduler = $this->GetSchedulerInstance();
		return $scheduler->GetNextScheduleAnimation();
	}

	public function SetAnimationPlayed( ColoreRequestHelper &$cro ) {
		$animation_id = $cro->getRequestProperty( 'animation_id' );
		if( ! $animation_id || ! is_numeric( $animation_id ) )
			return;

		// Make query
		$query = array(
				'action' => 'update',
				'table' => 'animations',
				'fields' => array(
						'state' => 1,
				),
				'criteria' => array(
						'id' => $animation_id
				),
		);

		// Do query
		$res = $this->dbconn->mappedQuery( $query );

		// Make query
		$query = array(
				'action' => 'update',
				'table' => 'controllers',
				'fields' => array(
						'last_animation' => $animation_id,
				),
				'criteria' => array(
						'id' => $cro->controller_info,
				),
		);

		// Do query
		$res = $this->dbconn->mappedQuery( $query );
	}

}

?>


text:
<lex-comments-view id="lexAppCommentView" class="animate-switch" entry-config="config.entry" entry="currentEntry"
                   control="control"></lex-comments-view>


text:
package org.apache.pulsar.functions.api.examples;

import org.apache.pulsar.functions.api.Context;
import org.apache.pulsar.functions.api.Function;

import java.util.Arrays;

/**
 * The classic word count example done using pulsar functions
 * Each input message is a sentence that split into words and each word counted.
 * The built in counter state is used to keep track of the word count in a
 * persistent and consistent manner.
 */
public class WordCountFunction implements Function<String, Void> {
    @Override
    public Void process(String input, Context context) throws Exception {
        Arrays.asList(input.split("\\.")).forEach(word -> context.incrCounter(word, 1));
        return null;
    }
}


text:
module Paypal
  module Payment
    class Response::Reference < Base
      attr_required :identifier
      attr_optional :description, :status
      attr_accessor :info
    end
  end
end


text:
let React = require('react');
// let PropTypes = require('prop-types');
let SearchPhoto = require('./toolbar/search');

class Toolbar extends React.Component {
    render() {
        return (
            <div className="header">
                <SearchPhoto />
            </div>
        )
    }
}

// Toolbar.propTypes = {
//     prop: PropTypes.array.isRequired
// };

module.exports = Toolbar;


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-list/iron-list.html">
<dom-module id="ys-results-list">
    <template>
        <iron-list id="ironList" items="{{ list }}" as="item">
            <template>
                <paper-card heading="{{ item.hotel_name }}" image="{{ item.coverImage }}">

{{ item.score }}

 {{ item.stars }} Stars, {{ item.avgRate }} avg/price

 {{ item.address }}

 Pay now: {{ item.pre_paid }} , Cardless: {{ item.is_cardless }}

                </paper-card>
            </template>
        </iron-list>
    </template>

</dom-module>


text:
// This file *must* remain with absolutely no run-time dependency.

#include <urbi/urbi-root.hh>

#include <libport/config.h>

int main(int argc, char* argv[])
{
  UrbiRoot urbi_root(argv[0],
#ifdef STATIC_BUILD
                     true
#else
                     false
#endif
                     );
  return urbi_root.urbi_launch(argc, argv);
}


text:
package com.simplesteph.kafka.Validators;

import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigException;

public class BatchSizeValidator implements ConfigDef.Validator {

    @Override
    public void ensureValid(String name, Object value) {
        Integer batchSize = (Integer) value;
        if (!(1 <= batchSize && batchSize <= 100)){
            throw new ConfigException(name, value, "Batch Size must be a positive integer that's less or equal to 100");
        }
    }
}


text:
<?php

error_reporting(E_STRICT | E_ALL);

// You can set the include path to src directory or reference
// DfpUser.php directly via require_once.
// $path = '/path/to/dfp_api_php_lib/src';
$path = dirname(__FILE__) . '/../../../../src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';
require_once 'Google/Api/Ads/Common/Util/MapUtils.php';

try {
  // Get DfpUser from credentials in "../auth.ini"
  // relative to the DfpUser.php file's directory.
  $user = new DfpUser();

  // Log SOAP XML request and response.
  $user->LogDefaults();

  // Get the TeamService.
  $teamService = $user->GetService('TeamService', 'v201208');

  // Create a statement to order teams by name.
  $filterStatementText = 'ORDER BY name LIMIT 500';
  $filterStatement = new Statement($filterStatementText);

  // Get teams by statement.
  $page = $teamService->getTeamsByStatement($filterStatement);

  // Display results.
  if (isset($page->results)) {
    $i = $page->startIndex;
    foreach ($page->results as $team) {
      print $i . ') Team with ID "' . $team->id
          . '" and name "' . $team->name
          . "\" was found.\n";
       $i++;
    }
  }

  print 'Number of results found: ' . $page->totalResultSetSize . "\n";
} catch (OAuth2Exception $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
  print $e->getMessage() . "\n";
}


text:
@interface UITableViewCell (AFUtilities)

+ (instancetype)af_cellForTableView:(UITableView *)tableView withStyle:(UITableViewCellStyle)style;
+ (instancetype)af_cellForTableView:(UITableView *)tableView;
+ (instancetype)af_staticCellWithStyle:(UITableViewCellStyle)style;
+ (instancetype)af_staticCell;

@end


text:
<?php
class ecrPhpdocIgnore
{

  protected $file;

  public function __construct($file)
  {
    $this->file = $file;
    //TODO exception si fichier non trouvé
  }

  public function getIgnoredLines()
  {
    $tokens = token_get_all(file_get_contents($this->file));
    $usedTokens = array();
    foreach ($tokens as $token)
    {
      if ($token[0] == T_FUNCTION || $token[0] == T_DOC_COMMENT)
      {
        $usedTokens[] = $token;
      }
    }
    $usedTokens[] = array(null, null, count(file($this->file)));
    $ignoredLines = array();
    $nextFunctionWillBeIgnored = false;
    $isCurrentFunctionIgnored   = false;
    $startLine = null;
    foreach ($usedTokens as $token)
    {
      if ($isCurrentFunctionIgnored)
      {
        $endLine = $token[2];
        if ($token[0] == T_FUNCTION || $token[0] == T_DOC_COMMENT)
        {
          $endLine--;
        }
        $ignoredLines = array_merge($ignoredLines, range($startLine, $endLine));
        $nextFunctionWillBeIgnored = false;
        $isCurrentFunctionIgnored  = false;
        $startLine                 = null;
      }

      if ($token[0] == T_DOC_COMMENT && strpos($token[1], '@codeCoverageIgnore'))
      {
        $nextFunctionWillBeIgnored = true;
      }
      elseif ($token[0] == T_FUNCTION && $nextFunctionWillBeIgnored && null === $startLine)
      {
        $isCurrentFunctionIgnored = true;
        $startLine = $token[2];
      }
          }
    return $ignoredLines;
  }

}


text:
let mongoose = require('mongoose')
let Animal = require('../models/animal')
let connection = 'mongodb://localhost:27017/animal'
let User = require('../models/user')
mongoose.Promise = global.Promise
mongoose.connect(connection)

Animal.findById('5821d9f8bd572435e8c5b0d4')
  .then(animal => {
    User.findByIdAndUpdate(animal.addedBy, {'$pull': {'animals': {'_id': '5821d9f8bd572435e8c5b0d4'}}})
  })


text:
import uuid
from mock import Mock
from synapse.types import RoomID, UserID

from tests import unittest
from twisted.internet import defer
from tests.storage.event_injector import EventInjector

from tests.utils import setup_test_homeserver

class EventsStoreTestCase(unittest.TestCase):

    @defer.inlineCallbacks
    def setUp(self):
        self.hs = yield setup_test_homeserver(
            resource_for_federation=Mock(),
            http_client=None,
        )
        self.store = self.hs.get_datastore()
        self.db_pool = self.hs.get_db_pool()
        self.message_handler = self.hs.get_handlers().message_handler
        self.event_injector = EventInjector(self.hs)

    @defer.inlineCallbacks
    def test_count_daily_messages(self):
        self.db_pool.runQuery("DELETE FROM stats_reporting")

        self.hs.clock.now = 100

        # Never reported before, and nothing which could be reported
        count = yield self.store.count_daily_messages()
        self.assertIsNone(count)
        count = yield self.db_pool.runQuery("SELECT COUNT(*) FROM stats_reporting")
        self.assertEqual([(0,)], count)

        # Create something to report
        room = RoomID.from_string("!abc123:test")
        user = UserID.from_string("@raccoonlover:test")
        yield self.event_injector.create_room(room)

        self.base_event = yield self._get_last_stream_token()

        yield self.event_injector.inject_message(room, user, "Raccoons are really cute")

        # Never reported before, something could be reported, but isn't because
        # it isn't old enough.
        count = yield self.store.count_daily_messages()
        self.assertIsNone(count)
        self._assert_stats_reporting(1, self.hs.clock.now)

        # Already reported yesterday, two new events from today.
        yield self.event_injector.inject_message(room, user, "Yeah they are!")
        yield self.event_injector.inject_message(room, user, "Incredibly!")
        self.hs.clock.now += 60 * 60 * 24
        count = yield self.store.count_daily_messages()
        self.assertEqual(2, count)  # 2 since yesterday
        self._assert_stats_reporting(3, self.hs.clock.now)  # 3 ever

        # Last reported too recently.
        yield self.event_injector.inject_message(room, user, "Who could disagree?")
        self.hs.clock.now += 60 * 60 * 22
        count = yield self.store.count_daily_messages()
        self.assertIsNone(count)
        self._assert_stats_reporting(4, self.hs.clock.now)

        # Last reported too long ago
        yield self.event_injector.inject_message(room, user, "No one.")
        self.hs.clock.now += 60 * 60 * 26
        count = yield self.store.count_daily_messages()
        self.assertIsNone(count)
        self._assert_stats_reporting(5, self.hs.clock.now)

        # And now let's actually report something
        yield self.event_injector.inject_message(room, user, "Indeed.")
        yield self.event_injector.inject_message(room, user, "Indeed.")
        yield self.event_injector.inject_message(room, user, "Indeed.")
        # A little over 24 hours is fine :)
        self.hs.clock.now += (60 * 60 * 24) + 50
        count = yield self.store.count_daily_messages()
        self.assertEqual(3, count)
        self._assert_stats_reporting(8, self.hs.clock.now)

    @defer.inlineCallbacks
    def _get_last_stream_token(self):
        rows = yield self.db_pool.runQuery(
            "SELECT stream_ordering"
            " FROM events"
            " ORDER BY stream_ordering DESC"
            " LIMIT 1"
        )
        if not rows:
            defer.returnValue(0)
        else:
            defer.returnValue(rows[0][0])

    @defer.inlineCallbacks
    def _assert_stats_reporting(self, messages, time):
        rows = yield self.db_pool.runQuery(
            "SELECT reported_stream_token, reported_time FROM stats_reporting"
        )
        self.assertEqual([(self.base_event + messages, time,)], rows)


text:
package statistics

import (
	"sync/atomic"

	"github.com/nuclio/nuclio/pkg/processor/trigger"

	"github.com/nuclio/errors"
	"github.com/nuclio/logger"
	"github.com/prometheus/client_golang/prometheus"
)

type triggerGatherer struct {
	trigger            trigger.Trigger
	handledEventsTotal *prometheus.CounterVec
	prevStatistics     trigger.Statistics
	logger             logger.Logger
}

func newTriggerGatherer(instanceName string,
	logger logger.Logger,
	trigger trigger.Trigger,
	metricRegistry *prometheus.Registry) (*triggerGatherer, error) {

	newTriggerGatherer := &triggerGatherer{
		trigger: trigger,
		logger:  logger.GetChild("gatherer"),
	}

	// base labels for handle events
	labels := prometheus.Labels{
		"instance":      instanceName,
		"trigger_class": trigger.GetClass(),
		"trigger_kind":  trigger.GetKind(),
		"trigger_id":    trigger.GetID(),
		"function":      trigger.GetFunctionName(),
		"project":       trigger.GetProjectName(),
		"namespace":     trigger.GetNamespace(),
	}

	newTriggerGatherer.handledEventsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
		Name:        "nuclio_processor_handled_events_total",
		Help:        "Total number of handled events",
		ConstLabels: labels,
	}, []string{"result"})

	if err := metricRegistry.Register(newTriggerGatherer.handledEventsTotal); err != nil {
		return nil, errors.Wrap(err, "Failed to register handled events metric")
	}

	return newTriggerGatherer, nil
}

func (esg *triggerGatherer) Gather() error {

	// read current stats
	currentStatistics := *esg.trigger.GetStatistics()

	// diff from previous to get this period
	diffStatistics := currentStatistics.DiffFrom(&esg.prevStatistics)

	eventsHandledSuccessTotal := atomic.LoadUint64(&diffStatistics.EventsHandledSuccessTotal)
	eventsHandledFailureTotal := atomic.LoadUint64(&diffStatistics.EventsHandledFailureTotal)

	esg.handledEventsTotal.With(prometheus.Labels{
		"result": "success",
	}).Add(float64(eventsHandledSuccessTotal))

	esg.handledEventsTotal.With(prometheus.Labels{
		"result": "failure",
	}).Add(float64(eventsHandledFailureTotal))

	esg.prevStatistics = currentStatistics

	return nil
}


text:
package org.apache.sqoop.repository;

import org.apache.sqoop.core.ConfigurationConstants;

public final class RepoConfigurationConstants {

  /**
   * All repository related configuration is prefixed with this:
   * <tt>org.apache.sqoop.repository.</tt>
   */
  public static final String PREFIX_REPO_CONFIG =
      ConfigurationConstants.PREFIX_GLOBAL_CONFIG + "repository.";

  /**
   * System properties set up by the Repository Manager before initializing
   * the provider.
   */
  public static final String SYSCFG_REPO_SYSPROP_PREFIX = PREFIX_REPO_CONFIG
      + "sysprop.";

  /**
   * Class name of the repository implementation specified by:
   * <tt>org.apache.sqoop.repository.provider</tt>
   */
  public static final String SYSCFG_REPO_PROVIDER = PREFIX_REPO_CONFIG
      + "provider";

  /**
   * Boolean property defining whether repository is allowed to make changes
   * on disk structures (schema in databases, changing file format, ...).
   */
  public static final String SYSCFG_REPO_SCHEMA_IMMUTABLE=
    PREFIX_REPO_CONFIG + "schema.immutable";

  /**
   * Class name for the JDBC repository handler specified by:
   * <tt>org.apache.sqoop.repository.jdbc.handler</tt>.
   */
  public static final String SYSCFG_REPO_JDBC_HANDLER = PREFIX_REPO_CONFIG
      + "jdbc.handler";

  /**
   * JDBC connection URL specified by:
   * <tt>org.apache.sqoop.repository.jdbc.url</tt>
   */
  public static final String SYSCFG_REPO_JDBC_URL = PREFIX_REPO_CONFIG
      + "jdbc.url";

  /**
   * JDBC driver to be used, specified by:
   * <tt>org.apache.sqoop.repository.jdbc.driver</tt>
   */
  public static final String SYSCFG_REPO_JDBC_DRIVER = PREFIX_REPO_CONFIG
      + "jdbc.driver";

  /**
   * JDBC connection user name, specified by:
   * <tt>org.apache.sqoop.repository.jdbc.user</tt>
   */
  public static final String SYSCFG_REPO_JDBC_USER = PREFIX_REPO_CONFIG
      + "jdbc.user";

  /**
   * JDBC connection password, specified by:
   * <tt>org.apache.sqoop.repository.jdbc.password</tt>
   */
  public static final String SYSCFG_REPO_JDBC_PASSWORD = PREFIX_REPO_CONFIG
      + "jdbc.password";

  /**
   * JDBC Transaction Isolation, specified by:
   * <tt>org.apache.sqoop.repository.jdbc.transaction.isolation</tt>. The valid
   * values include: <tt>READ_UNCOMMITTED</tt>, <tt>READ_COMMITTED</tt>,
   * <tt>REPEATABLE_READ</tt> and <tt>SERIALIZABLE</tt>.
   */
  public static final String SYSCFG_REPO_JDBC_TX_ISOLATION = PREFIX_REPO_CONFIG
      + "jdbc.transaction.isolation";

  /**
   * JDBC connection pool maximum connections, specified by:
   * <tt>org.apache.sqoop.repository.jdbc.maximum.connections</tt>
   */
  public static final String SYSCFG_REPO_JDBC_MAX_CONN = PREFIX_REPO_CONFIG
      + "jdbc.maximum.connections";

  /**
   * Prefix that is used to provide any JDBC specific properties for the
   * system. Configuration keys which start with this prefix will be stripped
   * of the prefix and used as regular properties for JDBC connection
   * initialization. The prefix value is
   * <tt>org.apache.sqoop.repository.jdbc.properties.</tt> A property such as
   * <tt>foo</tt> with value <tt>bar</tt> will be set as:
   * <tt>org.apache.sqoop.repository.jdbc.properties.foo = bar </tt>
   */
  public static final String PREFIX_SYSCFG_REPO_JDBC_PROPERTIES =
      PREFIX_REPO_CONFIG + "jdbc.properties.";

  private RepoConfigurationConstants() {
    // Disable explicit object creation
  }
}


text:
#region

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AgilefantTimes.API.Agilefant.Common;
using Newtonsoft.Json;
// ReSharper disable ClassNeverInstantiated.Global
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global

#endregion

namespace AgilefantTimes.API.Agilefant
{
    public class AgilefantSprintSummary : AgilefantBase
    {
        [JsonProperty("backlogSize")]
        public int? BacklogSize { get; private set; }

        [JsonProperty("baselineLoad")]
        public object BaselineLoad { get; private set; }

        [JsonProperty("description")]
        public string Description { get; private set; }

        [JsonProperty("endDate")]
        protected long EndDateLong { get; private set; }

        public DateTime EndDate => new DateTime(1970, 1, 1).AddMilliseconds(EndDateLong);

        [JsonProperty("name")]
        public string Name { get; private set; }

        [JsonProperty("product")]
        public bool Product { get; private set; }

        [JsonProperty("readonlyToken")]
        public object ReadonlyToken { get; private set; }

        [JsonProperty("root")]
        public AgilefantBacklogProductSummary ProductSummary { get; private set; }

        [JsonProperty("standAlone")]
        public bool StandAlone { get; private set; }

        [JsonProperty("startDate")]
        protected long StartDateLong { get; private set; }

        public DateTime StartDate => new DateTime(1970, 1, 1).AddMilliseconds(StartDateLong);

        /// <summary>
        /// Gets an array of sprints available
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="backlogId">The backlog to get sprints for.</param>
        /// <returns>The sprint</returns>
        internal static async Task<AgilefantSprintSummary[]> GetSprints(int backlogId, AgilefantSession session)
        {
            var response = await session.Post("ajax/retrieveSubBacklogs.action", new FormUrlEncodedContent(new Dictionary<string, string>
            {
                {"backlogId", backlogId.ToString()}
            }));
            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<AgilefantSprintSummary[]>(json);
        }
    }
}


text:
 (function(){

var myComponentData = org_scn_community_require.knownComponents.basics.RSSFeedReader;

RSSFeedReader = function () {

	var that = this;

	that.init = function() {
		// define root component
		org_scn_community_basics.fillDummyDataInit(that, that.initAsync);
	};

	that.initAsync = function (owner) {
		var that = owner;
		org_scn_community_component_Core(that, myComponentData);

		/* COMPONENT SPECIFIC CODE - START(initDesignStudio)*/
		// this.addStyleClass("scn-pack-?");

		/* COMPONENT SPECIFIC CODE - END(initDesignStudio)*/
	};

	that.afterUpdate = function() {
		/* COMPONENT SPECIFIC CODE - START(afterDesignStudioUpdate)*/

		// org_scn_community_basics.resizeContentAbsoluteLayout(that, that._oRoot, that.onResize);

		org_scn_community_basics.fillDummyData(that, that.processData, that.afterPrepare);
	};

	/* COMPONENT SPECIFIC CODE - START METHODS*/

	that.processData = function (flatData, afterPrepare, owner) {
		var that = owner;

		if(flatData != undefined) {
			that._flatData = flatData;
		}

		that.rss_container = 'RSSContainerForIFrame.html?rnd=' + Math.random() + "&";	// Cache-busting

		// processing on data
		that.afterPrepare(that);
	};

	that.afterPrepare = function (owner) {
		var that = owner;

		var xslFile = that.getXslUrl();
		var useBuildIn = that.getUseBuildInXsl();

		var xslLocation = "";

		if(useBuildIn) {
			xslLocation = org_scn_community_basics.getRepositoryImageUrlPrefix(that, xslFile, "", "rss.xsl");
			// need to make the "upper-folder" logic to match the call from the inner HTML iframe
			xslLocation = "../../../../../../" + xslLocation;
		} else {
			xslLocation = org_scn_community_basics.getRepositoryImageUrlPrefix(that, xslFile, xslFile, "rss.xsl");
		}

		var containerUrl = org_scn_community_basics.getRepositoryImageUrlPrefix (that, "", "", that.rss_container);

//		var urlEncodedFeed = that.getFeedUrl().replace("&", "%26");
//		urlEncodedFeed = urlEncodedFeed.replace("?", "%3F");
//		urlEncodedFeed = urlEncodedFeed.replace("=", "%3D");

		var urlEncodedFeed = encodeURIComponent(that.getFeedUrl());
		var urlEncodedXsl = encodeURIComponent(xslLocation);

		var url_string = encodeURI(containerUrl)
				+ 'feed=' + urlEncodedFeed +"&"
				+ 'xsl=' + urlEncodedXsl;

		var html = '<iframe src="'+url_string+'" width="auto" height="auto"></iframe>';

		this.$().html(html);
	};

	that.onResize = function (width, height, parent) {
		// in case special resize code is required
	};

	/* COMPONENT SPECIFIC CODE - END METHODS*/
	return that;
};

define([myComponentData.requireName], function(basicsrssfeedreader){
	myComponentData.instance = RSSFeedReader;
	return myComponentData.instance;
});

}).call(this);


text:
package com.flipkart.fdp.migration.db.models;

import static com.flipkart.fdp.migration.db.utils.DBUtils.COL_BATCH_CONFIG;
import static com.flipkart.fdp.migration.db.utils.DBUtils.COL_JOB_ID;
import static com.flipkart.fdp.migration.db.utils.DBUtils.COL_STATUS;
import static com.flipkart.fdp.migration.db.utils.DBUtils.TAB_BATCH_RUNS;
import static javax.persistence.EnumType.STRING;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import lombok.Getter;

import com.flipkart.fdp.migration.db.utils.DBUtils;

@Entity
@Table(name = TAB_BATCH_RUNS)
@Getter
public class BatchRun implements Serializable {

	private static final long serialVersionUID = 4361283698132475133L;

	@Id
	@NotNull
	@Column(name = COL_JOB_ID, updatable = false, nullable = false)
	private String jobId;

	@Column(name = DBUtils.COL_START_TIME, nullable = false)
	private long startTime;

	@Column(name = DBUtils.COL_END_TIME, nullable = false)
	private long endTime;

	@Column(name = DBUtils.COL_BATCH_ID, nullable = false)
	private long batchId;

	@Column(name = COL_BATCH_CONFIG, nullable = false, length = 4096)
	private String batchConfig;

	@Column(name = COL_STATUS)
	@Enumerated(STRING)
	private Status status;

	public BatchRun() {

	}

	public BatchRun(String jobId, long startTime, long endTime, long batchId,
			String batchConfig, Status status) {
		this.jobId = jobId;
		this.startTime = startTime;
		this.endTime = endTime;
		this.batchId = batchId;
		this.batchConfig = batchConfig;
		this.status = status;
	}

}


text:
<resources>
    <string name="app_name">SimpleStore</string>
</resources>


text:
package org.jboss.resteasy.reactive.common.jaxrs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Variant;

/**
 * @author Bill Burke
 */
public class VariantListBuilderImpl extends Variant.VariantListBuilder {
    private final ArrayList<Variant> variants = new ArrayList<Variant>();
    private final ArrayList<Locale> currentLanguages = new ArrayList<Locale>();
    private final ArrayList<String> currentEncodings = new ArrayList<String>();
    private final ArrayList<MediaType> currentTypes = new ArrayList<MediaType>();

    public List<Variant> build() {
        add();
        ArrayList<Variant> copy = new ArrayList<Variant>(variants);
        variants.clear();
        currentLanguages.clear();
        currentEncodings.clear();
        currentTypes.clear();
        return copy;
    }

    public Variant.VariantListBuilder add() {
        int langSize = currentLanguages.size();
        int encodingSize = currentEncodings.size();
        int typeSize = currentTypes.size();

        int i = 0;

        if (langSize == 0 && encodingSize == 0 && typeSize == 0)
            return this;

        do {
            MediaType type = null;
            if (i < typeSize)
                type = currentTypes.get(i);
            int j = 0;
            do {
                String encoding = null;
                if (j < encodingSize)
                    encoding = currentEncodings.get(j);
                int k = 0;
                do {
                    Locale language = null;
                    if (k < langSize)
                        language = currentLanguages.get(k);
                    variants.add(new Variant(type, language, encoding));
                    k++;
                } while (k < langSize);
                j++;
            } while (j < encodingSize);
            i++;
        } while (i < typeSize);

        currentLanguages.clear();
        currentEncodings.clear();
        currentTypes.clear();

        return this;
    }

    public Variant.VariantListBuilder languages(Locale... languages) {
        currentLanguages.addAll(Arrays.asList(languages));
        return this;
    }

    @Override
    public Variant.VariantListBuilder encodings(String... encodings) {
        currentEncodings.addAll(Arrays.asList(encodings));
        return this;
    }

    @Override
    public Variant.VariantListBuilder mediaTypes(MediaType... mediaTypes) {
        currentTypes.addAll(Arrays.asList(mediaTypes));
        return this;
    }
}


text:
package gwt.material.design.client.base;

public interface HasDataAttributes {
    /**
     * Set data attribute of an {@link com.google.gwt.dom.client.Element}.
     * E.g. data-position="left".
     */
    void setDataAttribute(String dataAttr, String value);

    /**
     * Get a data attribute of the {@link com.google.gwt.dom.client.Element}.
     */
    String getDataAttribute(String dataAttr);
}


text:
<?php
	// This is used to connect to database. Required anytime we wish to use database.
	$dbhost = 'localhost';
	$dbuser = '***';
	$dbpass = '***';
	$dbname = '***';
	require_once( 'DB.php' );

	$db = DB::connect( "mysql://$dbuser:$dbpass@$dbhost/$dbname" );

	$db->setFetchMode(DB_FETCHMODE_ASSOC);
?>


text:
<?php
/* ====================
[BEGIN_COT_EXT]
Code=boxes
Hooks=header.tags
Tags=header.tpl:{HEADER_BOXES_HEADMETA},{HEADER_BOXES_SPEEDUP},{HEADER_BOXES_CSS},{HEADER_BOXES_EXTERNAL_JSCSS}
Order=10
[END_COT_EXT]
==================== */
/**
 * boxes plugin
 *
 * @author Roffun
 * @copyright Copyright (C) 2015 - today: Roffun | https://github.com/Roffun
 * @license BSD
 */

defined('COT_CODE') or die('Wrong URL.');

$shortpath = $cfg['plugin']['boxes'];
$boxes_theme_css_path = $cfg['mainurl'] . '/' . $cfg['themes_dir'] . '/' . $theme . '/css/';

if (!empty($shortpath['box_speedup']))
{
     foreach (preg_split('#([\n\r]+)#Usi', $shortpath['box_speedup']) as $bspdup)
     {
          $box_speedup .= @file_get_contents($boxes_theme_css_path . $bspdup);
          $box_speedupmin = '<style>' . cot_rc_minify($box_speedup, 'css') . '</style>';
     }
}
else
{
     $box_speedupmin = false;
}

if (!empty($shortpath['box_headcss']))
{
     $box_headcss = '<style>' . cot_rc_minify($shortpath['box_headcss'], 'css') . '</style>';
}

$t->assign(array(
     'HEADER_BOXES_HEADMETA' => $shortpath['box_headmeta'],
     'HEADER_BOXES_SPEEDUP' => $box_speedupmin,
     'HEADER_BOXES_CSS' => $box_headcss,
     'HEADER_BOXES_EXTERNAL_JSCSS' => $shortpath['box_head_externaljscss']));