text:
package org.metaborg.meta.lang.dynsem.interpreter.nodes.natives;

import org.metaborg.meta.lang.dynsem.interpreter.DynSemLanguage;
import org.metaborg.meta.lang.dynsem.interpreter.nodes.matching.MatchPattern;
import org.metaborg.meta.lang.dynsem.interpreter.nodes.rules.RuleResult;
import org.metaborg.meta.lang.dynsem.interpreter.nodes.rules.premises.Premise;
import org.metaborg.meta.lang.dynsem.interpreter.utils.InterpreterUtils;
import org.metaborg.meta.lang.dynsem.interpreter.utils.SourceUtils;
import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoList;

import com.oracle.truffle.api.CompilerAsserts;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import com.oracle.truffle.api.source.SourceSection;

public abstract class NativeCallPremise extends Premise {
	@Child private NativeExecutableNode execNode;

	@Child private MatchPattern rhsNode;

	@Children private final MatchPattern[] rhsRwNodes;

	public NativeCallPremise(SourceSection source, NativeExecutableNode execNode, MatchPattern rhsNode,
			MatchPattern[] rhsComponentNodes) {
		super(source);
		this.execNode = execNode;
		this.rhsNode = rhsNode;
		this.rhsRwNodes = rhsComponentNodes;
	}

	@Specialization
	@ExplodeLoop
	public void doExecute(VirtualFrame frame) {
		final RuleResult res = execNode.execute(frame);

		rhsNode.executeMatch(frame, res.result);

		// evaluate the RHS component pattern matches
		final Object[] components = res.components;
		CompilerAsserts.compilationConstant(rhsRwNodes.length);
		for (int i = 0; i < rhsRwNodes.length; i++) {
			rhsRwNodes[i].executeMatch(frame, InterpreterUtils.getComponent(getContext(), components, i, this));
		}
	}

	public static NativeCallPremise create(DynSemLanguage lang, IStrategoAppl t, FrameDescriptor ruleFD) {
		CompilerAsserts.neverPartOfCompilation();
		// NativeRelationPremise: NativeRule * Term * List(Term) -> Relation
		assert Tools.hasConstructor(t, "NativeRelationPremise", 3);
		NativeExecutableNode ruleNode = NativeExecutableNode.create(lang, Tools.applAt(t, 0), ruleFD);
		MatchPattern rhsNode = MatchPattern.create(Tools.applAt(t, 1), ruleFD);

		IStrategoList rhsRwsT = Tools.listAt(t, 2);
		MatchPattern[] rhsRwNodes = new MatchPattern[rhsRwsT.size()];
		for (int i = 0; i < rhsRwNodes.length; i++) {
			rhsRwNodes[i] = MatchPattern.create(Tools.applAt(rhsRwsT, i), ruleFD);
		}

		return NativeCallPremiseNodeGen.create(SourceUtils.dynsemSourceSectionFromATerm(t), ruleNode, rhsNode,
				rhsRwNodes);
	}

}


text:
<?php

namespace Kunstmaan\TaggingBundle\Tests\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Kunstmaan\TaggingBundle\Entity\Taggable;
use Kunstmaan\TaggingBundle\Entity\TaggableTrait;
use PHPUnit\Framework\TestCase;

class Random implements Taggable
{
    use TaggableTrait;

    /**
     * @Id
     * @GeneratedValue
     * @Column(type="integer")
     */
    public $id;

    /**
     * @Column(name="title", type="string", length=50)
     */
    public $title;

    public function getId()
    {
        return 5;
    }
}

/**
 * Class TaggableTraitTest
 */
class TaggableTraitTest extends TestCase
{
    public function testGetters()
    {
        $object = new Random();

        $object->setTags(new ArrayCollection());
        $object->setTagLoader(function () {
            return new ArrayCollection();
        });

        $this->assertInstanceOf(ArrayCollection::class, $object->getTags());
        $this->assertEquals(Random::class, $object->getTaggableType());
        $this->assertEquals(5, $object->getTaggableId());
    }

    public function testTagsByClosureLoader()
    {
        $object = new Random();
        $object->setTagLoader(function () {
            return new ArrayCollection();
        });
        $this->assertInstanceOf(ArrayCollection::class, $object->getTags());
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Plugins\API;

use Piwik\API\Proxy;
use Piwik\API\Request;
use Piwik\Columns\Dimension;
use Piwik\Config;
use Piwik\Container\StaticContainer;
use Piwik\DataTable;
use Piwik\DataTable\Filter\ColumnDelete;
use Piwik\DataTable\Row;
use Piwik\Date;
use Piwik\IP;
use Piwik\Metrics;
use Piwik\Period;
use Piwik\Period\Range;
use Piwik\Piwik;
use Piwik\Plugin\Dimension\VisitDimension;
use Piwik\Plugins\API\DataTable\MergeDataTables;
use Piwik\Plugins\CoreAdminHome\CustomLogo;
use Piwik\Segment\SegmentExpression;
use Piwik\Translation\Translator;
use Piwik\Version;

require_once PIWIK_INCLUDE_PATH . '/core/Config.php';

/**
 * This API is the Metadata API: it gives information about all other available APIs methods, as well as providing
 * human readable and more complete outputs than normal API methods.
 *
 * Some of the information that is returned by the Metadata API:
 *

 *
the dynamically generated list of all API methods via "getReportMetadata"

 *
the list of metrics that will be returned by each method, along with their human readable name, via "getDefaultMetrics" and "getDefaultProcessedMetrics"

 *
the list of segments metadata supported by all functions that have a 'segment' parameter

 *
the (truly magic) method "getProcessedReport" will return a human readable version of any other report, and include the processed metrics such as
 * conversion rate, time on site, etc. which are not directly available in other methods.

 *
the method "getSuggestedValuesForSegment" returns top suggested values for a particular segment. It uses the Live.getLastVisitsDetails API to fetch the most recently used values, and will return the most often used values first.

 *

 * The Metadata API is for example used by the Piwik Mobile App to automatically display all Piwik reports, with translated report & columns names and nicely formatted values.
 * More information on the Metadata API documentation page
 *
 * @method static \Piwik\Plugins\API\API getInstance()
 */
class API extends \Piwik\Plugin\API
{
    /**
     * Get Piwik version
     * @return string
     */
    public function getPiwikVersion()
    {
        Piwik::checkUserHasSomeViewAccess();
        return Version::VERSION;
    }

    /**
     * Returns the most accurate IP address availble for the current user, in
     * IPv4 format. This could be the proxy client's IP address.
     *
     * @return string IP address in presentation format.
     */
    public function getIpFromHeader()
    {
        Piwik::checkUserHasSomeViewAccess();
        return IP::getIpFromHeader();
    }

    /**
     * Returns the section [APISettings] if defined in config.ini.php
     * @return array
     */
    public function getSettings()
    {
        return Config::getInstance()->APISettings;
    }

    /**
     * Default translations for many core metrics.
     * This is used for exports with translated labels. The exports contain columns that
     * are not visible in the UI and not present in the API meta data. These columns are
     * translated here.
     * @return array
     */
    public static function getDefaultMetricTranslations()
    {
        return Metrics::getDefaultMetricTranslations();
    }

    public function getSegmentsMetadata($idSites = array(), $_hideImplementationData = true)
    {
        $segments = array();

        foreach (Dimension::getAllDimensions() as $dimension) {
            foreach ($dimension->getSegments() as $segment) {
                $segments[] = $segment->toArray();
            }
        }

        /**
         * Triggered when gathering all available segment dimensions.
         *
         * This event can be used to make new segment dimensions available.
         *
         * **Example**
         *
         *     public function getSegmentsMetadata(&$segments, $idSites)
         *     {
         *         $segments[] = array(
         *             'type'           => 'dimension',
         *             'category'       => Piwik::translate('General_Visit'),
         *             'name'           => 'General_VisitorIP',
         *             'segment'        => 'visitIp',
         *             'acceptedValues' => '13.54.122.1, etc.',
         *             'sqlSegment'     => 'log_visit.location_ip',
         *             'sqlFilter'      => array('Piwik\IP', 'P2N'),
         *             'permission'     => $isAuthenticatedWithViewAccess,
         *         );
         *     }
         *
         * @param array &$dimensions The list of available segment dimensions. Append to this list to add
         *                           new segments. Each element in this list must contain the
         *                           following information:
         *
         *                           - **type**: Either `'metric'` or `'dimension'`. `'metric'` means
         *                                       the value is a numeric and `'dimension'` means it is
         *                                       a string. Also, `'metric'` values will be displayed
         *                                       under **Visit (metrics)** in the Segment Editor.
         *                           - **category**: The segment category name. This can be an existing
         *                                           segment category visible in the segment editor.
         *                           - **name**: The pretty name of the segment. Can be a translation token.
         *                           - **segment**: The segment name, eg, `'visitIp'` or `'searches'`.
         *                           - **acceptedValues**: A string describing one or two exacmple values, eg
         *                                                 `'13.54.122.1, etc.'`.
         *                           - **sqlSegment**: The table column this segment will segment by.
         *                                             For example, `'log_visit.location_ip'` for the
         *                                             **visitIp** segment.
         *                           - **sqlFilter**: A PHP callback to apply to segment values before
         *                                            they are used in SQL.
         *                           - **permission**: True if the current user has view access to this
         *                                             segment, false if otherwise.
         * @param array $idSites The list of site IDs we're getting the available segments
         *                       for. Some segments (such as Goal segments) depend on the
         *                       site.
         */
        Piwik::postEvent('API.getSegmentDimensionMetadata', array(&$segments, $idSites));

        $isAuthenticatedWithViewAccess = Piwik::isUserHasViewAccess($idSites) && !Piwik::isUserIsAnonymous();

        $segments[] = array(
            'type'           => 'dimension',
            'category'       => Piwik::translate('General_Visit'),
            'name'           => 'General_UserId',
            'segment'        => 'userId',
            'acceptedValues' => 'any non empty unique string identifying the user (such as an email address or a username).',
            'sqlSegment'     => 'log_visit.user_id',
            'sqlFilter'      => array($this, 'checkSegmentMatchTypeIsValidForUser'),
            'permission'     => $isAuthenticatedWithViewAccess,

            // TODO specify that this segment is not compatible with some operators
//            'unsupportedOperators' = array(MATCH_CONTAINS, MATCH_DOES_NOT_CONTAIN),
        );

        $segments[] = array(
            'type'           => 'dimension',
            'category'       => Piwik::translate('General_Visit'),
            'name'           => 'General_VisitorID',
            'segment'        => 'visitorId',
            'acceptedValues' => '34c31e04394bdc63 - any 16 Hexadecimal chars ID, which can be fetched using the Tracking API function getVisitorId()',
            'sqlSegment'     => 'log_visit.idvisitor',
            'sqlFilterValue' => array('Piwik\Common', 'convertVisitorIdToBin'),
            'permission'     => $isAuthenticatedWithViewAccess,
        );

        $segments[] = array(
            'type'           => 'dimension',
            'category'       => Piwik::translate('General_Visit'),
            'name'           => Piwik::translate('General_Visit') . " ID",
            'segment'        => 'visitId',
            'acceptedValues' => 'Any integer. ',
            'sqlSegment'     => 'log_visit.idvisit',
            'permission'     => $isAuthenticatedWithViewAccess,
        );

        $segments[] = array(
            'type'           => 'metric',
            'category'       => Piwik::translate('General_Visit'),
            'name'           => 'General_VisitorIP',
            'segment'        => 'visitIp',
            'acceptedValues' => '13.54.122.1. Select IP ranges with notation: visitIp>13.54.122.0;visitIp<13.54.122.255',
            'sqlSegment'     => 'log_visit.location_ip',
            'sqlFilterValue' => array('Piwik\Network\IPUtils', 'stringToBinaryIP'),
            'permission'     => $isAuthenticatedWithViewAccess,
        );

        foreach ($segments as &$segment) {
            $segment['name'] = Piwik::translate($segment['name']);
            $segment['category'] = Piwik::translate($segment['category']);

            if ($_hideImplementationData) {
                unset($segment['sqlFilter']);
                unset($segment['sqlFilterValue']);
                unset($segment['sqlSegment']);
            }
        }

        usort($segments, array($this, 'sortSegments'));
        return $segments;
    }

    private function sortSegments($row1, $row2)
    {
        $customVarCategory = Piwik::translate('CustomVariables_CustomVariables');

        $columns = array('type', 'category', 'name', 'segment');
        foreach ($columns as $column) {
            // Keep segments ordered alphabetically inside categories..
            $type = -1;
            if ($column == 'name') $type = 1;

            $compare = $type * strcmp($row1[$column], $row2[$column]);

            // hack so that custom variables "page" are grouped together in the doc
            if ($row1['category'] == $customVarCategory
                && $row1['category'] == $row2['category']
            ) {
                $compare = strcmp($row1['segment'], $row2['segment']);
                return $compare;
            }
            if ($compare != 0) {
                return $compare;
            }
        }
        return $compare;
    }

    /**
     * Throw an exception if the User ID segment is used with an un-supported match type,
     *
     * @ignore
     * @param $value
     * @param $sqlSegment
     * @param $matchType
     * @param $name
     * @return $value
     * @throws \Exception
     */
    public function checkSegmentMatchTypeIsValidForUser($value, $sqlSegment, $matchType, $name)
    {
        $acceptedMatches = array(
            SegmentExpression::MATCH_EQUAL,
            SegmentExpression::MATCH_IS_NOT_NULL_NOR_EMPTY,
            SegmentExpression::MATCH_IS_NULL_OR_EMPTY,
            SegmentExpression::MATCH_NOT_EQUAL,
        );
        if (in_array($matchType, $acceptedMatches)) {
            return $value;
        }
        $message = "Invalid Segment match type: try using 'userId' segment with one of the following match types: %s.";
        throw new \Exception(sprintf($message, implode(", ", $acceptedMatches)));
    }

    /**
     * Returns the url to application logo (~280x110px)
     *
     * @param bool $pathOnly If true, returns path relative to doc root. Otherwise, returns a URL.
     * @return string
     */
    public function getLogoUrl($pathOnly = false)
    {
        $logo = new CustomLogo();
        return $logo->getLogoUrl($pathOnly);
    }

    /**
     * Returns the url to header logo (~127x50px)
     *
     * @param bool $pathOnly If true, returns path relative to doc root. Otherwise, returns a URL.
     * @return string
     */
    public function getHeaderLogoUrl($pathOnly = false)
    {
        $logo = new CustomLogo();
        return $logo->getHeaderLogoUrl($pathOnly);
    }

    /**
     * Returns the URL to application SVG Logo
     *
     * @ignore
     * @param bool $pathOnly If true, returns path relative to doc root. Otherwise, returns a URL.
     * @return string
     */
    public function getSVGLogoUrl($pathOnly = false)
    {
        $logo = new CustomLogo();
        return $logo->getSVGLogoUrl($pathOnly);
    }

    /**
     * Returns whether there is an SVG Logo available.
     * @ignore
     * @return bool
     */
    public function hasSVGLogo()
    {
        $logo = new CustomLogo();
        return $logo->hasSVGLogo();
    }

    /**
     * Loads reports metadata, then return the requested one,
     * matching optional API parameters.
     */
    public function getMetadata($idSite, $apiModule, $apiAction, $apiParameters = array(), $language = false,
                                $period = false, $date = false, $hideMetricsDoc = false, $showSubtableReports = false)
    {
        if ($language) {
            /** @var Translator $translator */
            $translator = StaticContainer::get('Piwik\Translation\Translator');
            $translator->setCurrentLanguage($language);
        }

        $reporter = new ProcessedReport();
        $metadata = $reporter->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language, $period, $date, $hideMetricsDoc, $showSubtableReports);
        return $metadata;
    }

    /**
     * Triggers a hook to ask plugins for available Reports.
     * Returns metadata information about each report (category, name, dimension, metrics, etc.)
     *
     * @param string $idSites Comma separated list of website Ids
     * @param bool|string $period
     * @param bool|Date $date
     * @param bool $hideMetricsDoc
     * @param bool $showSubtableReports
     * @return array
     */
    public function getReportMetadata($idSites = '', $period = false, $date = false, $hideMetricsDoc = false,
                                      $showSubtableReports = false)
    {
        $reporter = new ProcessedReport();
        $metadata = $reporter->getReportMetadata($idSites, $period, $date, $hideMetricsDoc, $showSubtableReports);
        return $metadata;
    }

    public function getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment = false,
                                       $apiParameters = false, $idGoal = false, $language = false,
                                       $showTimer = true, $hideMetricsDoc = false, $idSubtable = false, $showRawMetrics = false)
    {
        $reporter = new ProcessedReport();
        $processed = $reporter->getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment,
            $apiParameters, $idGoal, $language, $showTimer, $hideMetricsDoc, $idSubtable, $showRawMetrics);

        return $processed;
    }

    /**
     * Get a combined report of the *.get API methods.
     */
    public function get($idSite, $period, $date, $segment = false, $columns = false)
    {
        $columns = Piwik::getArrayFromApiParameter($columns);

        // build columns map for faster checks later on
        $columnsMap = array();
        foreach ($columns as $column) {
            $columnsMap[$column] = true;
        }

        // find out which columns belong to which plugin
        $columnsByPlugin = array();
        $meta = \Piwik\Plugins\API\API::getInstance()->getReportMetadata($idSite, $period, $date);
        foreach ($meta as $reportMeta) {
            // scan all *.get reports
            if ($reportMeta['action'] == 'get'
                && !isset($reportMeta['parameters'])
                && $reportMeta['module'] != 'API'
                && !empty($reportMeta['metrics'])
            ) {
                $plugin = $reportMeta['module'];
                $allMetrics = array_merge($reportMeta['metrics'], @$reportMeta['processedMetrics'] ?: array());
                foreach ($allMetrics as $column => $columnTranslation) {
                    // a metric from this report has been requested
                    if (isset($columnsMap[$column])
                        // or by default, return all metrics
                        || empty($columnsMap)
                    ) {
                        $columnsByPlugin[$plugin][] = $column;
                    }
                }
            }
        }
        krsort($columnsByPlugin);

        $mergedDataTable = false;
        $params = compact('idSite', 'period', 'date', 'segment', 'idGoal');
        foreach ($columnsByPlugin as $plugin => $columns) {
            // load the data
            $className = Request::getClassNameAPI($plugin);
            $params['columns'] = implode(',', $columns);
            $dataTable = Proxy::getInstance()->call($className, 'get', $params);

            $dataTable->filter(function (DataTable $table) {
                $table->clearQueuedFilters();
            });

            // merge reports
            if ($mergedDataTable === false) {
                $mergedDataTable = $dataTable;
            } else {
                $merger = new MergeDataTables();
                $merger->mergeDataTables($mergedDataTable, $dataTable);
            }
        }

        if (!empty($columnsMap)
            && !empty($mergedDataTable)
        ) {
            $mergedDataTable->queueFilter('ColumnDelete', array(false, array_keys($columnsMap)));
        }

        return $mergedDataTable;
    }

    /**
     * Given an API report to query (eg. "Referrers.getKeywords", and a Label (eg. "free%20software"),
     * this function will query the API for the previous days/weeks/etc. and will return
     * a ready to use data structure containing the metrics for the requested Label, along with enriched information (min/max values, etc.)
     *
     * @param int $idSite
     * @param string $period
     * @param Date $date
     * @param string $apiModule
     * @param string $apiAction
     * @param bool|string $label
     * @param bool|string $segment
     * @param bool|string $column
     * @param bool|string $language
     * @param bool|int $idGoal
     * @param bool|string $legendAppendMetric
     * @param bool|string $labelUseAbsoluteUrl
     * @return array
     */
    public function getRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $label = false, $segment = false, $column = false, $language = false, $idGoal = false, $legendAppendMetric = true, $labelUseAbsoluteUrl = true)
    {
        $rowEvolution = new RowEvolution();
        return $rowEvolution->getRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $label, $segment, $column,
            $language, $idGoal, $legendAppendMetric, $labelUseAbsoluteUrl);
    }

    public function getLastDate($date, $period)
    {
        $lastDate = Range::getLastDate($date, $period);

        return array_shift($lastDate);
    }

    /**
     * Performs multiple API requests at once and returns every result.
     *
     * @param array $urls The array of API requests.
     * @return array
     */
    public function getBulkRequest($urls)
    {
        if (empty($urls)) {
            return array();
        }

        $urls = array_map('urldecode', $urls);
        $urls = array_map(array('Piwik\Common', 'unsanitizeInputValue'), $urls);

        $result = array();
        foreach ($urls as $url) {
            $req = new Request($url . '&format=php&serialize=0');
            $result[] = $req->process();
        }
        return $result;
    }

    /**
     * Return true if plugin is activated, false otherwise
     *
     * @param string $pluginName
     * @return bool
     */
    public function isPluginActivated($pluginName)
    {
        Piwik::checkUserHasSomeViewAccess();
        return \Piwik\Plugin\Manager::getInstance()->isPluginActivated($pluginName);
    }

    /**
     * Given a segment, will return a list of the most used values for this particular segment.
     * @param $segmentName
     * @param $idSite
     * @throws \Exception
     * @return array
     */
    public function getSuggestedValuesForSegment($segmentName, $idSite)
    {
        if (empty(Config::getInstance()->General['enable_segment_suggested_values'])) {
            return array();
        }
        Piwik::checkUserHasViewAccess($idSite);

        $maxSuggestionsToReturn = 30;
        $segmentsMetadata = $this->getSegmentsMetadata($idSite, $_hideImplementationData = false);

        $segmentFound = false;
        foreach ($segmentsMetadata as $segmentMetadata) {
            if ($segmentMetadata['segment'] == $segmentName) {
                $segmentFound = $segmentMetadata;
                break;
            }
        }
        if (empty($segmentFound)) {
            throw new \Exception("Requested segment not found.");
        }

        // if segment has suggested values callback then return result from it instead
        if (isset($segmentFound['suggestedValuesCallback'])) {
            return call_user_func($segmentFound['suggestedValuesCallback'], $idSite, $maxSuggestionsToReturn);
        }

        // if period=range is disabled, do not proceed
        if (!Period\Factory::isPeriodEnabledForAPI('range')) {
            return array();
        }

        $startDate = Date::now()->subDay(60)->toString();
        $requestLastVisits = "method=Live.getLastVisitsDetails
        &idSite=$idSite
        &period=range
        &date=$startDate,today
        &format=original
        &serialize=0
        &flat=1";

        // Select non empty fields only
        // Note: this optimization has only a very minor impact
        $requestLastVisits .= "&segment=$segmentName" . urlencode('!=');

        // By default Live fetches all actions for all visitors, but we'd rather do this only when required
        if ($this->doesSegmentNeedActionsData($segmentName)) {
            $requestLastVisits .= "&filter_limit=400";
        } else {
            $requestLastVisits .= "&doNotFetchActions=1";
            $requestLastVisits .= "&filter_limit=800";
        }

        $request = new Request($requestLastVisits);
        $table = $request->process();
        if (empty($table)) {
            throw new \Exception("There was no data to suggest for $segmentName");
        }

        // Cleanup data to return the top suggested (non empty) labels for this segment
        $values = $table->getColumn($segmentName);

        // Select also flattened keys (custom variables "page" scope, page URLs for one visit, page titles for one visit)
        $valuesBis = $table->getColumnsStartingWith($segmentName . ColumnDelete::APPEND_TO_COLUMN_NAME_TO_KEEP);
        $values = array_merge($values, $valuesBis);

        $values = $this->getMostFrequentValues($values);

        $values = array_slice($values, 0, $maxSuggestionsToReturn);

        $values = array_map(array('Piwik\Common', 'unsanitizeInputValue'), $values);

        return $values;
    }

    /**
     * @param $segmentName
     * @return bool
     */
    protected function doesSegmentNeedActionsData($segmentName)
    {
        // If you update this, also update flattenVisitorDetailsArray
        $segmentsNeedActionsInfo = array('visitConvertedGoalId',
                                         'pageUrl', 'pageTitle', 'siteSearchKeyword',
                                         'entryPageTitle', 'entryPageUrl', 'exitPageTitle', 'exitPageUrl');
        $isCustomVariablePage = stripos($segmentName, 'customVariablePage') !== false;
        $isEventSegment = stripos($segmentName, 'event') !== false;
        $isContentSegment = stripos($segmentName, 'content') !== false;
        $doesSegmentNeedActionsInfo = in_array($segmentName, $segmentsNeedActionsInfo) || $isCustomVariablePage || $isEventSegment || $isContentSegment;
        return $doesSegmentNeedActionsInfo;
    }

    /**
     * @param $values
     * @param $value
     * @return array
     */
    private function getMostFrequentValues($values)
    {
        // remove false values (while keeping zeros)
        $values = array_filter($values, 'strlen');

        // array_count_values requires strings or integer, convert floats to string (mysqli)
        foreach ($values as &$value) {
            if (is_numeric($value)) {
                $value = (string)round($value, 3);
            }
        }
        // we have a list of all values. let's show the most frequently used first.
        $values = array_count_values($values);

        arsort($values);
        $values = array_keys($values);
        return $values;
    }
}

/**
 */
class Plugin extends \Piwik\Plugin
{
    public function __construct()
    {
        // this class is named 'Plugin', manually set the 'API' plugin
        parent::__construct($pluginName = 'API');
    }

    /**
     * @see Piwik\Plugin::getListHooksRegistered
     */
    public function getListHooksRegistered()
    {
        return array(
            'AssetManager.getStylesheetFiles' => 'getStylesheetFiles'
        );
    }

    public function getStylesheetFiles(&$stylesheets)
    {
        $stylesheets[] = "plugins/API/stylesheets/listAllAPI.less";
    }
}


text:
package net.markenwerk.commons.iterators;

/**
 * A {@link DoubleArrayIterator} is an {@link AbstractIndexedIterator} that
 * iterates over a given {@code double[]}.
 *
 * @author Torsten Krause (tk at markenwerk dot net)
 * @since 1.0.0
 */
public final class DoubleArrayIterator extends AbstractIndexedIterator<Double> {

	private final double[] array;

	/**
	 * Creates a new {@linkplain DoubleArrayIterator}.
	 *
	 * @param array
	 *           The {@code double[]} to iterate over.
	 *
	 * @throws IllegalArgumentException
	 *            If the given {@code double[]} is {@literal null}.
	 */
	public DoubleArrayIterator(double... array) throws IllegalArgumentException {
		super(0, length(array));
		this.array = array;
	}

	private static int length(double[] array) {
		if (null == array) {
			throw new IllegalArgumentException("The given array is null");
		}
		return array.length;
	}

	@Override
	public Double get(int index) {
		return array[index];
	}

}


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

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
net.sf.antcontrib.cpptasks.types Class Hierarchy (cpptasks 1.0b5 API)
</TITLE>

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

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package net.sf.antcontrib.cpptasks.types

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

net.sf.antcontrib.cpptasks.types.CommandLineArgument

net.sf.antcontrib.cpptasks.types.CompilerArgument
net.sf.antcontrib.cpptasks.types.LinkerArgument

org.apache.tools.ant.types.EnumeratedAttribute

net.sf.antcontrib.cpptasks.types.CommandLineArgument.LocationEnum
net.sf.antcontrib.cpptasks.types.LibraryTypeEnum

net.sf.antcontrib.cpptasks.types.FlexLong
org.apache.tools.ant.ProjectComponent

org.apache.tools.ant.types.DataType

org.apache.tools.ant.types.AbstractFileSet (implements java.lang.Cloneable, org.apache.tools.ant.types.selectors.SelectorContainer)

org.apache.tools.ant.types.FileSet

net.sf.antcontrib.cpptasks.types.ConditionalFileSet

net.sf.antcontrib.cpptasks.types.DefineSet
net.sf.antcontrib.cpptasks.types.LibrarySet

net.sf.antcontrib.cpptasks.types.SystemLibrarySet

org.apache.tools.ant.types.Path (implements java.lang.Cloneable)

net.sf.antcontrib.cpptasks.types.ConditionalPath

net.sf.antcontrib.cpptasks.types.IncludePath
net.sf.antcontrib.cpptasks.types.SystemIncludePath

net.sf.antcontrib.cpptasks.types.UndefineArgument

net.sf.antcontrib.cpptasks.types.DefineArgument

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2001-2008 Ant-Contrib Project. All Rights Reserved.


text:
package mongodb

import (
	"github.com/tsuru/tsuru/storage/storagetest"
	"gopkg.in/check.v1"
)

var _ = check.Suite(&storagetest.PlanSuite{
	PlanService: &PlanService{},
	SuiteHooks:  &mongodbBaseTest{},
})


text:
set -e

export MN_SOURCE=$PWD
export MN_INSTALL=`pip show multinet | grep Location | awk '{print $2"/multinet"}'`

if [[ "${REPORT_COVERAGE}" == 1 ]]; then
    pytest --cov
else
    cd $MN_INSTALL
    printenv PWD
    pytest
    cd $MN_SOURCE
fi

set +e


text:
/*
 Description: Initialization script
 Filename:app.js
 Created Date: 29/7/2013
 */

var caramel = require('caramel'),
    config = require('/config/publisher.json'),
    carbon = require('carbon'),
    mediaType = 'application/vnd.wso2.registry-ext-type+xml',
    conf = carbon.server.loadConfig('carbon.xml'),
    offset = conf.*::['Ports'].*::['Offset'].text(),
    hostName = conf.*::['HostName'].text().toString();

// var ext_parser = require('/modules/ext/core/extension.parser.js').extension_parser();
// var ext_domain = require('/modules/ext/core/extension.domain.js').extension_domain();
// var ext_core = require('/modules/ext/core/extension.core.js').extension_core();
// var ext_mng = require('/modules/ext/core/extension.management.js').extension_management();

if (hostName === null || hostName === '') {
    hostName = 'localhost';
}

var httpPort = 9763 + parseInt(offset, 10);
var httpsPort = 9443 + parseInt(offset, 10);

var process = require('process');
process.setProperty('server.host', hostName);
process.setProperty('http.port', httpPort.toString());
process.setProperty('https.port', httpsPort.toString());

var pubConfig = require('/config/publisher.js').config();

var mod = require('store');
var rxt=require('rxt');
var lifecycle=require('lifecycle');

caramel.configs({
    context: '/publisher',
    cache: false,
    negotiation: true,
    themer: function () {
        //TODO: Hardcoded theme
        return 'default';
    }

});

mod.server.init(pubConfig);
mod.user.init(pubConfig);
rxt.core.init();
rxt.resources.init();
var context=caramel.configs().context;
rxt.app.init(context);
lifecycle.core.init();

var publisher = require('/modules/publisher.js');
publisher.init(pubConfig);

//var SUPER_TENANT_ID=-1234;
//var event = require('/modules/event.js');
//event.emit('tenantLoad', SUPER_TENANT_ID);

//Configure Caramel

//startup log for url
var logPublisherUrl = function () {
	var log = new Log();
    log.info("Publisher URL : " + config.server.http + caramel.configs().context);
};

//Cause the super tenant to be load
var SUPER_TENANT = -1234;
var event = require('event');
event.emit('tenantLoad', SUPER_TENANT);

setTimeout(logPublisherUrl, 7000);


text:
'use strict';

exports.__esModule = true;
exports['default'] = bindCallback;

function bindCallback(func, thisArg, argCount) {
    if (typeof thisArg === 'undefined') {
        return func;
    }
    switch (argCount) {
        case 0:
            return function () {
                return func.call(thisArg);
            };
        case 1:
            return function (arg) {
                return func.call(thisArg, arg);
            };
        case 2:
            return function (value, index) {
                return func.call(thisArg, value, index);
            };
        case 3:
            return function (value, index, collection) {
                return func.call(thisArg, value, index, collection);
            };
    }
    return function () {
        return func.apply(thisArg, arguments);
    };
}

;
//# sourceMappingURL=bindCallback.js.map
module.exports = exports['default'];
//# sourceMappingURL=bindCallback.js.map


text:
__author__ = 'tspycher'
import time

class Isa(object):
    """
    Class which describes the ideal athmosphere
    """

    ft_per_hpa = 27
    subtract_c_per_tousandfeet = 2
    feet_per_c = 120
    base_qnh = 1013.25
    tmp_ams = 15

    earliest_sunset = "16:30"
    latest_sunrise = "08:30"

    def __set__(self, instance, value):
        raise Exception("not allowed to edit parameters")


text:
// coded by Jongwhan Lee   (leejw51@gmail.com)
// Session
package main

import (
	//"fmt"
	"net"
	"time"
	//	"os"
	//"bytes"
	//"encoding/binary"
	"sync"

	"github.com/golang/protobuf/proto"
)

type Session struct {
	program    *Program
	Name       string
	connection net.Conn
	Finish     bool
	wg         sync.WaitGroup

	packetQueue chan *Packet
	Active      bool // this session is active
}

func (session *Session) stop() {
	println("Wait To Finish")
	session.Finish = true

	session.connection.Close()

	session.wg.Wait()
	session.Active = false
	println("Wait Done")
}

func (session *Session) initialize() {
	session.Finish = false
	session.Active = true
	session.wg.Add(2)
	session.packetQueue = make(chan *Packet, 10)
}

func (session *Session) blockingSend(buf []byte) error {
	length := len(buf)
	processed := 0
	end := 0
	remain := 0

	for {
		remain = length - processed
		if 0 == remain {
			println("Send=", length)
			return nil
		}
		end = processed + remain
		n, err := session.connection.Write(buf[processed:end])
		if err != nil {
			println("Send Error=", err)
			session.Active = false
			return err
		}
		processed += n

	}

	return nil
}

func (session *Session) blockingRead(buf []byte) error {
	length := len(buf)
	processed := 0
	end := 0
	remain := 0
	for {
		remain = length - processed
		if 0 == remain {
			println("Read=", length)
			return nil
		}
		end = processed + remain
		n, err := session.connection.Read(buf[processed:end])
		if err != nil {
			println("Receive Error=", err)
			session.Active = false
			return err
		}
		processed += n

	}

	return nil
}
func (session *Session) receiveRoutine() {
	defer session.wg.Done()

	for {

		headBytes := make([]byte, 16)
		err := session.blockingRead(headBytes)
		if err != nil {
			return
		}

		newPacket := new(Packet)

		// read head
		newPacket.head.decode(headBytes)
		println("ID=", newPacket.head.id, "   Length=", newPacket.head.length)

		// read body
		newPacket.body = make([]byte, newPacket.head.length)
		err = session.blockingRead(newPacket.body)
		if err != nil {

			return
		}
		/*	buf := newPacket.unpack()
			message := &BasicMessage{}
			proto.Unmarshal(buf, message)

			println("message=", message.Talk)*/

		session.program.onReceivePacket(session, newPacket)

		if session.Finish {
			break
		}
	}
}

func (session *Session) sendRoutine() {

	defer session.wg.Done()

	for {
		select {
		case res := <-session.packetQueue:
			// write head
			data, _ := res.head.encode()
			err := session.blockingSend(data)
			if err != nil {
				return
			}

			// write body
			err = session.blockingSend(res.body)
			if err != nil {
				return
			}

		case <-time.After(time.Second * 1):
		}

		if session.Finish {
			break
		}
	}
}

func (session *Session) run() {

	go session.receiveRoutine()
	go session.sendRoutine()
}

func (session *Session) sendPacket(packet *Packet) {
	session.packetQueue <- packet
}

//--------- main routine..
func (session *Session) doProcess(packet *Packet) {
	session.parse(packet)

}

// called from main routine
func (session *Session) onReceiveBasicMessage(packet *Packet) {
	message := &BasicMessage{}
	proto.Unmarshal(packet.unpack(), message)
	println("Received=", message.Talk)

	session.program.broadcast(packet)
}

func (session *Session) onReceiveJsonMessage(packet *Packet) {
	message := packet.unpack()
	println("Received=", string(message))

	session.program.broadcast(packet)
}

func (session *Session) parse(packet *Packet) {
	parse(session, packet)
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <title>Artificial Reason</title>

    <link rel="shortcut icon" href="assets/img/favicon.png" />

    <meta name="description" content="">

    <link href="assets/css/preload.css" rel="stylesheet">

    <link href="assets/css/vendors.css" rel="stylesheet">
    <link href="assets/css/syntaxhighlighter/shCore.css" rel="stylesheet" >

    <link href="assets/css/style-blue.css" rel="stylesheet" title="default">
    <link href="assets/css/width-full.css" rel="stylesheet" title="default">

artificial reason

Clean and elegant theme

                 Login

                    <form role="form">

Login Form

                                <input type="text" class="form-control" placeholder="Username">

                                <input type="password" class="form-control" placeholder="Password">

                                    <input type="checkbox"> Remember me

                            <button type="submit" class="btn btn-ar btn-primary pull-right">Login</button>

                    </form>

                    <form role="form">

                            <input type="text" class="form-control" placeholder="Search...">

                                <button class="btn btn-ar btn-primary" type="button">Go!</button>

                    </form>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            Artificial Reason

                    Home

Option 1: Default

Option 2: Services

Option 3: Full Intro

Option 4: Only Full Intro

Option 5: News

Option 6: Professional Profile

Option 7: Subscribe

New Home Pages 1.4

Option 8: Product New

                    UI Elements

 CSS

 Typography

 Headers

 Dividers

 Blockquotes

 Forms

 Tables

 Buttons

 Basic Buttons

 Buttons Library Update

 Social Buttons

 Icons

 Artificial Reason Icons

 Glyphicons Icons

 Font Awesome

 Social Icons

 New in 1.4

 Profile Cards New

 Counters New

 Navbar Tabs New

 Masonry Layer New

 Components

 Components Dropdowns

 Panels

 Lists

 Paginations

 Labels and Badges

 Alerts and Wells

 Thumbnails

 Modals

 Progress Bars

 Tooltip & Popover

 Extra Elements

 Collapses & Tabs

 Vertical Tabs New

 Switch Controls New

 Contents Box

 Carousels

 Charts & CountDowns

 Masonry Layer New

                    Pages

                                About us & Team

About us Option 1

About us Option 2

About us & Team

Our Team Option 1

Our Team Option 2

                                Form

Contact Option 1

Contact Option 2

Login Integrated

Login Full Page

Login and Register

Register Option 1

                                Profiles

User Profile Option 1

User Profile Option 2

                                Error

Error 404 Full Page

Error 404 Integrated

Error 500 Full Page

Error 500 Integrated

                                Bussiness & Products

Testimonials

Our Clients

Products

Services

                                Pricing

Pricing Box

Pricing Mega Table

                                FAQ & Support

Support Center

FAQ Option 1

FAQ Option 2

                                Coming Soon

Coming Soon Option 1

Coming Soon Option 2

                                Timeline

Timeline Left

Timeline Center

                    Blog

Blog Right Sidebar

Blog Left Sidebar

Blog Full

Blog Masonry New

Other Option

Blog Item

Blog Item Full

                    E-commerce

E-commerce Home

E-commerce Filters

Product

Cart

                    Portfolio

Portfolio sidebar filters

Portfolio topbar filters

Portfolio with captions

Portfolio item

Portfolio item device

A template, infinite possibilities

We give you everything done, except the coffee

Built with Bootstrap

HTML5 and CSS3

Responsive Template

Lorem ipsum dolor sit amet consectetur adipisicing elit. In rerum maxime quis tenetur dolor recusandae a nulla qui enim dolorem.

Customization extremes

Configure your own template in few easy steps

25 default colors

Variables less for all colors

Full width and boxed mode

Lorem ipsum dolor sit amet consectetur adipisicing elit. In rerum maxime quis tenetur dolor recusandae a nulla qui enim dolorem.

Templates for almost everything

Artificial Reason include over 80 HTML templates

84 HTML Templates

More than 50 components

Extra CSS classes

Lorem ipsum dolor sit amet consectetur adipisicing elit. In rerum maxime quis tenetur dolor recusandae a nulla qui enim dolorem.

Lorem ipsum dolor

Consectetur adipisicing elit vritatis dolor rem officia molestiae atque eveniet inventore earum quas voluptates cumque

Lorem ipsum dolor

Consectetur adipisicing elit vritatis dolor rem officia molestiae atque eveniet inventore earum quas voluptates cumque

Lorem ipsum dolor

Consectetur adipisicing elit vritatis dolor rem officia molestiae atque eveniet inventore earum quas voluptates cumque

Lorem ipsum dolor

Consectetur adipisicing elit vritatis dolor rem officia molestiae atque eveniet inventore earum quas voluptates cumque

The template for all devices

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi, sapiente, nam sunt rem beatae architecto cupiditate numquam consectetur dolorum aliquam suscipit adipisci expedita vel quaerat illum aperiam facere inventore officia.

Consequuntur sed ipsum eius minima eum velit soluta accusamus omnis maiores modi quae mollitia consectetur adipisci.

Knows the Artificial Reason and surprise yourself

About us

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa, alias, nihil molestias libero corporis perferendis a quasi at.

Eos, illum, odit nulla provident sint atque quasi necessitatibus dolores voluptatibus perspiciatis aliquid tempora possimus laudantium. Blanditiis, deleniti!

Saepe, laborum, eligendi vitae ad excepturi officiis vel omnis quidem et dolorum rem vero explicabo consequatur mollitia nihil!

Fuga, omnis, quo, cumque, ipsa quasi facilis voluptatibus iure veniam nostrum voluptate accusantium dolore reprehenderit. Corrupti, mollitia, maiores!

Lorem ipsum dolor sit amet, consectetur adipisicing elit ducimus, pariatur ad ipsam et quod numquam eveniet magni aspernatur.

                           Talent and creativity

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati molestiae id ipsum ipsa repudiandae. Voluptatum, molestias, quas magnam repellat quos facilis sequi. Ullam optio eius deleniti dolore quasi doloribus ipsam incidunt perferendis.

Dolores, corrupti, laborum, officia sit aliquam doloremque accusantium nemo sunt veniam est incidunt perferendis minima obcaecati ex aperiam voluptatibus blanditiis eum suscipit magnam dolorum in adipisci nihil ipsam perspiciatis molestiae!

                           Design and code

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit dignissimos inventore cupiditate expedita saepe enim nobis nostrum? Laborum, laudantium, maiores, cupiditate, perspiciatis at ad accusamus corporis sed ipsam et velit!

Incidunt, harum itaque voluptatum asperiores recusandae explicabo maiores. Alias, quos, ex impedit at error id laborum fugit architecto qui beatae molestiae dolorum rem veritatis quia aliquam totam accusamus perferendis. Nulla!

                           Quality and Support

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia, rerum unde doloribus accusamus pariatur non expedita quibusdam velit totam obcaecati. Consequatur, deserunt, asperiores quam nisi earum voluptates animi labore tempore!

Dolorum, aliquam, totam labore saepe error a eum culpa assumenda sint laudantium ipsa iure ullam et dicta nesciunt repellendus optio voluptatibus reprehenderit odit officia fugiat necessitatibus recusandae architecto ad neque?

Latest Works

                        More info

Title Caption

                        More info

Title Caption

                        More info

Title Caption

                        More info

Title Caption

                        More info

Title Caption

                        More info

Title Caption

                        More info

Title Caption

                        More info

Title Caption

                        More info

Title Caption

                        More info

Title Caption

                        More info

Title Caption

                        More info

Title Caption

Discover our projects and the rigorous process of creation. Our principles are creativity, design, experience and knowledge. We are backed by 20 years of research.

Our Clients

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante ultricies nisi vel augue quam semper libero.

                            Brian Krzanich, Intel CEO

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante ultricies nisi vel augue quam semper libero.

                            Brian Krzanich, Intel CEO

Dolore totam at ea reiciendis suscipit a tempore cum nisi aspernatur nisi alias posuere erat a ante posuere erat a ante ultricies ultricies nisi vel augue quam semper conse erat quuntur.

                            Sheldon Cooper, Physical Quantum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante ultricies nisi vel augue quam semper libero.

                            Brian Krzanich, Intel CEO

Sitemap

Home

Blog

Portafolio

Works

Timeline

Pricing

About Us

Our Team

Services

FAQ

Login

Contact

Subscribe

Lorem ipsum Amet fugiat elit nisi anim mollit minim labore ut esse Duis ullamco ad dolor veniam velit.

                    <input type="text" class="form-control" placeholder="Email Adress">

                        <button class="btn btn-ar btn-primary" type="button">Subscribe</button>

Recent Post

Lorem ipsum Duis quis occaecat minim lorem ipsum tempor officia labor

                            August 18, 2013

Lorem ipsum dolor excepteur sunt in lorem ipsum cillum tempor

                            September 14, 2013

Lorem ipsum Dolor cupidatat minim adipisicing et fugiat

                            October 9, 2013

Recent Works

© 2014 Artificial Reason, inc. All rights reserved.

        <input type="text" class="form-control" placeholder="Search...">

            <button class="btn btn-default" type="button"></button>

Navigation

Home

Portfolio

About us

Blog

Contact

Social Media


text:
    <link  href="rainbow/themes/github.css" rel="stylesheet" type="text/css"/>
    <link  href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>

    <link  href="css/main.css" rel="stylesheet" type="text/css"/>

Echo effect with delay and gain

  var source = context.createOscillator(); // source

  var gainNode = context.createGain(); // gain
      gainNode.gain.value = 0.5;

  var delayNode = context.createDelay(); // delay
      delayNode.delayTime.value  = 0.75;

  var destination = context.destination; // destination

  source.connect(gainNode);
  gainNode.connect(destination);

  gainNode.connect(delayNode);
  delayNode.connect(gainNode);

  now = context.currentTime;
  source.start(now);
  source.stop(now + 0.3);

  <button type="button" class="play  btn btn-primary">Play</button>
  <button type="button" class="pause btn btn-success">Stop</button>


text:
using Microsoft.Build.Construction;
using Microsoft.DotNet.ProjectJsonMigration;
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.Tools.Test.Utilities;
using NuGet.Frameworks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using FluentAssertions;
using Microsoft.DotNet.ProjectJsonMigration.Rules;

namespace Microsoft.DotNet.ProjectJsonMigration.Tests
{
    public class GivenThatIWantToMigrateProjectDependencies : TestBase
    {
        [Fact]
        public void Project_dependencies_are_migrated_to_ProjectReference()
        {
            var solutionDirectory =
                TestAssetsManager.CreateTestInstance("TestAppWithLibrary", callingMethod: "p").Path;

            var appDirectory = Path.Combine(solutionDirectory, "TestApp");

            var projectContext = ProjectContext.Create(appDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);
            var mockProj = ProjectRootElement.Create();
            var testSettings = new MigrationSettings(appDirectory, appDirectory, "1.0.0", mockProj, null);
            var testInputs = new MigrationRuleInputs(new[] {projectContext}, mockProj, mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());
            new MigrateProjectDependenciesRule().Apply(testSettings, testInputs);

            var projectReferences = mockProj.Items.Where(item => item.ItemType.Equals("ProjectReference", StringComparison.Ordinal));
            projectReferences.Count().Should().Be(1);

            projectReferences.First().Include.Should().Be(Path.Combine("..", "TestLibrary", "TestLibrary.csproj"));
        }

        [Fact]
        public void It_throws_when_project_dependency_is_unresolved()
        {
            // No Lock file => unresolved
            var solutionDirectory =
                TestAssetsManager.CreateTestInstance("TestAppWithLibrary").Path;

            var appDirectory = Path.Combine(solutionDirectory, "TestApp");
            var libraryDirectory = Path.Combine(solutionDirectory, "TestLibrary");
            Directory.Delete(libraryDirectory, true);

            var projectContext = ProjectContext.Create(appDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);
            var mockProj = ProjectRootElement.Create();
            var testSettings = new MigrationSettings(appDirectory, appDirectory, "1.0.0", mockProj);
            var testInputs = new MigrationRuleInputs(new[] {projectContext}, mockProj, mockProj.AddItemGroup(), mockProj.AddPropertyGroup());

            Action action = () => new MigrateProjectDependenciesRule().Apply(testSettings, testInputs);
            action.ShouldThrow<Exception>()
                .Where(e => e.Message.Contains("MIGRATE1014::Unresolved Dependency: Unresolved project dependency (TestLibrary)"));
        }

        [Theory]
        [InlineData(@"some/path/to.cSproj", new [] { @"some/path/to.cSproj" })]
        [InlineData(@"to.CSPROJ",new [] { @"to.CSPROJ" })]
        public void It_migrates_csproj_ProjectReference_in_xproj(string projectReference, string[] expectedMigratedReferences)
        {
            var xproj = ProjectRootElement.Create();
            xproj.AddItem("ProjectReference", projectReference);

            var projectReferenceName = Path.GetFileNameWithoutExtension(projectReference);

            var projectJson = @"
                {
                    ""dependencies"": {" +
                        $"\"{projectReferenceName}\"" + @": {
                            ""target"" : ""project""
                        }
                    }
                }
            ";

            var testDirectory = Temp.CreateDirectory().Path;
            var migratedProj = TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[]
                {
                    new MigrateProjectDependenciesRule()
                }, projectJson, testDirectory, xproj);

            var migratedProjectReferenceItems = migratedProj.Items.Where(i => i.ItemType == "ProjectReference");
            migratedProjectReferenceItems.Should().HaveCount(expectedMigratedReferences.Length);
            migratedProjectReferenceItems.Select(m => m.Include).Should().BeEquivalentTo(expectedMigratedReferences);
        }

        [Fact]
        public void It_migrates_csproj_ProjectReference_in_xproj_including_condition_on_ProjectReference()
        {
            var projectReference = "some/to.csproj";
            var xproj = ProjectRootElement.Create();
            var csprojReferenceItem = xproj.AddItem("ProjectReference", projectReference);
            csprojReferenceItem.Condition = " '$(Foo)' == 'bar' ";

            var projectReferenceName = Path.GetFileNameWithoutExtension(projectReference);

            var projectJson = @"
                {
                    ""dependencies"": {" +
                        $"\"{projectReferenceName}\"" + @": {
                            ""target"" : ""project""
                        }
                    }
                }
            ";

            var testDirectory = Temp.CreateDirectory().Path;
            var migratedProj = TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[]
                {
                    new MigrateProjectDependenciesRule()
                }, projectJson, testDirectory, xproj);

            var migratedProjectReferenceItems = migratedProj.Items.Where(i => i.ItemType == "ProjectReference");
            migratedProjectReferenceItems.Should().HaveCount(1);

            var migratedProjectReferenceItem = migratedProjectReferenceItems.First();
            migratedProjectReferenceItem.Include.Should().Be(projectReference);
            migratedProjectReferenceItem.Condition.Should().Be(" '$(Foo)' == 'bar' ");
        }

        [Fact]
        public void It_migrates_csproj_ProjectReference_in_xproj_including_condition_on_ProjectReference_parent()
        {
            var projectReference = "some/to.csproj";
            var xproj = ProjectRootElement.Create();
            var csprojReferenceItem = xproj.AddItem("ProjectReference", projectReference);
            csprojReferenceItem.Parent.Condition = " '$(Foo)' == 'bar' ";

            var projectReferenceName = Path.GetFileNameWithoutExtension(projectReference);

            var projectJson = @"
                {
                    ""dependencies"": {" +
                        $"\"{projectReferenceName}\"" + @": {
                            ""target"" : ""project""
                        }
                    }
                }
            ";

            var testDirectory = Temp.CreateDirectory().Path;
            var migratedProj = TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[]
                {
                    new MigrateProjectDependenciesRule()
                }, projectJson, testDirectory, xproj);

            var migratedProjectReferenceItems = migratedProj.Items.Where(i => i.ItemType == "ProjectReference");
            migratedProjectReferenceItems.Should().HaveCount(1);

            var migratedProjectReferenceItem = migratedProjectReferenceItems.First();
            migratedProjectReferenceItem.Include.Should().Be(projectReference);
            migratedProjectReferenceItem.Condition.Should().Be(" '$(Foo)' == 'bar' ");
        }

        [Fact]
        public void It_migrates_csproj_ProjectReference_in_xproj_including_condition_on_ProjectReference_parent_and_item()
        {
            var projectReference = "some/to.csproj";
            var xproj = ProjectRootElement.Create();
            var csprojReferenceItem = xproj.AddItem("ProjectReference", projectReference);
            csprojReferenceItem.Parent.Condition = " '$(Foo)' == 'bar' ";
            csprojReferenceItem.Condition = " '$(Bar)' == 'foo' ";

            var projectReferenceName = Path.GetFileNameWithoutExtension(projectReference);

            var projectJson = @"
                {
                    ""dependencies"": {" +
                        $"\"{projectReferenceName}\"" + @": {
                            ""target"" : ""project""
                        }
                    }
                }
            ";

            var testDirectory = Temp.CreateDirectory().Path;
            var migratedProj = TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[]
                {
                    new MigrateProjectDependenciesRule()
                }, projectJson, testDirectory, xproj);

            var migratedProjectReferenceItems = migratedProj.Items.Where(i => i.ItemType == "ProjectReference");
            migratedProjectReferenceItems.Should().HaveCount(1);

            var migratedProjectReferenceItem = migratedProjectReferenceItems.First();
            migratedProjectReferenceItem.Include.Should().Be(projectReference);
            migratedProjectReferenceItem.Condition.Should().Be(" '$(Bar)' == 'foo'  and  '$(Foo)' == 'bar' ");
        }
    }
}


text:
Dummy::Application.routes.draw do
  root :to => "books#index"
  resources :books
end


text:
Duostaff::Application.configure do
  config.cache_classes = false
  config.cache_store = :mem_cache_store

  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  config.action_mailer.raise_delivery_errors = false
  config.active_support.deprecation = :log
  config.action_mailer.default_url_options = { :host => "localhost" }

  config.assets.compress = false
  config.assets.compile = true

  config.assets.debug = true
  config.eager_load = false

  SEND_NEWS_LETTER = false

  # Constants for mailers
  BASE_URL = "localhost"
  BASE_PORT = 3000
  WEBSITE_URL                    = "#{BASE_URL}#{BASE_PORT}"

  config.action_mailer.delivery_method     = :sendmail
  config.action_mailer.default_url_options = { :host => BASE_URL, :port => BASE_PORT }
end


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();

        $user = $this->session->userdata("user");
        if ($user['profile_type'] != 'ADMIN') {
            die('Você não possui permissão de acesso a gestão de usuários!');
        }
        $this->load->model('User_model');
        $this->load->model('Profile_model');
    }

    public function index()
    {
        $data['profiles'] = $this->Profile_model->getprofiles();

        $data['user_active'] = [
            ['value' => 'S', 'label' => 'Sim'],
            ['value' => 'N', 'label' => 'Não'],
        ];

        $data['content'] = 'user/user_view';

        $this->parser->parse('master_template', $data);
    }

    /**
     * Formatação especial para a exibição dos dados na GRID
     * Formata email, telefones etc.
     * @author Saulo de Siqueira
     */
    public function formatDatagrid($datagrid)
    {
        $formatedGrid = array();
        foreach ($datagrid as $key => $value) {
            $data = array();
            foreach ($value as $i => $val) {
                switch ($i) {
                    case 'ind_ativo':
                        if ($val == "S") {
                            $formatedGrid[$key] = $data[$i] = "Sim";
                        } elseif ($val == "N") {
                            $formatedGrid[$key] = $data[$i] = "Não";
                        } else {
                            $formatedGrid[$key] = $data[$i] = $val;
                        }
                        break;
                    default:
                        $formatedGrid[$key] = $data[$i] = $val;
                        break;
                }
            }
            $formatedGrid[$key] = $data;
        }

        return $formatedGrid;
    }

    public function store()
    {
        $data = array();
        parse_str($_POST["data"], $data);

        $user = new StdClass();
        $user->user_id = !is_null($data["user_id"]) ? $data["user_id"] : null;
        $user->user_name = $data["user_name"];
        $user->user_email = $data["user_email"];
        $user->profile_id = $data["profile_id"];
        $user->user_password = $data["user_password"];
        $user->ind_ativo = $data["ind_ativo"];

        $message = array();
        if ($user->user_id == null) {
            if ($this->userExists($user)) {
                $message['boolean'] = false;
                $message['message'] = "Já existe um usuário cadastrado com este e-mail";
                echo json_encode($message);
                exit(0);
            }
            $this->User_model->storeUser($user);
        } else {
            $this->updateUser();
        }
        $message['boolean'] = true;
        $message['message'] = "Usuário salvo com sucesso!";
        echo json_encode($message);
        exit(0);
    }

    public function show($id)
    {
        $user = $this->User_model->getUser($id);
        echo json_encode($user);
        exit(0);
    }

    public function edit($id)
    {
        $user = $this->User_model->getUser($id);
        echo json_encode($user);
        exit(0);
    }

    public function updateUser()
    {
        $data = array();
        parse_str($_POST["data"], $data);

        $user = new StdClass();
        $user->user_id = $data["user_id"];
        $user->user_name = $data["user_name"];
        $user->user_email = $data["user_email"];
        $user->profile_id = $data["profile_id"];
        $user->user_password = $data["user_password"];
        $user->ind_ativo = $data['ind_ativo'];
        $this->User_model->updateUser($user);

        $message = array();
        $message['boolean'] = true;
        $message['message'] = "Usuário salvo com sucesso!";
        echo json_encode($message);
        exit(0);
    }

    public function destroy($id)
    {
        $canDelete = $this->User_model->canDelete($id);

        if (!$canDelete['boolean']) {
            echo json_encode($canDelete);
            exit(0);
        }

        $this->User_model->deleteUser($id);
        $message['boolean'] = true;
        $message['message'] = "Usuário removido com sucesso";
        echo json_encode($message);
        exit(0);
    }

    public function datagrid()
    {
        echo json_encode($this->formatDatagrid($this->User_model->datagrid()));
        exit(0);
    }

    public function userExists($user)
    {
        $total = $this->User_model->userExists($user);
        if ($total[0]["total"] > 0) {
            return true;
        }

        return false;
    }
}


text:
; ******************************************************
;  * move
;  *****************************************************
move_invaders:
  cmp byte [invaders_move_cycle], INVADERS_MOVE_CYCLES
  je .move
  inc byte [invaders_move_cycle]
  jmp .done
.move:
  push si
  push cx
  push dx
  push ax

  mov byte [invaders_move_cycle], 0 ; reset the cycle counter
  mov si, invaders
  mov cl, NUM_INVADERS
.loop:
  ; load position
  mov dx, [si]

  ; skip invader, if destroyed
  cmp dx, INVALID_STATE
  je .continue

  ; move invader
  mov al, [invaders_move_direction]
  call move

  ; check collisions
  call check_bullet_collisions

  mov [si], dx

  cmp dx, INVALID_STATE
  jne .shoot

  ; dec invader counter
  dec byte [num_invaders_alive]
  jmp .continue

.shoot:
  ; shoot, if necessary
  mov al, [invaders_shoot_cycle]
  cmp byte al, [invaders_shoot_cycles]
  jne .continue
  call create_invader_bullet
.continue:
  add si, INVADER_SIZE
  dec cl
  jnz .loop

  ; update the shoot cycle
  mov al, [invaders_shoot_cycle]
  cmp byte al, [invaders_shoot_cycles]
  jne .inc_shoot_cycle
  mov byte [invaders_shoot_cycle], 0
  jmp .update_move_direction
.inc_shoot_cycle:
  inc byte [invaders_shoot_cycle]

.update_move_direction:
  mov al, [invaders_move_direction]
  inc al
  cmp al, MOVE_RESET
  jl .save_move_direction
  xor al, al  ; reset the move direction
.save_move_direction:
  mov [invaders_move_direction], al

  ; restore registers
  pop ax
  pop dx
  pop cx
  pop si
.done:
  ret

; ******************************************************
;  * render
;  *****************************************************
render_invaders:
  push si
  push ax
  push cx

  mov al, ICON_INVADER
  mov si, invaders
  mov cl, NUM_INVADERS
.loop:
  mov dx, [si]
  cmp dx, INVALID_STATE
  je .continue
  call print_object
.continue:
  add si, INVADER_SIZE
  dec cl
  jnz .loop
.done:
  pop cx
  pop ax
  pop si
  ret


text:
import React from 'react';
import { storiesOf } from '@storybook/react-native';
import { withKnobs } from '@storybook/addon-knobs';
import Wrapper from './../../Wrapper';
import { Example as DefaultLink } from './Basic';
import { Example as ExternalLink } from './ExternalLink';
import { Example as CustomOnPress } from './CustomOnPress';
import { Example as UnderlineLink } from './UnderlineLink';
import { Example as CompositeLink } from './CompositeLink';

storiesOf('Link', module)
  .addDecorator(withKnobs)
  .addDecorator((getStory: any) => <Wrapper>{getStory()}</Wrapper>)
  .add('Default Link', () => <DefaultLink />)
  .add('External Link', () => <ExternalLink />)
  .add('Custom Function onPress Link', () => <CustomOnPress />)
  .add('Composite Link Example', () => <CompositeLink />)
  .add('Underline Link', () => <UnderlineLink />);


text:
package nl.sense_os.commonsense.main.client.groups.join.components;

import java.util.ArrayList;
import java.util.List;

import nl.sense_os.commonsense.main.client.ext.component.WizardFormPanel;
import nl.sense_os.commonsense.main.client.ext.model.ExtSensor;
import nl.sense_os.commonsense.main.client.ext.util.SenseKeyProvider;
import nl.sense_os.commonsense.main.client.ext.util.SensorProcessor;
import nl.sense_os.commonsense.main.client.ext.util.SensorTextFilter;
import nl.sense_os.commonsense.main.client.sensors.library.LibraryColumnsFactory;
import nl.sense_os.commonsense.main.client.sensors.library.SensorGroupRenderer;

import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.form.AdapterField;
import com.extjs.gxt.ui.client.widget.form.LabelField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;

public class ShareSensorsForm extends WizardFormPanel {

	private List<String> reqSensorNames;
	private LabelField lblReqSensors;

	private GroupingStore<ExtSensor> store;
	private Grid<ExtSensor> grid;
	private ToolBar filterBar;

	public ShareSensorsForm(final List<String> reqSensors, List<String> optSensors,
			List<ExtSensor> sensors) {

		reqSensorNames = reqSensors;

		initGrid(sensors);
		initFilters();
		ContentPanel panel = new ContentPanel(new FitLayout());
		panel.setHeaderVisible(false);
		panel.setStyleAttribute("backgroundColor", "white");
		panel.setTopComponent(filterBar);
		panel.add(grid);

		AdapterField field = new AdapterField(panel) {

			@Override
			public boolean isValid() {
				return isValid(false);
			}

			@Override
			public boolean isValid(boolean silent) {

				selectRequiredSensors();

				String missingSensors = "";
				List<ExtSensor> selected = grid.getSelectionModel().getSelectedItems();
				for (String reqName : reqSensorNames) {
					boolean reqSensorSelected = false;
					for (ExtSensor sensor : selected) {
						if (sensor.getName().equals(reqName)) {
							reqSensorSelected = true;
							break;
						}
					}
					if (!reqSensorSelected) {
						missingSensors += reqName + ", ";
					}
				}
				boolean valid = missingSensors.length() == 0;

				// display message
				// TODO does not work
				if (!valid && !silent) {
					if (missingSensors.length() > 0) {
						missingSensors = missingSensors.substring(0, missingSensors.length() - 2);
					}
					markInvalid("You need to select " + missingSensors + " sensor(s)");
				}
				return valid;
			}
		};
		field.setHeight(325);
		field.setResizeWidget(true);
		field.setFieldLabel("Select the sensors that you want to share with the group");
		add(field, new FormData(anchorSpec));

		lblReqSensors = new LabelField("foo");
		lblReqSensors.setHideLabel(true);
		setReqSensors(reqSensors);
		add(lblReqSensors, new FormData("-5"));
	}

	public Grid<ExtSensor> getGrid() {
		return grid;
	}

	public List<ExtSensor> getSharedSensors() {
		return grid.getSelectionModel().getSelection();
	}

	/**
	 * Initializes filter toolbar for the grid with sensors. The bar contains text filter and an
	 * owner filter.
	 */
	private void initFilters() {

		// text filter
		SensorTextFilter<ExtSensor> textFilter = new SensorTextFilter<ExtSensor>();
		textFilter.bind(store);

		// add filters to filter bar
		filterBar = new ToolBar();
		filterBar.add(new LabelToolItem("Filter: "));
		filterBar.add(textFilter);
	}

	private void initGrid(List<ExtSensor> sensors) {

		// list store
		store = new GroupingStore<ExtSensor>();
		store.setKeyProvider(new SenseKeyProvider<ExtSensor>());
		store.setMonitorChanges(true);
		store.add(sensors);

		// selection model for the grid
		CheckBoxSelectionModel<ExtSensor> selectionModel = new CheckBoxSelectionModel<ExtSensor>();

		// Column model
		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
		configs.add(selectionModel.getColumn());
		configs.addAll(LibraryColumnsFactory.create().getColumns());
		ColumnModel cm = new ColumnModel(configs);

		// grouping view for the grid
		GroupingView view = new GroupingView();
		view.setShowGroupedColumn(true);
		view.setForceFit(true);
		view.setGroupRenderer(new SensorGroupRenderer(cm));

		grid = new Grid<ExtSensor>(store, cm);
		grid.setModelProcessor(new SensorProcessor<ExtSensor>());
		grid.setView(view);
		grid.setBorders(false);
		grid.setId("group-sensor-share-grid");
		grid.setStateful(true);
		grid.setLoadMask(true);
		grid.setSelectionModel(selectionModel);
	}

	private void selectRequiredSensors() {

		List<ExtSensor> sensors = store.getModels();
		List<ExtSensor> requiredSensors = new ArrayList<ExtSensor>();
		for (ExtSensor sensor : sensors) {
			boolean required = false;
			for (String reqName : reqSensorNames) {
				if (sensor.getName().equals(reqName)) {
					required = true;
					break;
				}
			}
			if (required) {
				requiredSensors.add(sensor);
			}
		}

		// select the sensors in the grid
		grid.getSelectionModel().select(true,
				requiredSensors.toArray(new ExtSensor[requiredSensors.size()]));
	}

	public void setReqSensors(List<String> sensorNames) {

		reqSensorNames = sensorNames;

		String labelTxt = "You are required to share the following sensors to join this group: ";
		boolean visible = true;
		if (sensorNames.size() > 1) {
			for (String sensor : sensorNames) {
				labelTxt += "'" + sensor + "', ";
			}
			labelTxt = labelTxt.substring(0, labelTxt.length() - 2);
			visible = true;

		} else if (sensorNames.size() == 1) {
			labelTxt = "You are required to share your '" + sensorNames.get(0) + "' sensor.";
			visible = true;

		} else {
			labelTxt = "This group does not require you to share certain sensors.";
			visible = false;
		}

        lblReqSensors.setValue(labelTxt);
		lblReqSensors.setVisible(visible);

		selectRequiredSensors();
	}
}


text:
module SpaceshipInTrouble.Engine.ResourceSystem {

//six seconds? maybe a little bit too much?
//this is the timeout for loading the resources
    var DEFAULT_TIMEOUT = 6000;

    /**
     * The ResourceLoader helps you loading various resources with promises.
     *
     * Warning: SINGLETON! Use `getInstance()` instead of `new`
     *
     */
    export class ResourceManager {

        private static _instance;

        /**
         * Warning: SINGLETON. Don't use this constructor, use `getInstance()` instead
         *
         * @method __constructor
         */
        constructor() {
            if (ResourceManager._instance) {
                throw new Error("Error: Instantiation failed: Use ResourceLoader.getInstance() instead of new.");
            }
            ResourceManager._instance = this;
        }

        /**
         * Singleton method for getting the instance for this `ResourceLoader`
         *
         * @method getInstance
         * @static
         * @returns {engine.util.ResourceLoader} the singleton instance of this `ResourceLoader`
         */
        public static getInstance(): ResourceManager {
            if (ResourceManager._instance == null) {
                ResourceManager._instance = new ResourceManager();
            }
            return ResourceManager._instance;
        }

        /**
         * Loads and parses a json file and returns a promise to it
         *
         * @param jsonFile the file to load
         * @returns {Promise(*)} promise for the parsed JSON Data
         */
        public loadJSONFile(jsonFile:string) {
            var deferred = Q.defer();
            $.ajax({
                type: 'GET',
                url: jsonFile,
                dataType: 'json',
                timeout: DEFAULT_TIMEOUT,
                context: this,
                success: deferred.resolve,
                error: function (xhr, type) {
                    deferred.reject(new Error("Failed to load File!"));
                }
            });
            return deferred.promise;
        }

    }

}


text:
set -o pipefail

yarn install && \
git submodule update --init --recursive


text:
exports.run = (client, message, args) => {
message.delete();

if (args == '') {
  var user = client.user;
} else {
  var user = message.mentions.users.first();
}

const limit_msg = "50";

message.channel.messages.fetch({limit: limit_msg}).then((messages) => {
  if (user) {
    const filterBy = user.id;
      messages = messages.filter(m => m.author.id === filterBy).array().slice(0, limit_msg);
  } else {
    message.channel.send('No User Find.');
    return;
  }
    message.channel.bulkDelete(messages)
    .catch(error => message.channel.send('⚠Error : ' + error.message));
});

client.once('messageDeleteBulk', messages => {
  var n = new Date().toLocaleString();
  let msg_ary = messages.array();
  let num = msg_ary.length;
message.channel.send(`✅ | Clean Up \'${num}\' Messages | at: \"${n}\" |`, {code : 'ml'});
  });

}


text:
{#
   This file is part of the Exposure package.

   Copyright 2013 by Sébastien Pujadas

   For the full copyright and licence information, please view the LICENCE
   file that was distributed with this source code.
#}

{% from 'form_macros.tpl.html' import error, autofill, error_class %}

{% extends "page.tpl.html" %}

{% block content %}

Sign up

<form role="form" class="form-horizontal" method="post" action="/">

	Role

				<input type="radio" name="usertype" value="projectowner" {% if (session.autofill.usertype == "projectowner") or not (session.autofill.usertype is defined) %} checked="checked" {% endif %} />
				Project owner

				<input type="radio" name="usertype" value="sponsor" {% if session.autofill.usertype == "sponsor" %} checked="checked" {% endif %}/>
				Sponsor

		{{ error(session.errors, 'usertype') }}

	Email address

		<input type="text" class="form-control" id="email" name="email" placeholder="Type in your email address"
		       maxlength="254" value="{{ autofill(session.autofill, 'email') }}" />
		{{ error(session.errors, 'email') }}

	Email address (confirm)

		<input type="text" class="form-control" id="email_check" name="email_check" placeholder="Type in your email address (again)"
		       maxlength="254" value="{{ autofill(session.autofill, 'email_check') }}" />
		{{ error(session.errors, 'email_check') }}

	Password

		<input type="password" class="form-control" id="password" name="password" placeholder="Type in a password" />
		{{ error(session.errors, 'password') }}

	Password (confirm)

		<input type="password" class="form-control" id="password_check" name="password_check" placeholder="Type in the same password" />
		{{ error(session.errors, 'password_check') }}

				<input type="checkbox" name="terms_and_conditions_accepted" value="y">I have read and accept the terms and conditions</input>
				{{ error(session.errors, 'tcs') }}

		<button type="submit" class="btn btn-primary">Sign up</button>

<input type="hidden" name="token" value="{{ session.token }}" />
<input type="hidden" name="action" value="user_signup" />

</form>

{% endblock %}


text:
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
//     Copyright (c) 2010-2013 Garrett Serack and CoApp Contributors.
//     Contributors can be discovered using the 'git log' command.
//     All rights reserved.
// </copyright>
// <license>
//     The software is licensed under the Apache 2.0 License (the "License")
//     You may not use the software except in compliance with the License.
// </license>
//-----------------------------------------------------------------------

namespace ClrPlus.Powershell.Provider.Base {
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Management.Automation.Provider;
    using System.Text;
    using Core.Utility;
    using Utility;

    public class ContentReader : IContentReader {
        private Stream _stream;
        private long _length;
        private List<string> _lineBuffer = new List<string>();
        private Decoder _decoder;

        public ContentReader(Stream stream, long length, Encoding encoding = null) {
            _stream = stream;
            _length = length;
            if (encoding != null) {
                _decoder = encoding.GetDecoder();
            }
        }

        public void Dispose() {
            Close();
        }

        private long RemainingBytes {
            get {
                return _length - _stream.Position;
            }
        }

        public IList Read(long linesToRead) {
            if (linesToRead == 0) {
                LoadBuffer(RemainingBytes);
                linesToRead = _lineBuffer.Count;
            }

            while (_lineBuffer.Count < linesToRead && RemainingBytes > 0) {
                LoadBuffer();
            }

            linesToRead = Math.Min(linesToRead, _lineBuffer.Count);

            if (linesToRead > 0) {
                lock (_lineBuffer) {
                    var result = _lineBuffer.GetRange(0, (int)linesToRead);
                    _lineBuffer.RemoveRange(0, (int)linesToRead);
                    return result;
                }
            }

            return new List<string>();
        }

        private void LoadBuffer(long bytesToRead = (256*1024)) {
            bytesToRead = Math.Min(bytesToRead, RemainingBytes);
            var buffer = new byte[bytesToRead];

            var read = _stream.Read(buffer, 0, (int)bytesToRead);
            var chars = new char[read];
            read = GetDecoder(buffer).GetChars(buffer, 0, read, chars, 0);
            lock (_lineBuffer) {
                _lineBuffer.AddRange(new String(chars, 0, read).Replace("\r\n", "\r").Split('\r'));
            }
        }

        private Decoder GetDecoder(byte[] buffer) {
            return _decoder ?? (_decoder = buffer.GetTextEncoding().GetDecoder());
        }

        public void Seek(long offset, SeekOrigin origin) {
            _stream.Seek(offset, origin);
        }

        public void Close() {
            if (_stream != null) {
                _stream.Close();
                _stream.Dispose();
                _stream = null;
            }
        }
    }
}


text:
import { CountValidatorTest } from './CountValidatorTest';

export default class CountValidatorArrayTest extends CountValidatorTest {
    createCollection(content) {
        return content;
    }
}


text:
"""Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import unittest

import list_appdata

class TestListAppdata(unittest.TestCase):
    """Unit test class for Appdata snippet"""

    @classmethod
    def test_list_appdata(cls):
        """Test list_appdata"""
        files = list_appdata.list_appdata()
        cls.assertNotEqual(cls, 0, len(files))

if __name__ == '__main__':
    unittest.main()


text:
<component name="libraryTable">
  <library name="animated-vector-drawable-25.3.0">
    <CLASSES>
      <root url="file://E:/Android_SDK/avd/.android/build-cache/ac95fd4e90bc0153f0c4dde72bac02f5330a0c45/output/res" />
      <root url="jar://E:/Android_SDK/avd/.android/build-cache/ac95fd4e90bc0153f0c4dde72bac02f5330a0c45/output/jars/classes.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://E:/Android_SDK/extras/android/m2repository/com/android/support/animated-vector-drawable/25.3.0/animated-vector-drawable-25.3.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text: export {router as api} from './api.js';


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(EntityCRUD.Startup))]
namespace EntityCRUD
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


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

<TITLE>
EventBuffer
</TITLE>

<META NAME="date" CONTENT="2011-03-08">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

edu.umass.cs.sase.engine

Class EventBuffer

java.lang.Object
  edu.umass.cs.sase.engine.EventBuffer

public class EventBuffer
extends java.lang.Object

This class is used to buffer the selected events.

Author:

haopeng

Constructor Summary

EventBuffer()

Method Summary

 void
bufferEvent(Event e)

          Buffers an event

 Event
getEvent(int Id)

          This method returns the event with the provided event id.

Methods inherited from class java.lang.Object

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

Constructor Detail

EventBuffer

public EventBuffer()

Method Detail

getEvent

public Event getEvent(int Id)

This method returns the event with the provided event id.

 this method is awesome.

Parameters:
Id - The id of the event you want

Returns:
The event with the Id.

bufferEvent

public void bufferEvent(Event e)

Buffers an event

Parameters:
e - The event to be buffered

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package types

import (
	"encoding/json"
	"errors"

	"github.com/appc/spec/Godeps/_workspace/src/github.com/GoogleCloudPlatform/kubernetes/pkg/api/resource"
)

var (
	ErrDefaultTrue     = errors.New("default must be false")
	ErrDefaultRequired = errors.New("default must be true")
	ErrRequestNonEmpty = errors.New("request not supported by this resource, must be empty")

	ResourceIsolatorNames = make(map[ACIdentifier]struct{})
)

const (
	ResourceBlockBandwidthName   = "resource/block-bandwidth"
	ResourceBlockIOPSName        = "resource/block-iops"
	ResourceCPUName              = "resource/cpu"
	ResourceMemoryName           = "resource/memory"
	ResourceNetworkBandwidthName = "resource/network-bandwidth"
)

func init() {
	AddIsolatorName(ResourceBlockBandwidthName, ResourceIsolatorNames)
	AddIsolatorName(ResourceBlockIOPSName, ResourceIsolatorNames)
	AddIsolatorName(ResourceCPUName, ResourceIsolatorNames)
	AddIsolatorName(ResourceMemoryName, ResourceIsolatorNames)
	AddIsolatorName(ResourceNetworkBandwidthName, ResourceIsolatorNames)

	AddIsolatorValueConstructor(ResourceBlockBandwidthName, NewResourceBlockBandwidth)
	AddIsolatorValueConstructor(ResourceBlockIOPSName, NewResourceBlockIOPS)
	AddIsolatorValueConstructor(ResourceCPUName, NewResourceCPU)
	AddIsolatorValueConstructor(ResourceMemoryName, NewResourceMemory)
	AddIsolatorValueConstructor(ResourceNetworkBandwidthName, NewResourceNetworkBandwidth)
}

func NewResourceBlockBandwidth() IsolatorValue {
	return &ResourceBlockBandwidth{}
}
func NewResourceBlockIOPS() IsolatorValue {
	return &ResourceBlockIOPS{}
}
func NewResourceCPU() IsolatorValue {
	return &ResourceCPU{}
}
func NewResourceNetworkBandwidth() IsolatorValue {
	return &ResourceNetworkBandwidth{}
}
func NewResourceMemory() IsolatorValue {
	return &ResourceMemory{}
}

type Resource interface {
	Limit() *resource.Quantity
	Request() *resource.Quantity
	Default() bool
}

type ResourceBase struct {
	val resourceValue
}

type resourceValue struct {
	Default bool               `json:"default"`
	Request *resource.Quantity `json:"request"`
	Limit   *resource.Quantity `json:"limit"`
}

func (r ResourceBase) Limit() *resource.Quantity {
	return r.val.Limit
}
func (r ResourceBase) Request() *resource.Quantity {
	return r.val.Request
}
func (r ResourceBase) Default() bool {
	return r.val.Default
}

func (r *ResourceBase) UnmarshalJSON(b []byte) error {
	return json.Unmarshal(b, &r.val)
}

func (r ResourceBase) AssertValid() error {
	return nil
}

type ResourceBlockBandwidth struct {
	ResourceBase
}

func (r ResourceBlockBandwidth) AssertValid() error {
	if r.Default() != true {
		return ErrDefaultRequired
	}
	if r.Request() != nil {
		return ErrRequestNonEmpty
	}
	return nil
}

type ResourceBlockIOPS struct {
	ResourceBase
}

func (r ResourceBlockIOPS) AssertValid() error {
	if r.Default() != true {
		return ErrDefaultRequired
	}
	if r.Request() != nil {
		return ErrRequestNonEmpty
	}
	return nil
}

type ResourceCPU struct {
	ResourceBase
}

func (r ResourceCPU) AssertValid() error {
	if r.Default() != false {
		return ErrDefaultTrue
	}
	return nil
}

type ResourceMemory struct {
	ResourceBase
}

func (r ResourceMemory) AssertValid() error {
	if r.Default() != false {
		return ErrDefaultTrue
	}
	return nil
}

type ResourceNetworkBandwidth struct {
	ResourceBase
}

func (r ResourceNetworkBandwidth) AssertValid() error {
	if r.Default() != true {
		return ErrDefaultRequired
	}
	if r.Request() != nil {
		return ErrRequestNonEmpty
	}
	return nil
}


text:
<?php
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;

use Doctrine\Common\Persistence\ObjectManager;
use ISL\BlogBundle\Entity\Article;
/**
 * Description of Articles
 *
 * @author gberger
 */
class Articles extends AbstractFixture implements OrderedFixtureInterface{

    public function load(ObjectManager $manager){
        $nbr = 20;

        for($i = 1; $i < $nbr; $i++){
            $article = new Article();
            $article->setAuteur("Greg Berger");
            $article->setTitre("Article ".$i);
            $article->setContenu($i." - Lorem ipsum etc.");

            $image = new ISL\BlogBundle\Entity\Image();
            $image->setUrl('https://placekitten.com/g/200/300');
            $image->setAlt('placeholder');
            $article->setImage($image);

            $article->addCategorie($this->getReference('cat-'.rand(0, 3)));
            $article->addCategorie($this->getReference('cat-'.rand(0, 3)));

            $manager->persist($article);
        }
        $manager->flush();
    }

    public function getOrder() {
        return 2;
    }

}