text:
from org.myrobotlab.image import Util
# start a opencv service

opencv = Runtime.start("opencv","OpenCV")
#gui.setActiveTab("opencv")

# add python as a listener to OpenCV data
# this tells the framework - whenever opencv.publishOpenCVData is invoked
# python.onOpenCVData will get called
python = Runtime.start("python","Python")
python.subscribe("opencv", "publishOpenCVData")

# call back - all data from opencv will come back to
# this method
def onOpenCVData(data):
  # check for a bounding box
  if data.getBoundingBoxArray() != None:
    for box in data.getBoundingBoxArray():
      print("bounding box", box.x, box.y, box.width, box.height)

# to capture from an image on the file system
# opencv.captureFromImageFile("C:\Users\grperry\Desktop\mars.jpg")

# not for you, it's for test
if ('virtual' in globals() and virtual):
  opencv.setMinDelay(500)
  opencv.setFrameGrabberType("org.bytedeco.javacv.FFmpegFrameGrabber")
  opencv.setInputSource("file")
  opencv.setInputFileName(Util.getRessourceDir()+"OpenCV/testData/monkeyFace.mp4")

opencv.capture()

#### LKOpticalTrack ####################
# experiment with Lucas Kanade optical flow/tracking
# adds the filter and one tracking point

opencv.addFilter("LKOpticalTrack")
opencv.setDisplayFilter("LKOpticalTrack")
# attempt to set a sample point in the middle
# of the video stream - you can
opencv.invokeFilterMethod("LKOpticalTrack","samplePoint", 0.5, 0.5)
sleep(4)
opencv.removeFilters()

opencv.addFilter("FaceDetect")
opencv.setDisplayFilter("FaceDetect")
# attempt to set a sample point in the middle
# of the video stream - you can

sleep(4)
opencv.removeFilters()

#### PyramidDown ####################
# scale the view down - faster since updating the screen is
# relatively slow
opencv.addFilter("PyramidDown")
opencv.setDisplayFilter("PyramidDown")
sleep(4)
# adding a second pyramid down filter - we need
# a unique name - so we'll call it PyramidDown2
opencv.addFilter("PyramidDown2","PyramidDown")
opencv.setDisplayFilter("PyramidDown2")
sleep(4)
opencv.removeFilters()

#### Canny ########################
# adding a canny filter
opencv.addFilter("Canny")
opencv.setDisplayFilter("Canny")
sleep(4)
canny = opencv.getFilter("Canny")
# changing parameters
canny.apertureSize = 3
canny.lowThreshold = 10.0
canny.highThreshold = 200.0

sleep(2)

canny.apertureSize = 5
canny.lowThreshold = 10.0
canny.highThreshold = 100.0

sleep(4)
opencv.removeFilters()
opencv.stopCapture()


text:
__author__ = "Cyril Jaquier, Steven Hiscocks, Yaroslav Halchenko"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier, 2008-2016 Fail2Ban Contributors"
__license__ = "GPL"

import platform

try:
	import setuptools
	from setuptools import setup
	from setuptools.command.install import install
	from setuptools.command.install_scripts import install_scripts
except ImportError:
	setuptools = None
	from distutils.core import setup

# all versions
from distutils.command.build_py import build_py
from distutils.command.build_scripts import build_scripts
if setuptools is None:
	from distutils.command.install import install
	from distutils.command.install_scripts import install_scripts
try:
	# python 3.x
	from distutils.command.build_py import build_py_2to3
	from distutils.command.build_scripts import build_scripts_2to3
	_2to3 = True
except ImportError:
	# python 2.x
	_2to3 = False

import os
from os.path import isfile, join, isdir, realpath
import sys
import warnings
from glob import glob

from fail2ban.setup import updatePyExec

if setuptools and "test" in sys.argv:
	import logging
	logSys = logging.getLogger("fail2ban")
	hdlr = logging.StreamHandler(sys.stdout)
	fmt = logging.Formatter("%(asctime)-15s %(message)s")
	hdlr.setFormatter(fmt)
	logSys.addHandler(hdlr)
	if set(["-q", "--quiet"]) & set(sys.argv):
		logSys.setLevel(logging.CRITICAL)
		warnings.simplefilter("ignore")
		sys.warnoptions.append("ignore")
	elif set(["-v", "--verbose"]) & set(sys.argv):
		logSys.setLevel(logging.DEBUG)
	else:
		logSys.setLevel(logging.INFO)
elif "test" in sys.argv:
	print("python distribute required to execute fail2ban tests")
	print("")

longdesc = '''
Fail2Ban scans log files like /var/log/pwdfail or
/var/log/apache/error_log and bans IP that makes
too many password failures. It updates firewall rules
to reject the IP address or executes user defined
commands.'''

if setuptools:
	setup_extra = {
		'test_suite': "fail2ban.tests.utils.gatherTests",
		'use_2to3': True,
	}
else:
	setup_extra = {}

data_files_extra = []

# Installing documentation files only under Linux or other GNU/ systems
# (e.g. GNU/kFreeBSD), since others might have protective mechanisms forbidding
# installation there (see e.g. #1233)
platform_system = platform.system().lower()
doc_files = ['README.md', 'DEVELOP', 'FILTERS', 'doc/run-rootless.txt']
if platform_system in ('solaris', 'sunos'):
	doc_files.append('README.Solaris')
if platform_system in ('linux', 'solaris', 'sunos') or platform_system.startswith('gnu'):
	data_files_extra.append(
		('/usr/share/doc/fail2ban', doc_files)
	)

# Get version number, avoiding importing fail2ban.
# This is due to tests not functioning for python3 as 2to3 takes place later
exec(open(join("fail2ban", "version.py")).read())

setup(
	name = "fail2ban",
	version = version,
	description = "Ban IPs that make too many password failures",
	long_description = longdesc,
	author = "Cyril Jaquier & Fail2Ban Contributors",
	author_email = "cyril.jaquier@fail2ban.org",
	url = "http://www.fail2ban.org",
	license = "GPL",
	platforms = "Posix",
	cmdclass = {
		'build_py': build_py, 'build_scripts': build_scripts,
	},
	scripts = [
		'bin/fail2ban-client',
		'bin/fail2ban-server',
		'bin/fail2ban-regex',
		'bin/fail2ban-testcases',
		# 'bin/fail2ban-python', -- link (binary), will be installed via install_scripts_f2b wrapper
	],
	packages = [
		'fail2ban',
		'fail2ban.client',
		'fail2ban.server',
		'fail2ban.tests',
		'fail2ban.tests.action_d',
	],
	package_data = {
		'fail2ban.tests':
			[ join(w[0], f).replace("fail2ban/tests/", "", 1)
				for w in os.walk('fail2ban/tests/files')
				for f in w[2]] +
			[ join(w[0], f).replace("fail2ban/tests/", "", 1)
				for w in os.walk('fail2ban/tests/config')
				for f in w[2]] +
			[ join(w[0], f).replace("fail2ban/tests/", "", 1)
				for w in os.walk('fail2ban/tests/action_d')
				for f in w[2]]
	},
	data_files = [
		('/etc/fail2ban',
			glob("config/*.conf")
		),
		('/etc/fail2ban/filter.d',
			glob("config/filter.d/*.conf")
		),
		('/etc/fail2ban/filter.d/ignorecommands',
			[p for p in glob("config/filter.d/ignorecommands/*") if isfile(p)]
		),
		('/etc/fail2ban/action.d',
			glob("config/action.d/*.conf") +
			glob("config/action.d/*.py")
		),
		('/etc/fail2ban/fail2ban.d',
			''
		),
		('/etc/fail2ban/jail.d',
			''
		),
		('/var/lib/fail2ban',
			''
		),
	] + data_files_extra,
	**setup_extra
)

redpajama_set_name: RedPajamaGithub


text:
package okra;

import okra.base.Okra;
import okra.model.DefaultOkraItem;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

@RunWith(JUnit4.class)
public class SingleThreadBenchmarkTest extends OkraBaseBenchmarkContainerTest {

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

    private static Okra<DefaultOkraItem> scheduler;

    @BeforeClass
    public static void init() throws UnknownHostException {
        scheduler = prepareDefaultMongo32OkraSpring();
    }

    @Test
    public void benchmarkSingleThreadTest() throws InterruptedException {

        int totalItems = 3000;
        LOGGER.info("Scheduling {} items... (0 to 30 secs ahead creation)", totalItems);

        Random random = new Random();
        for (int i = 0; i < totalItems; i++) {
            DefaultOkraItem item = new DefaultOkraItem();
            item.setRunDate(LocalDateTime.now().plusSeconds(random.nextInt(31)));
            scheduler.schedule(item);
        }

        LOGGER.info("Items scheduled.");
        LOGGER.info("Polling for items...");

        int receivedItems = 0;

        List<Double> deviationList = new ArrayList<>();
        List<DefaultOkraItem> processedItems = new ArrayList<>();
        while (receivedItems < totalItems) {
            Optional<DefaultOkraItem> opt = scheduler.poll();
            if (opt.isPresent()) {
                DefaultOkraItem item = opt.get();
                LOGGER.debug("Scheduled item received...: {}", item);
                receivedItems++;
                LocalDateTime runDate = item.getRunDate();
                double millisDiff = Math.abs(LocalDateTime.now().until(runDate, ChronoUnit.MILLIS));
                deviationList.add(millisDiff);
                processedItems.add(item);
            } else {
                Thread.sleep(500);
            }
        }

        LOGGER.info("Avg diff: [{}]", calcAvgDiff(deviationList));

        LOGGER.info("Removing schedules...");
        processedItems.parallelStream().forEach(i -> scheduler.delete(i));
        LOGGER.info("Done!");

    }

    private double calcAvgDiff(List<Double> deviationList) {
        DoubleSummaryStatistics statistics = deviationList.parallelStream().mapToDouble(val -> val).summaryStatistics();
        return statistics.getAverage();
    }

}


text:
#ifndef GAMSEXCEPTIONEXECUTION_H
#define GAMSEXCEPTIONEXECUTION_H

#include "gamsexception.h"

namespace gams {

/// Exception class thrown for GAMS execution exceptions.
class LIBSPEC GAMSExceptionExecution : public GAMSException
{
public:
    /// Constructor.
    /// \param what Exception message.
    /// \param exitCode Exit Code.
    GAMSExceptionExecution(const std::string& what, int exitCode);

    /// Constructor.
    /// \param what Exception message.
    /// \param exitCode Exit Code.
    GAMSExceptionExecution(const char* what, int exitCode);

    /// Get the return code.
    int rc();

private:
    int mRc;
};

} // namespace gams

#endif // GAMSEXCEPTIONEXECUTION_H


text:
<?php
namespace RUCD\WebshellDetector;

/**
 * Class Detector. Entry point containing all analyzers
 *
 * @file     Dectector
 * @category None
 * @package  Source
 * @author   Thibault Debatty <thibault.debatty@gmail.com>
 * @license  https://github.com/RUCD/webshell-detector/blob/master/LICENSE MIT
 * @link     https://github.com/RUCD/webshell-detector
 */
class Detector
{

    private $_analyzers = [];

    /**
     * Contructor of Detector. Initializes analyzers
     */
    public function __construct()
    {
        $this->_analyzers[] = new ExeAnalyzer();
        $this->_analyzers[] = new SignaturesAnalyzer();
        $this->_analyzers[] = new EntropyAnalyzer();
        $this->_analyzers[] = new FuzzyHashingAnalyzer();
        $this->_analyzers[] = new ObfuscationAnalyzer();
    }

    /**
     * Recursively scan a directory, and scan all files.
     *
     * @param string $directory Name of the directory to scan
     *
     * @return array a generator of entries $file => $score
     */
    public function analyzeDirectory($directory)
    {

        if (!is_dir($directory)) {
            throw new Exception("$directory is not a directory!");
        }

        $files = scandir($directory);
        foreach ($files as $file) {
            if ($file === ".." || $file === ".") {
                continue;
            }

            $file = $directory . DIRECTORY_SEPARATOR . $file;

            if (is_dir($file)) {
                yield from $this->analyzeDirectory($file);
                continue;

            }

            if (preg_match('/\.php$/', $file)) {
                $score = $this->analyzeString(
                    file_get_contents($file)
                );
                yield $file => $score;
            }
        }
    }

    /**
     * Analyze a string and return a score between 0 (harmless) and 1 (highly
     * suspicious).
     *
     * @param string $string The string to analyzer
     *
     * @return float The score
     */
    public function analyzeString($string)
    {
        $scores = [];
        foreach ($this->_analyzers as $analyzer) {
            $res = $analyzer->analyze($string);
            $scores[] = $res;
        }
        //var_dump($scores);
        return $this->_aggregate($scores);
    }

    /**
     * Returns a mark regarding the harmfulness of submitted scores
     *
     * @param array $scores The computed scores
     *
     * @return float The final score
     */
    private function _aggregate($scores)
    {
        // For now, perform a simple average
        return array_sum($scores) / count($scores);
    }
}


text:
using System.Collections.Generic;

namespace QueryFirst
{
    public static class System2Alias
    {
        private static Dictionary<string, string> _map = new Dictionary<string, string>()
            {
                {"System.Int32","int" },
                {"System.String","string" },
                {"System.Boolean","bool" },
                {"System.Byte","byte" },
                {"System.SByte","sbyte" },
                {"System.Char","char" },
                {"System.Decimal","decimal" },
                {"System.Double","double" },
                {"System.Single","float" },
                {"System.UInt32","uint" },
                {"System.Int64","long" },
                {"System.UInt64","ulong" },
                {"System.Object","object" },
                {"System.Int16","short" },
                {"System.UInt16","ushort" },
                {"System.Guid","Guid" },
                {"System.DateTime","DateTime" }
            };

        public static string Map(string csType, bool nullable)
        {
            if (_map.ContainsKey(csType))
            {
                var qm = "?";
                if (!nullable || csType == "System.String" || csType == "System.Object")
                    qm = "";
                return _map[csType] + qm;
            }
            else
            {
                return csType;
            }
        }
    }
}


text:
<?php

namespace Dingo\Api\Provider;

use ReflectionClass;
use FastRoute\RouteParser\Std as StdRouteParser;
use Dingo\Api\Routing\Adapter\Lumen as LumenAdapter;
use FastRoute\DataGenerator\GroupCountBased as GcbDataGenerator;

class LumenServiceProvider extends DingoServiceProvider
{
    /**
     * Boot the service provider.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        // Because Lumen sets the route resolver at a very weird point we're going to
        // have to use reflection whenever the request instance is rebound to
        // set the route resolver to get the current route.
        $this->app->rebinding('Illuminate\Http\Request', function ($app, $request) {
            $request->setRouteResolver(function () use ($app) {
                $reflection = new ReflectionClass($app);

                $property = $reflection->getProperty('currentRoute');
                $property->setAccessible(true);

                return $property->getValue($app);
            });
        });

        $this->app->routeMiddleware([
            'api.auth' => 'Dingo\Api\Http\Middleware\Auth',
            'api.throttle' => 'Dingo\Api\Http\Middleware\RateLimit',
        ]);
    }

    /**
     * Setup the configuration.
     *
     * @return void
     */
    protected function setupConfig()
    {
        $this->app->configure('api');

        parent::setupConfig();
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        parent::register();

        $reflection = new ReflectionClass($this->app);

        $this->app->instance('app.middleware', $this->gatherAppMiddleware($reflection));

        $this->addRequestMiddlewareToBeginning($reflection);

        $this->app->singleton('api.router.adapter', function ($app) {
            return new LumenAdapter($app, new StdRouteParser, new GcbDataGenerator, 'FastRoute\Dispatcher\GroupCountBased');
        });
    }

    /**
     * Add the request middleware to the beginning of the middleware stack on the
     * Lumen application instance.
     *
     * @param \ReflectionClass $reflection
     *
     * @return void
     */
    protected function addRequestMiddlewareToBeginning(ReflectionClass $reflection)
    {
        $property = $reflection->getProperty('middleware');
        $property->setAccessible(true);

        $middleware = $property->getValue($this->app);

        array_unshift($middleware, 'Dingo\Api\Http\Middleware\Request');

        $property->setValue($this->app, $middleware);
        $property->setAccessible(false);
    }

    /**
     * Gather the application middleware besides this one so that we can send
     * our request through them, exactly how the developer wanted.
     *
     * @param \ReflectionClass $reflection
     *
     * @return array
     */
    protected function gatherAppMiddleware(ReflectionClass $reflection)
    {
        $property = $reflection->getProperty('middleware');
        $property->setAccessible(true);

        $middleware = $property->getValue($this->app);

        return $middleware;
    }
}


text:
import _ from 'lodash';
import { isIframe, debug, win } from 'classes/helpers';

const syncMutation = (sync, lock, store, mutation) => {
	// lock iframe/top vuex from syncing
	sync[lock] = true;

	// actually sync the mutation
	sync[store].commit(
		mutation.type,
		_.cloneDeep(mutation.payload)
	);

	// unlock
	sync[lock] = false;
};

export const shareMutationsMain = store => {
	let sync = win.astroSync = {};

	sync.iframeIsSyncing = false;
	sync.parentIsSyncing = false;

	sync.store = store;

	store.subscribe(mutation => {
		if(!sync.iframeStore) {
			return;
		}

		if(!sync.iframeIsSyncing) {
			debug(`[Syncing top -> iframe] ${mutation.type}`);

			syncMutation(
				sync,
				'parentIsSyncing',
				'iframeStore',
				mutation
			);
		}
	});
};

export const shareMutationsIframe = store => {
	let sync = win.top.astroSync;

	sync.iframeStore = store;

	// copy current top window state into iframe state
	store.replaceState(_.cloneDeep(sync.store.state));

	store.subscribe(mutation => {
		if(!sync.store) {
			return;
		}

		if(!sync.parentIsSyncing) {
			debug(`[Syncing iframe -> top] ${mutation.type}`);

			syncMutation(
				sync,
				'iframeIsSyncing',
				'store',
				mutation
			);
		}
	});
};

export default isIframe ? shareMutationsIframe : shareMutationsMain;


text:
PROVIDER_NAME=iterio
PACKAGE_NAME=sysctl

PROVIDER_DIR=/opt/${PROVIDER_NAME}
PACKAGE_DIR=${PROVIDER_DIR}/${PACKAGE_NAME}
CONTROL_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
DATA_DIR=${CONTROL_DIR}/../data

install --group=root --mode=644 --owner=root ${DATA_DIR}/sysctl.conf /etc/

# Signal SUCCESS
exit 0


text:
It's an implementation of popular game Doodle Jump, controlled with accelerometer.
#Description
It contains PC application and STM32 code.
#Tools
Microsoft Visual Studio 2013, MonoGame, GIMP.
#How to run
Builds are available on our release page.
#How to compile
STM32 binary file is in "bin" folder.
#Future improvements
No future improvements are planned
#Attributions
Graphics: Dragon Ball: Advanced Adventure (GBA)
Music: Daft Punk - Veridis Quo
Virtual Port Com: https://github.com/xenovacivus/STM32DiscoveryVCP
#License
MIT License
#Credits
Piotr Nowak, Damian Rusin
The project was conducted during the Microprocessor Lab course held by the Institute of Control and Information Engineering, Poznan University of Technology.
Supervisor: Michał Fularz


text:
<?php
include_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' .
     DIRECTORY_SEPARATOR . 'Highchart.php';

$chart = new Highchart();

$chart->chart->renderTo = "container";
$chart->chart->type = "column";
$chart->title->text = "Stacked column chart";
$chart->xAxis->categories = array(
    'Apples',
    'Oranges',
    'Pears',
    'Grapes',
    'Bananas'
);
$chart->yAxis->min = 0;
$chart->yAxis->title->text = "Total fruit consumption";
$chart->yAxis->stackLabels->enabled = 1;
$chart->yAxis->stackLabels->style->fontWeight = "bold";
$chart->yAxis->stackLabels->style->color = new HighchartJsExpr(
    "(Highcharts.theme && Highcharts.theme.textColor) || 'gray'");
$chart->legend->align = "right";
$chart->legend->x = - 100;
$chart->legend->verticalAlign = "top";
$chart->legend->y = 20;
$chart->legend->floating = 1;
$chart->legend->backgroundColor = new HighchartJsExpr(
    "(Highcharts.theme && Highcharts.theme.legendBackgroundColorSolid) || 'white'");
$chart->legend->borderColor = "#CCC";
$chart->legend->borderWidth = 1;
$chart->legend->shadow = false;

$chart->tooltip->formatter = new HighchartJsExpr(
    "function() {
    return ''+ this.x +'
'+
    this.series.name +': '+ this.y +'
'+
    'Total: '+ this.point.stackTotal;}");

$chart->plotOptions->column->stacking = "normal";
$chart->plotOptions->column->dataLabels->enabled = 1;
$chart->plotOptions->column->dataLabels->color = new HighchartJsExpr(
    "(Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'");

$chart->series[] = array(
    'name' => "John",
    'data' => array(
        5,
        3,
        4,
        7,
        2
    )
);

$chart->series[] = array(
    'name' => "Jane",
    'data' => array(
        2,
        2,
        3,
        2,
        1
    )
);

$chart->series[] = array(
    'name' => "Joe",
    'data' => array(
        3,
        4,
        4,
        2,
        5
    )
);
?>

    <title>Stacked column</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <?php $chart->printScripts(); ?>


text:
This article provides an introduction to StackTracer for developers and system/server administrators. By reading it, you learn:

* What StackTracer is and the value it provides to troubleshooting your applications
* How to capture traces of any .net application running in production
* How to analyze the trace files and find the root cause of issue

#What is StackTracer

A tool that captures and analyzes stack trace samples captured at fixed intervals from any .net CLR process.

The Stacktracer is a console application attaches using the debugengine Interface and works with any .net process; no access to application source code is necessary,
no library modifications are needed, and there is no run-time instrumentation of CLR code. Configuration
options given at start of command line to specify the interval for stack trace and number of samples.Current implementation include output generation in xml/xslt for viewing the most recent stack traces. The performance impact of the stacktracer is minimal: less than a 8% increase in total elapsed time for a
set of standard benchmarks. Future plans include GUI, better filtering capabilities in analysis.

##Highlights

>*	800 kb single exe file(no installation required) with only dependency of .net framework 4.0 client profile.
>*	Captures stack trace of any .net process Windows forms ,WPF, asp.net you name it.
>*	No need of any symbol files.
>*	You can troubleshoot applications written in .net framework 2.0 to 4.5
>*	Target 32 bit and 64 bit process.
>*	View traces in browser. (inspired from IIS FREB)
>*	Intuitive timeline view to filter out unwanted stacks/threads.
>*	Very easy to troubleshoot Hang or High CPU issues on production enviroments.
>*	Less overhead on the running process,so you can troubleshoot slow performance issues which are less than 5 seconds .

##Limitations

>*	Needs .NET framework 4.0
>*	Will not show any native stack information.
>*	That means if the hang is due to GC, this may not help you.

##Downloads

    ID	Category	Bitness

    1	Azure Websites	x86  |  x64

    2	.NET Process	x86  | x64

---------------------------------------------------------------------------------------------------------------


text:
package service

import (
	"context"
	"errors"
	"strconv"
	"time"

	accrpc "go-common/app/service/main/account/rpc/client"
	"go-common/app/service/main/spy/conf"
	"go-common/app/service/main/spy/dao"
	"go-common/app/service/main/spy/model"
	"go-common/library/log"
	"go-common/library/stat/prom"
)

const (
	_score = 100
)

// Service biz service def.
type Service struct {
	c              *conf.Config
	dao            *dao.Dao
	missch         chan func()
	scorech        chan func()
	infomissch     chan func()
	spyConfig      map[string]interface{}
	configLoadTick time.Duration
	promBaseScore  *prom.Prom
	promEventScore *prom.Prom
	promBlockInfo  *prom.Prom
	accRPC         *accrpc.Service3
	allEventName   map[int64]string
	loadEventTick  time.Duration
}

// New new a Service and return.
func New(c *conf.Config) (s *Service) {
	s = &Service{
		c:              c,
		dao:            dao.New(c),
		missch:         make(chan func(), 10240),
		scorech:        make(chan func(), 10240),
		infomissch:     make(chan func(), 10240),
		spyConfig:      make(map[string]interface{}),
		configLoadTick: time.Duration(c.Property.ConfigLoadTick),
		promBaseScore:  prom.New().WithCounter("spy_basescore", []string{"name"}),
		promEventScore: prom.New().WithCounter("spy_eventscore", []string{"name"}),
		promBlockInfo:  prom.New().WithCounter("spy_block_info", []string{"name"}),
		accRPC:         accrpc.New3(c.RPC.Account),
		allEventName:   make(map[int64]string),
		loadEventTick:  time.Duration(c.Property.LoadEventTick),
	}
	if err := s.loadSystemConfig(); err != nil {
		panic(err)
	}
	s.loadeventname()

	go s.missproc()
	go s.infomissproc()
	go s.loadconfigproc()
	go s.loadeventproc()
	go s.updatescoreproc()
	return s
}

// Ping check dao health.
func (s *Service) Ping(c context.Context) (err error) {
	return s.dao.Ping(c)
}

// Close close all dao.
func (s *Service) Close() {
	s.dao.Close()
}

func (s *Service) missproc() {
	defer func() {
		if x := recover(); x != nil {
			log.Error("service.missproc panic(%v)", x)
			go s.missproc()
			log.Info("service.missproc recover")
		}
	}()
	for {
		f := <-s.missch
		f()
	}
}

func (s *Service) mission(f func()) {
	defer func() {
		if x := recover(); x != nil {
			log.Error("service.mission panic(%v)", x)
		}
	}()
	select {
	case s.missch <- f:
	default:
		log.Error("service.missproc chan full")
	}
}

func (s *Service) updatescoreproc() {
	defer func() {
		if x := recover(); x != nil {
			log.Error("service.updatescoreproc panic(%v)", x)
			go s.updatescoreproc()
			log.Info("service.updatescoreproc recover")
		}
	}()
	for {
		f := <-s.scorech
		f()
	}
}

func (s *Service) updatescore(f func()) {
	defer func() {
		if x := recover(); x != nil {
			log.Error("service.updatescore panic(%v)", x)
		}
	}()
	select {
	case s.scorech <- f:
	default:
		log.Error("service.updatescore chan full")
	}
}

func (s *Service) infomissproc() {
	defer func() {
		if x := recover(); x != nil {
			log.Error("service.infomissproc panic(%v)", x)
			go s.infomissproc()
			log.Info("service.infomissproc recover")
		}
	}()
	for {
		f := <-s.infomissch
		f()
	}
}

func (s *Service) infomission(f func()) {
	defer func() {
		if x := recover(); x != nil {
			log.Error("service.infomission panic(%v)", x)
		}
	}()
	select {
	case s.infomissch <- f:
	default:
		log.Error("service.infomissch chan full")
	}
}

func (s *Service) loadconfigproc() {
	defer func() {
		if x := recover(); x != nil {
			log.Error("service.loadconfig panic(%v)", x)
		}
	}()
	for {
		time.Sleep(s.configLoadTick)
		s.loadSystemConfig()
	}
}

func (s *Service) loadSystemConfig() (err error) {
	var (
		cdb map[string]string
	)
	cdb, err = s.dao.Configs(context.TODO())
	if err != nil {
		log.Error("sys config db get data err(%v)", err)
		return
	}
	if len(cdb) == 0 {
		err = errors.New("sys config no data")
		return
	}
	cs := make(map[string]interface{}, len(cdb))
	for k, v := range cdb {
		switch k {
		case model.LimitBlockCount:
			t, err1 := strconv.ParseInt(v, 10, 64)
			if err1 != nil {
				log.Error("sys config err(%s,%v,%v)", model.LimitBlockCount, t, err1)
				err = err1
				return
			}
			cs[k] = t
		case model.LessBlockScore:
			tmp, err1 := strconv.ParseInt(v, 10, 8)
			if err1 != nil {
				log.Error("sys config err(%s,%v,%v)", model.LessBlockScore, tmp, err1)
				err = err1
				return
			}
			cs[k] = int8(tmp)
		case model.AutoBlock:
			tmp, err1 := strconv.ParseInt(v, 10, 8)
			if err1 != nil {
				log.Error("sys config err(%s,%v,%v)", model.AutoBlock, tmp, err1)
				err = err1
				return
			}
			cs[k] = int8(tmp)
		default:
			cs[k] = v
		}
	}
	s.spyConfig = cs
	log.Info("loadSystemConfig success(%v)", cs)
	return
}

//Config get config.
func (s *Service) Config(key string) (interface{}, bool) {
	if s.spyConfig == nil {
		return nil, false
	}
	v, ok := s.spyConfig[key]
	return v, ok
}

func (s *Service) loadeventname() (err error) {
	var (
		c  = context.Background()
		es []*model.Event
	)
	es, err = s.dao.AllEvent(c)
	if err != nil {
		log.Error("loadeventname allevent error(%v)", err)
		return
	}
	tmp := make(map[int64]string, len(es))
	for _, e := range es {
		tmp[e.ID] = e.NickName
	}
	s.allEventName = tmp
	log.Info("loadeventname (%v) load success", tmp)
	return
}

func (s *Service) loadeventproc() {
	for {
		time.Sleep(s.loadEventTick)
		s.loadeventname()
	}
}


text:
set -e # We want any sub commands in here to fail the whole script.

# Any commands that should be run after the deb has been removed

ret=false
getent passwd $1 >/dev/null 2>&1 && ret=true

if $ret; then
    deluser django-readonly
else
    echo "User already removed."
fi


text:
NS_ASSUME_NONNULL_BEGIN

@interface NCDBDgmppItemRequirements (CoreDataProperties)

@property (nonatomic) float calibration;
@property (nonatomic) float cpu;
@property (nonatomic) float powerGrid;
@property (nullable, nonatomic, retain) NCDBDgmppItem *item;

@end

NS_ASSUME_NONNULL_END


text:
var foo = (function (exports,external) {
	'use strict';

	exports.q = external.p;
	exports.p = external.default;

	return exports;

}({},external));


text:
package main

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestCreateDefaultConfig(t *testing.T) {
	// serverConfig should be initialized by testsSetup function
	if assert.NotNil(t, serverConfig, "server configuration is expected") {
		assert.Equal(t, defaultDatabaseType, serverConfig.DbType, "wrong db type")
		assert.Equal(t, defaultServicePort, serverConfig.ServerPort, "wrong server port")
		assert.Equal(t, initBasketCapacity, serverConfig.InitCapacity, "wrong initial capacity")
		assert.Equal(t, maxBasketCapacity, serverConfig.MaxCapacity, "wrong max capacity")
		assert.Equal(t, defaultPageSize, serverConfig.PageSize, "wrong page size")
		assert.Equal(t, "./baskets.db", serverConfig.DbFile, "wrong DB file location")
		assert.NotEmpty(t, serverConfig.MasterToken, "expected randomly generated master token")
	}
}

func TestArrayFlags(t *testing.T) {
	var flags arrayFlags
	flags.Set("123")
	flags.Set("abc")
	flags.Set("xyz")
	flags.Set("abc")

	assert.Equal(t, "123,abc,xyz,abc", flags.String(), "unexpected list of flags")
}

func TestNormalizePrefix(t *testing.T) {
	assert.Empty(t, normalizePrefix(""), "expected empty prefix after normalization")
	assert.Equal(t, "/xyz", normalizePrefix("/xyz"), "unexpected result of normalization")
	assert.Equal(t, "/abc", normalizePrefix("abc"), "unexpected result of normalization")
	assert.Equal(t, "/services/baskets", normalizePrefix("services/baskets"), "unexpected result of normalization")
	assert.Equal(t, "/abc/def/ghi", normalizePrefix("/abc/def/ghi"), "unexpected result of normalization")
}


text:
package org.zstack.header.configuration;

import org.zstack.header.message.APIMessage;

/**
 */
public class APIGenerateApiTypeScriptDefinitionMsg extends APIMessage {
    private String outputPath;

    public String getOutputPath() {
        return outputPath;
    }

    public void setOutputPath(String outputPath) {
        this.outputPath = outputPath;
    }

    public static APIGenerateApiTypeScriptDefinitionMsg __example__() {
        APIGenerateApiTypeScriptDefinitionMsg msg = new APIGenerateApiTypeScriptDefinitionMsg();

        return msg;
    }

}


text:
var router = require('express').Router(),
    fs = require('fs'),
    Application = require('../models/application');

module.exports = function (passport) {
    router.route('/admin')
        .get(passport.authenticate('basic', {session: false}), function (req, res, next) {
            Application.find({}, function (err, models) {
                if (err) {
                    return next(err);
                }
                var applications = [];
                for (var i = 0; i < models.length; i++) {
                    var app = {
                        id: models[i].id,
                        name: models[i].name,
                        platform: models[i].platform,
                        shortcuts: models[i].shortcuts
                    };
                    applications.push(app);
                }
                res.render('./admin/admin', {
                    title: 'Admin Panel',
                    applications: applications
                });
            });
        });

    router.route('/admin/edit/:id')
        .get(passport.authenticate('basic', {session: false}), function (req, res, next) {
            Application.findOne({_id: req.params.id}, function (err, model) {
                if (err) {
                    return next(err);
                }
                var app = {
                    id: model.id,
                    name: model.name,
                    platform: model.platform,
                    shortcuts: model.shortcuts
                };
                res.render('./admin/edit', {
                    title: 'Edit Application',
                    application: app
                });
            });
        });

    router.route('/admin/upload')
        .all(passport.authenticate('basic', {session: false}))
        .post(function (req, res, next) {
            try {
                var data = JSON.parse(req.files.app_shortcuts.buffer);
                Application.create(data, function (err, data) {
                    if (err) {
                        res.status(500).send(err);
                    }
                    res.redirect('back')
                });
            }
            catch (ex) {
                res.status(400).send(ex);
            }
        });
    return router;
};


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <!--PlaybackActivity-->
    <dimen name="fragment_palyback_album_art_size">250dp</dimen>

    <!--PlaybackFragment-->
    <dimen name="fragment_playback_top_bottom_padding">20dp</dimen>
    <dimen name="fragment_playback_seek_bar_time__text_size">10sp</dimen>

    <!--TracksBrowserFragment row-->
    <dimen name="row_album_art_size">50dp</dimen>

    <!--Notification-->
    <dimen name="large_icon_height">64dp</dimen>
    <dimen name="large_icon_width">64dp</dimen>

    <dimen name="new_playlist_edit_text_width">70dp</dimen>

    <dimen name="albums_grid_view_spacing">1dp</dimen>

    <dimen name="navigation_view_image_height">150dp</dimen>

    <dimen name="toolbar_progressbar_height">1dp</dimen>

    <dimen name="list_divider_height">0.1dp</dimen>

    <dimen name="check_circle_padding">7dp</dimen>

    <dimen name="list_row_without_art_height">50dp</dimen>

    <dimen name="dock_playback_height">50dp</dimen>
    <dimen name="dock_playback_progress_height">2dp</dimen>

    <dimen name="seekbar_height">2dp</dimen>
    <dimen name="seekbar_thumb_inner">12dp</dimen>

    <dimen name="font_size">14sp</dimen>

    <dimen name="equalizer_margin">5dp</dimen>
    <dimen name="text_view_padding">5dp</dimen>
    <dimen name="fragment_playback_left_right_padding">5dp</dimen>

    <dimen name="default_padding">3dp</dimen>
    <dimen name="default_margin">3dp</dimen>

    <dimen name="dialog_rename_padding">20dp</dimen>

    <dimen name="dialog_min_width">500dp</dimen>
    <dimen name="dialog_title_text_size">18sp</dimen>
    <dimen name="dialog_text_size">15sp</dimen>
    <dimen name="dialog_padding">5dp</dimen>
    <dimen name="dialog_body_up_bottom_padding">10dp</dimen>

    <dimen name="album_art_column_width">150dp</dimen>
    <dimen name="padding_small">8dp</dimen>
    <dimen name="margin_medium">16dp</dimen>
    <dimen name="padding_medium">16dp</dimen>
    <dimen name="cardview_elevation">6dp</dimen>
    <dimen name="height_list_item">72dp</dimen>
    <dimen name="margin_small">8dp</dimen>
    <dimen name="margin_large">16dp</dimen>
</resources>


text:
"""Package provides template filters management
"""
import string
from .context import resolve

class FilterManager(object):
    """Class used for filters manipulations
    """
    __slots__ = ('apply', 'filters', 'is_filter_exists', )

    def __init__(self):
        """Create new tag managet instance
        """
        super(FilterManager, self).__init__()
        self.filters = {}

    def is_filter_exists(self, name):
        """Check is filter exists
        """
        if name not in self.filters:
            raise Exception("Filter '%s' is not registered" % name)
        return self.filters[name]

    def register(self, filter):
        '''Register filter in manager
        '''
        self.filters[filter.__name__] = filter

    def apply(self, filter, value, args, arg_types, context):
        '''Apply filter to values
        '''
        filter_func = self.is_filter_exists(filter)
        new_args = []
        i = 0
        while i < len(args):
            new_args.append(arg_types[i] and args[i] or context[args[i]])
            i += 1
        return filter_func(value, *new_args)

filter_manager = FilterManager()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

class Sphere : Object3D
{
    public float size;

    public Vector3 position;

    private Material matC;

    private Mesh meshC;

    private Matrix transform;

    public Sphere(Panel3D _panel3D, Vector3 _position, float _size)
        : base(_panel3D)
    {

        position = _position;
        size = _size;

        meshC = Mesh.Sphere(device, size, 10, 10);

        CreateMaterial();
        CalculateAngle();
        CalculateTransform();
    }

    void CreateMaterial()
    {
        matC = new Material();
        matC.Ambient = Color.Blue; //on affecte au material qui va recouviri la sphere la couleur de la boules concernée
        matC.Diffuse = Color.Blue;// pareil pour la couleur diffuse
    }

    void CalculateTransform()
    {
        transform = Matrix.Multiply(Matrix.Identity, Matrix.Translation(position));
    }

    void CalculateAngle()
    {
        //Vector3 dir = new Vector3(0, 0, -1f);
        //axisRotation = productVect(dir, direction);
        //angle = (float)Math.Acos(productSca(dir, direction));
    }

    Vector3 productVect(Vector3 v1, Vector3 v2)
    {
        float X = v1.Y * v2.Z - v1.Z * v2.Y;
        float Y = v1.Z * v2.X - v1.X * v2.Z;
        float Z = v1.X * v2.Y - v1.Y * v2.X;
        return new Vector3(X, Y, Z);
    }

    float productSca(Vector3 v1, Vector3 v2)
    {
        return v1.X * v2.X + v1.Y * v2.Y + v1.Z * v2.Z;
    }

    public override void draw()
    {
        panel3D.activeLight(true);

        device.RenderState.FillMode = FillMode.Solid;

        device.Material = matC;
        device.Transform.World = transform;
        meshC.DrawSubset(0);

        panel3D.activeLight(false);
    }
}


text:
#ifndef V8NPObject_h
#define V8NPObject_h

#if PLATFORM(CHROMIUM)
#include <bindings/npruntime.h>
#else
#include "npruntime_internal.h"
#endif

#include <v8.h>

namespace WebCore {

// These functions can be replaced by normal JS operation.
// Getters
v8::Handle<v8::Value> npObjectNamedPropertyGetter(v8::Local<v8::String> name, const v8::AccessorInfo&);
v8::Handle<v8::Value> npObjectIndexedPropertyGetter(uint32_t index, const v8::AccessorInfo&);
v8::Handle<v8::Value> npObjectGetNamedProperty(v8::Local<v8::Object> self, v8::Local<v8::String> name);
v8::Handle<v8::Value> npObjectGetIndexedProperty(v8::Local<v8::Object> self, uint32_t index);

// Setters
v8::Handle<v8::Value> npObjectNamedPropertySetter(v8::Local<v8::String> name, v8::Local<v8::Value>, const v8::AccessorInfo&);
v8::Handle<v8::Value> npObjectIndexedPropertySetter(uint32_t index, const v8::AccessorInfo&);
v8::Handle<v8::Value> npObjectSetNamedProperty(v8::Local<v8::Object> self, v8::Local<v8::String> name, v8::Local<v8::Value>);
v8::Handle<v8::Value> npObjectSetIndexedProperty(v8::Local<v8::Object> self, uint32_t index, v8::Local<v8::Value>);

v8::Handle<v8::Value> npObjectInvokeDefaultHandler(const v8::Arguments&);

// Get a wrapper for a NPObject.
// If the object is already wrapped, the pre-existing wrapper will be returned. If the object is not wrapped, wrap it, and
// give V8 a weak reference to the wrapper which will cleanup when there are no more JS references to the object.
v8::Local<v8::Object> createV8ObjectForNPObject(NPObject*, NPObject* root);

// Tell V8 to forcibly remove an object.
// This is used at plugin teardown so that the caller can aggressively unload the plugin library. After calling this
// function, the persistent handle to the wrapper will be gone, and the wrapped NPObject will be removed so that it
// cannot be referred to.
void forgetV8ObjectForNPObject(NPObject*);

} // namespace WebCore

#endif // V8NPObject_h


text:
Sample application to demonstrate how easy it is to build realtime applications with [Kemal](https://github.com/sdogruyol/kemal) using WebSocket.

## Installation

```
git clone https://github.com/sdogruyol/kemal-chat
cd kemal-chat && shards install
crystal run src/kemal_chat.cr
```

## Usage

Go to `http://localhost:3000/` to see it in action.

![Kemal Chat Gif](/images/kemal-chat.gif)

## Contributing

1. Fork it ( https://github.com/sdogruyol/kemal-chat/fork )
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request

## Contributors

- [[sdogruyol]](https://github.com/sdogruyol) Sdogruyol - creator, maintainer


text:
<?php

namespace Bundles\StoreBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class RecipeAdmin extends Admin
{
    // Fields to be shown on create/edit forms
    protected function configureFormFields(FormMapper $formMapper)
    {
        $pictureFormField = ['label' => 'Изображение1',
                             'required' => false,
                             'data_class' => null];
        if ($this->getSubject()->getImage()) {
            $pictureFormField['help'] = '<img src="/' . $this->getSubject()->getImage() . '" class="admin-preview" />';}
        $formMapper
            ->add('title', 'text', array('label' => 'Post Title'))
            ->add('slug')
            ->add('is_active')
            ->add('imageFile', 'file',$pictureFormField)
            ->add('content') //if no type is specified, SonataAdminBundle tries to guess it
            ->add('category')
            ->add('features', 'sonata_type_model', array('expanded' => true, 'compound' => true, 'multiple' => true, 'label' => 'Выберите опции') )
        ;
    }

    // Fields to be shown on filter forms
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('title')
            ->add('slug')
        ;
    }

    // Fields to be shown on lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('title')
            ->add('category')
            ->add('is_active', null, array('editable' => true))
            ->add('slug')
            ->add('image', 'image')
            ->add('_action', 'actions', array('label' => 'Действия',
                'actions' => array(
                    'edit' => array(),
                    'delete' => array(),
                )
            ))
        ;
    }

    private function _processFiles($object) {
        if ($object->getImageFile() instanceof \Symfony\Component\HttpFoundation\File\File) {
            $object->setImage($this->_persistFile($object->getImageFile(), \Bundles\StoreBundle\Entity\Recipe::IMAGE_BASEPATH, true, $object->getImage()));
        }
    }

      public function prePersist($object) { //Чего делаем перед созданием?
        $this->_processFiles($object);
        parent::prePersist($object);
    }

    public function preUpdate($object) { //Чего делаем перед обновлением?
        $this->_processFiles($object, true);
        parent::preUpdate($object);
    }

    public function preRemove($object) { //Чего делаем перед удалением?
        if (is_file($object->getImage()))
            unlink($object->getImage());

        parent::preRemove($object);
    }

    protected function _persistFile(\Symfony\Component\HttpFoundation\File\File $file, $basepath, $update = false, $previous = '') {
        if ($update && is_file($previous)) {
            unlink($previous);
        }
        $filename = uniqid() . '.' . $file->guessExtension();
        $file->move($basepath, $filename);
        return $basepath . $filename;
    }
}


text:
<?php
/* @var $this AdminController */
/* @var Survey $oSurvey */
/* @var Quota $oQuota */
/* @var string $editUrl */
/* @var string $deleteUrl */
/* @var array $aQuotaItems */

?>
<?php if (Permission::model()->hasSurveyPermission($oSurvey->getPrimaryKey(), 'quotas','update')) { ?>
    <a href="<?php echo $editUrl; ?>" class="btn btn-default" data-toggle='tooltip' title='<?php eT("Edit"); ?>'>

<?php } ?>
<?php if (Permission::model()->hasSurveyPermission($oSurvey->getPrimaryKey(), 'quotas','delete')) { ?>
    <a data-href="<?php echo $deleteUrl; ?>" class="btn btn-default" data-toggle="modal" data-target="#confirmation-modal" data-tooltip="true" title="<?php eT("Delete");?>" >

<?php } ?>
<?php if (Permission::model()->hasSurveyPermission($oSurvey->getPrimaryKey(), 'quotas','update')) {
    echo CHtml::link(CHtml::tag('span', array(
        'class' => 'glyphicon glyphicon-ok-sign',
    ), ''
    ), array(
        'admin/validate',
        'sa'=>'quota',
        'sid'=>$oSurvey->getPrimaryKey(),
        'quota'=>$oQuota->getPrimaryKey(),
    ), array(
        'class'=>'btn btn-default',
        'title'=>sprintf(gT("Validation of quota %s"),$oQuota->name),
        'target'=>'dialog',
        'data-tooltip' => 'true'
    ));
}


text:
[![npm](https://img.shields.io/npm/v/stylelint-config-semantic.svg?style=flat-square)](https://www.npmjs.com/package/stylelint-config-semantic)
[![npm](https://img.shields.io/npm/dm/stylelint-config-semantic.svg?style=flat-square)](https://www.npmjs.com/package/stylelint-config-semantic)
[![Travis](https://img.shields.io/travis/rodoabad/stylelint-config-semantic.svg?style=flat-square)](https://travis-ci.org/rodoabad/stylelint-config-semantic)

# Semantic rules for your CSS

Code should always be written in such a way that makes it look like a single person wrote it, no matter how many people have contributed and that is the purpose of this set of rules powered by [stylelint](https://github.com/stylelint/stylelint).

## Installation

You need to have `stylelint` and this config as part of your `devDependencies`.

`npm i stylelint stylelint-config-semantic -D`

## Usage

### Load everything

To use all the rules all at once add `stylelint-config-semantic` to your `extends` property in `.stylelintrc`.

```json
{
  "extends": [
    "stylelint-config-semantic"
  ]
}
```

### Load a specific rule

Each rule for `stylelint-config-semantic` can be loaded individually if you only want to load a specific rule. They are all located in the `lib` folder.

Load the `color` and `general` rule set.

```json
{
  "extends": [
    "stylelint-config-semantic/lib/color",
    "stylelint-config-semantic/lib/general"
  ]
}
```

### Override specific rules

To override the rules set by `stylelint-config-semantic` you need to define your own rules and set them as you see fit.

```json
{
  "extends": [
    "stylelint-config-semantic"
  ],
  "rules": {
    "indentation": 2
  }
}
```


text:
#import <React/RCTEventEmitter.h>

@interface RCTKeyboardObserver : RCTEventEmitter

@end


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project default="doclava">

    <target name="doclava">
        <javadoc packagenames="com.caverock.androidsvg.*"
                 destdir="doc"
                 sourcepath="src"
                 docletpath="D:\Users\Paul\Development\Java\doclava-1.0.6\doclava-1.0.6.jar"
                 bootclasspath="${java.home}\lib\rt.jar,C:\Program Files (x86)\Android\android-sdk\platforms\android-16\android.jar">
            <doclet name="com.google.doclava.Doclava">
                <param name="-public"/>
                <!-- param name="-stubs" value="build/stubs" / -->
                <param name="-hdf"/>
                <param name="project.name"/>
                <param name="AndroidSVG"/>
                <!-- versioning -->
                <!--
                <param name="-since"/> <param name="doclava/previous.xml"/> <param name="v1" />
                <param name="-apiversion" value="v2"/>
                -->
                <!-- federation -->
                <param name="-federate"/>
                <param name="JDK"/>
                <param name="http://download.oracle.com/javase/6/docs/api/index.html?"/>
                <param name="-federationxml"/>
                <param name="JDK"/>
                <param name="http://doclava.googlecode.com/svn/static/api/openjdk-6.xml"/>
            </doclet>
        </javadoc>
    </target>

</project>


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 4.0.2
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package org.pjsip.pjsua2;

public class AudioMediaVector extends java.util.AbstractList<AudioMedia> implements java.util.RandomAccess {
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

  protected AudioMediaVector(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr(AudioMediaVector obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  @SuppressWarnings("deprecation")
  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        pjsua2JNI.delete_AudioMediaVector(swigCPtr);
      }
      swigCPtr = 0;
    }
  }

  public AudioMediaVector(AudioMedia[] initialElements) {
    this();
    reserve(initialElements.length);

    for (AudioMedia element : initialElements) {
      add(element);
    }
  }

  public AudioMediaVector(Iterable<AudioMedia> initialElements) {
    this();
    for (AudioMedia element : initialElements) {
      add(element);
    }
  }

  public AudioMedia get(int index) {
    return doGet(index);
  }

  public AudioMedia set(int index, AudioMedia e) {
    return doSet(index, e);
  }

  public boolean add(AudioMedia e) {
    modCount++;
    doAdd(e);
    return true;
  }

  public void add(int index, AudioMedia e) {
    modCount++;
    doAdd(index, e);
  }

  public AudioMedia remove(int index) {
    modCount++;
    return doRemove(index);
  }

  protected void removeRange(int fromIndex, int toIndex) {
    modCount++;
    doRemoveRange(fromIndex, toIndex);
  }

  public int size() {
    return doSize();
  }

  public AudioMediaVector() {
    this(pjsua2JNI.new_AudioMediaVector__SWIG_0(), true);
  }

  public AudioMediaVector(AudioMediaVector other) {
    this(pjsua2JNI.new_AudioMediaVector__SWIG_1(AudioMediaVector.getCPtr(other), other), true);
  }

  public long capacity() {
    return pjsua2JNI.AudioMediaVector_capacity(swigCPtr, this);
  }

  public void reserve(long n) {
    pjsua2JNI.AudioMediaVector_reserve(swigCPtr, this, n);
  }

  public boolean isEmpty() {
    return pjsua2JNI.AudioMediaVector_isEmpty(swigCPtr, this);
  }

  public void clear() {
    pjsua2JNI.AudioMediaVector_clear(swigCPtr, this);
  }

  public AudioMediaVector(int count, AudioMedia value) {
    this(pjsua2JNI.new_AudioMediaVector__SWIG_2(count, AudioMedia.getCPtr(value), value), true);
  }

  private int doSize() {
    return pjsua2JNI.AudioMediaVector_doSize(swigCPtr, this);
  }

  private void doAdd(AudioMedia x) {
    pjsua2JNI.AudioMediaVector_doAdd__SWIG_0(swigCPtr, this, AudioMedia.getCPtr(x), x);
  }

  private void doAdd(int index, AudioMedia x) {
    pjsua2JNI.AudioMediaVector_doAdd__SWIG_1(swigCPtr, this, index, AudioMedia.getCPtr(x), x);
  }

  private AudioMedia doRemove(int index) {
    long cPtr = pjsua2JNI.AudioMediaVector_doRemove(swigCPtr, this, index);
    return (cPtr == 0) ? null : new AudioMedia(cPtr, false);
  }

  private AudioMedia doGet(int index) {
    long cPtr = pjsua2JNI.AudioMediaVector_doGet(swigCPtr, this, index);
    return (cPtr == 0) ? null : new AudioMedia(cPtr, false);
  }

  private AudioMedia doSet(int index, AudioMedia val) {
    long cPtr = pjsua2JNI.AudioMediaVector_doSet(swigCPtr, this, index, AudioMedia.getCPtr(val), val);
    return (cPtr == 0) ? null : new AudioMedia(cPtr, false);
  }

  private void doRemoveRange(int fromIndex, int toIndex) {
    pjsua2JNI.AudioMediaVector_doRemoveRange(swigCPtr, this, fromIndex, toIndex);
  }

}


text:
#ifndef VG_FUNNEL_HPP_INCLUDED
#define VG_FUNNEL_HPP_INCLUDED

#include <string>
#include <vector>
#include <unordered_map>
#include <cassert>
#include <cmath>
#include <functional>
#include <iostream>
#include <limits>
#include <vg/vg.pb.h>
#include "annotation.hpp"

/**
 * \file funnel.hpp
 * Contains the Funnel class, for recording the history of complex multi-stage transformations of sets of results.
 */

namespace vg {

using namespace std;

/**
 * Represents a record of an invocation of a pipeline for an input.
 *
 * Tracks the history of "lines" of data "item" provenance through a series of
 * "stages", containing a series of "filters".
 *
 * Lines are "introduced", and "project" from earlier stages to later stages,
 * possibly "expanding" or "merging", until they "fail" a filter or reach the
 * final stage. At each stage, items occur in a linear order and are identified
 * by index.
 *
 * An item may be a "group", with a certain size.
 *
 * We also can assign scores to items at a stage.
 */
class Funnel {

public:
    /// Start processing the given named input.
    /// Name must not be empty.
    /// No stage or substage will be active.
    void start(const string& name);

    /// Stop processing the given named input.
    /// All stages and substages are stopped.
    void stop();

    /// Start the given stage, and end all previous stages and substages.
    /// Name must not be empty.
    /// Multiple stages with the same name will be coalesced.
    void stage(const string& name);

    /// Stop the current stage.
    void stage_stop();

    /// Start the given substage, nested insude the current stage. End all previous substages.
    /// Substages within a stage may repeat and are coalesced.
    /// Name must not be empty.
    void substage(const string& name);

    /// Stop the current substage.
    void substage_stop();

    /// Start processing the given item coming from the previous stage.
    void processing_input(size_t prev_stage_item);

    /// Stop processing an item from the previous stage.
    void processed_input();

    /// Start producing the given output item, whether it has been projected yet or not.
    void producing_output(size_t item);

    /// Stop producing an output item.
    void produced_output();

    /// Introduce the given number of new items, starting their own lines of provenance (default 1).
    void introduce(size_t count = 1);

    /// Expand the given item from the previous stage into the given number of new items at this stage.
    void expand(size_t prev_stage_item, size_t count);

    /// Merge all the given item indexes from the previous stage into a new item at this stage.
    /// The new item will be a group, sized according to the number of previous items merged.
    template<typename Iterator>
    void merge_group(Iterator prev_stage_items_begin, Iterator prev_stage_items_end);

    /// Project a single item from the previous stage to a single non-group item at this stage.
    void project(size_t prev_stage_item);

    /// Project a single item from the previous stage to a new group item at the current stage, with the given size.
    void project_group(size_t prev_stage_item, size_t group_size);

    /// Fail the given item from the previous stage on the given filter and do not project it through to this stage.
    /// Items which do not fail a filter must pass the filter and be projected to something.
    /// The filter name must survive the funnel, because a pointer to it will be stored.
    /// Allows a statistic for the filtered-on value for the failing item to be recorded.
    void fail(const char* filter, size_t prev_stage_item, double statistic = nan(""));

    /// Pass the given item from the previous stage through the given filter at this stage.
    /// Items which do not pass a filter must fail it.
    /// All items which pass filters must do so in the same order.
    /// The filter name must survive the funnel, because a pointer to it will be stored.
    /// Allows a statistic for the filtered-on value for the passing item to be recorded.
    void pass(const char* filter, size_t prev_stage_item, double statistic = nan(""));

    /// Assign the given score to the given item at the current stage.
    void score(size_t item, double score);

    /// Tag the given item as "correct" at the current stage. Future items that
    /// derive from it will also be tagged as correct.
    void tag_correct(size_t item);

    /// Return true if the given item at this stage is tagged correct, or
    /// descends from an item that was tagged correct.
    bool is_correct(size_t item) const;

    /// Return true if the given item at the previous stage is tagged correct, or
    /// descends from an item that was tagged correct.
    bool was_correct(size_t prev_stage_item) const;

    /// Get the name of the most recent stage that had a correct-tagged item
    /// survive into it, or "none" if no items were ever tagged correct.
    string last_correct_stage() const;

    /// Get the index of the most recent item created in the current stage.
    size_t latest() const;

    /// Call the given callback with stage name, and vector of result item sizes at that stage, for each stage.
    void for_each_stage(const function<void(const string&, const vector<size_t>&)>& callback) const;

    /// Represents the performance of a filter, for either item counts or total item sizes.
    /// Note that passing_correct and failing_correct will always be 0 if nothing is tagged correct.
    struct FilterPerformance {
        size_t passing = 0;
        size_t failing = 0;
        size_t passing_correct = 0;
        size_t failing_correct = 0;
    };

    /// Call the given callback with stage name, filter name, performance
    /// report for items, performance report for total size of items, values
    /// for correct items for the filter statistic, and values for incorrect
    /// (or merely not known-correct) items for the filter statistic.
    /// Runs the callback for each stage and filter, in order. Only includes
    /// filters that were actually passed or failed by any items.
    void for_each_filter(const function<void(const string&, const string&,
        const FilterPerformance&, const FilterPerformance&,
        const vector<double>&, const vector<double>&)>& callback) const;

    /// Dump information from the Funnel as a dot-format Graphviz graph to the given stream.
    /// Illustrates stages and provenance.
    void to_dot(ostream& out);

    /// Set an alignments annotations with the number of results at each stage
    /// if annotate_correctness is true, also annotate the alignment with the
    /// number of correct results at each stage. This assumes that we've been
    /// tracking correctness all along
    void annotate_mapped_alignment(Alignment& aln, bool annotate_correctness);

protected:

    /// What's the name of the funnel we start()-ed. Will be empty if nothing is running.
    string funnel_name;

    /// What's the name of the current stage? Will be empty if no stage is running.
    string stage_name;

    /// What's the name of the current substage? Will be empty if no substage is running.
    string substage_name;

    /// What's the current prev-stage input we are processing?
    /// Will be numeric_limits<size_t>::max() if none.
    size_t input_in_progress = numeric_limits<size_t>::max();

    /// what's the current current-stage output we are generating?
    /// Will be numeric_limits<size_t>::max() if none.
    size_t output_in_progress = numeric_limits<size_t>::max();

    // Now members we need for provenance tracking

    /// Represents an Item whose provenance we track
    struct Item {
        size_t group_size = 0;
        double score = 0;
        /// Is this item tagged as correct, or a descendant of a tagged item?
        bool correct = false;
        /// What previous stage items were combined to make this one, if any?
        vector<size_t> prev_stage_items = {};
        /// What filters did the item pass at this stage, if any?
        vector<const char*> passed_filters = {};
        /// And what statistics did they have (or NaN)?
        vector<double> passed_statistics = {};
        /// What filter did the item finally fail at at this stage, if any?
        const char* failed_filter = nullptr;
        /// And what statistic did it fail with (or NaN)?
        double failed_statistic = nan("");
    };

    /// Represents a Stage which is a series of Items, which track their own provenance.
    struct Stage {
        string name;
        vector<Item> items;
        /// How many of the items were actually projected?
        /// Needed because items may need to expand to hold information for items that have not been projected yet.
        size_t projected_count = 0;
        /// Does this stage contain any items tagged as correct?
        bool has_correct = false;
    };

    /// Ensure an item with the given index exists in the current stage and return a reference to it.
    /// We need to do it this way because we might save a production duration before an item is really projected.
    /// The items of the current stage should only be modified through this.
    /// Note that you do *not* need to create an item in order to get it.
    Item& get_item(size_t index);

    /// Create a new item in the current stage and get its index.
    /// Advances the projected count counter.
    size_t create_item();

    /// Rercord all the stages, including their names and item provenance.
    /// Handles repeated stages.
    vector<Stage> stages;
};

template<typename Iterator>
void Funnel::merge_group(Iterator prev_stage_items_begin, Iterator prev_stage_items_end) {
    // There must be a prev stage to merge from
    assert(stages.size() > 1);
    auto& prev_stage = stages[stages.size() - 2];

    // Make a new item to hold all the given items.
    size_t index = create_item();

    for (Iterator& i = prev_stage_items_begin; i != prev_stage_items_end; ++i) {
        // For each prev stage item (not copying the iterator)
        size_t prev_stage_item = *i;

        // Make sure it existed
        assert(prev_stage.items.size() > prev_stage_item);

        // Record the dependency
        get_item(index).prev_stage_items.push_back(prev_stage_item);

        if (prev_stage.items[prev_stage_item].correct) {
            // Tag the new item correct if it came from something correct.
            tag_correct(index);
        }
    }

    // Update its size
    get_item(index).group_size = get_item(index).prev_stage_items.size();
}

}

#endif


text:
package it.polito.ai.polibox.web.controllers.inputform.validation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import it.polito.ai.polibox.web.controllers.inputform.NotificationOption;
import it.polito.ai.polibox.web.controllers.inputform.NotificationOptions;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class NotificationOptionsValidator implements Validator{
	private Matcher numberMatcher;
	private Pattern numberPattern;
	private static final String NUMBER_PATTERN="^([0-9]+)$";
	public NotificationOptionsValidator() {
		numberPattern=Pattern.compile(NUMBER_PATTERN);
	}

	public boolean supports(Class<?> clazz) {
		return NotificationOptions.class.equals(clazz) || NotificationOption.class.equals(clazz);
	}

	public void validate(Object target, Errors errors) {
		NotificationOption[] list=new NotificationOption[1];
		if(target instanceof NotificationOptions)
			list=((NotificationOptions) target).getList();
		else if(target instanceof NotificationOption)
			list[0]=(NotificationOption) target;
		int i;
		for(i=0;i<list.length;i++){
			numberMatcher=numberPattern.matcher(list[i].getCode());
			if(!numberMatcher.matches())
				errors.reject("code.invalid");
		}

	}

}


text:
Copyright iDoulist Team 2015

input test 20150505


text:
.include <bsd.own.mk>

SUBDIR=	mount_psshfs mount_sysctlfs

.include <bsd.subdir.mk>


text:
package com.orm.androrm.migration;

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

import android.content.Context;

import com.orm.androrm.Model;
import com.orm.androrm.field.DatabaseField;
import com.orm.androrm.field.ManyToManyField;

/**
 * @author Philipp Giese
 *
 */
public class Migrator<T extends Model> {

	private Class<T> mModel;
	private List<Migratable<T>> mMigrations;

	public Migrator(Class<T> model) {
		mModel = model;
		mMigrations = new ArrayList<Migratable<T>>();
	}

	public void addField(String name, DatabaseField<?> field) {
		AddFieldMigration<T> migration = new AddFieldMigration<T>(name, field);

		mMigrations.add(migration);
	}

	public <R extends Model> void addField(String name, ManyToManyField<T, R> field) {
		// Tables for M2M relations are created anyway. This stub is only here,
		// so that users aren't confused, if they try to add a M2M field. We let
		// them believe "they" did it :)
		return;
	}

	public void renameModel(String old, Class<? extends Model> updated) {
		RenameModelMigration<T> migration = new RenameModelMigration<T>(old);

		mMigrations.add(migration);
	}

	public void renameRelation(String old, Class<? extends Model> updated) {
		RenameRelationMigration<T> migration = new RenameRelationMigration<T>(old);

		mMigrations.add(migration);
	}

	public void migrate(Context context) {
		for(Migratable<T> migration : mMigrations) {
			if(migration.execute(context, mModel)) {
				Migration.create(mModel, migration).save(context);
			}
		}
	}

}


text:
<?php

namespace Sparky7\Orm;

use Sparky7\Orm\Qb\MongoDB;
use Exception;
use OuterIterator;

/**
 * Collection class.
 */
abstract class Collection implements OuterIterator
{
    /*
     * OuterIterator.
     */

    private $Iterator;

    /*
     * Other properties.
     */

    private $QB;

    /*
     * DB variables.
     */

    protected $MongoDB;
    protected $collection;
    protected $entity;

    /**
     * Call method.
     *
     * @param string $method    Method name
     * @param array  $arguments Arguments
     *
     * @return any
     */
    final public function __call($method, array $arguments = null)
    {
        if (is_callable([$this->QB, $method])) {
            if ($method === 'find') {
                $this->Iterator = call_user_func_array([$this->QB, $method], $arguments);
            } else {
                return call_user_func_array([$this->QB, $method], $arguments);
            }
        }

        return false;
    }

    /**
     * Define events.
     */
    public function events()
    {
        return [];
    }

    /**
     * Init class.
     */
    final public function init()
    {
        // Select Query Builder
        if (get_class($this->MongoDB) === 'MongoDB\Database') {
            $this->QB = new Qb\MongoDB($this->MongoDB, $this->collection);
        } elseif (get_class($this->MongoDB) === 'MongoDB') {
            $this->QB = new Qb\Mongo($this->MongoDB, $this->collection);
        } else {
            throw new Exception('Invalid mongo database');
        }

        // Register events
        if (method_exists($this, 'events')) {
            foreach ($this->events() as $key => $value) {
                $this->QB->on($key, $value);
            }
        }
    }

    /**
     * Create a new empty entity.
     *
     * @return object Entity
     */
    final public function entity()
    {
        return new $this->entity($this->MongoDB->{$this->collection}, []);
    }

    /**
     * Exports collection into an array.
     *
     * @return array Collection data
     */
    public function toArray()
    {
        $collection = [];

        foreach ($this as $Entity) {
            $collection[] = $Entity->toArray();
        }

        return $collection;
    }

    /**
     * Get Next.
     */
    public function getNext()
    {
        if (get_class($this->MongoDB) === 'MongoDB') {
            $this->next();
        }

        $data = $this->current();

        return (is_null($data)) ? $this->entity() : $data;
    }

    /**
     * Get the current value.
     *
     * @return mixed
     */
    public function current()
    {
        if (is_null($this->Iterator)) {
            return;
        }

        $data = $this->Iterator->current();

        if (is_null($data)) {
            return;
        }

        return new $this->entity($this->MongoDB->{$this->collection}, (array) $data);
    }

    /**
     * Get key.
     *
     * @return int Iterator key
     */
    final public function key()
    {
        return $this->Iterator->key();
    }

    /**
     * Increments iterator key.
     *
     * @return bool
     */
    final public function next()
    {
        return $this->Iterator->next();
    }

    /**
     * Decrements iterator key.
     *
     * @return bool
     */
    final public function rewind()
    {
        return $this->Iterator->rewind();
    }

    /**
     * Check to see if current key is valid.
     *
     * @return bool
     */
    final public function valid()
    {
        return $this->Iterator->valid();
    }

    /**
     * Get Inner Iterator.
     *
     * @return [type] Iterator
     */
    final public function getInnerIterator()
    {
        return $this->Iterator;
    }
}


text:
#include <cpc/terminal.h>

#include <assert.h>
#ifndef NDEBUG
	#include <stdbool.h>

	static bool cpc_terminal_initialized = false;
#endif

#ifdef _WIN32
	static cpc_terminal_style_t cpc_terminal_default_style;

	void cpc_terminal_init(void) {
		assert(!cpc_terminal_initialized);
		#ifndef NDEBUG
			cpc_terminal_initialized = true;
		#endif
		CONSOLE_SCREEN_BUFFER_INFO info;
		GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
		cpc_terminal_default_style = info.wAttributes;
	}

	void cpc_terminal_apply_style(cpc_terminal_style_t style) {
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), style);
	}

	void cpc_terminal_reset_style(void) {
		assert(cpc_terminal_initialized);
		cpc_terminal_apply_style(cpc_terminal_default_style);
	}

	void cpc_terminal_set_cursor_pos(unsigned short x, unsigned short y) {
		COORD coord;
		coord.X = (SHORT)x;
		coord.Y = (SHORT)y;
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	}

	void cpc_terminal_get_size(unsigned short *CPC_RESTRICT width, unsigned short *CPC_RESTRICT height) {
		CPC_ASSERT(width != NULL);
		CPC_ASSERT(height != NULL);
		CPC_ASSERT(width != height);
		CONSOLE_SCREEN_BUFFER_INFO info;
		const BOOL result = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
		CPC_ASSERT(!result || info.dwSize.X >= 0);
		CPC_ASSERT(!result || info.dwSize.Y >= 0);
		*width = (unsigned short)!!result * (unsigned short)info.dwSize.X;
		*height = (unsigned short)!!result * (unsigned short)info.dwSize.Y;
	}
#else
	#include <stdio.h>
	#include <sys/ioctl.h>

	void cpc_terminal_init(void) {
		assert(!cpc_terminal_initialized);
		#ifndef NDEBUG
			cpc_terminal_initialized = true;
		#endif
	}

	void cpc_terminal_apply_style(cpc_terminal_style_t style) {
		CPC_ASSERT(style != NULL);
		const int result = fputs(style, stdout);
		CPC_ASSERT(result >= 0);
	}

	void cpc_terminal_reset_style(void) {
		assert(cpc_terminal_initialized);
		cpc_terminal_apply_style("\x1B[0m");
	}

	void cpc_terminal_set_cursor_pos(unsigned short x, unsigned short y) {
		const int result = printf("\033[<%hu>;<%hu>H", x, y);
		CPC_ASSERT(result >= 0);
	}

	void cpc_terminal_get_size(unsigned short *CPC_RESTRICT width, unsigned short *CPC_RESTRICT height) {
		CPC_ASSERT(width != NULL);
		CPC_ASSERT(height != NULL);
		CPC_ASSERT(width != height);
		struct winsize window_size;
		const int result = ioctl(STDOUT_FILENO, TIOCGWINSZ, &window_size);
		*width = (result == 0) * window_size.ws_col;
		*height = (result == 0) * window_size.ws_row;
	}
#endif


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

<title>Untitled Document: Deriving a New Hash Table Type</title>

<meta name="description" content="Untitled Document: Deriving a New Hash Table Type">
<meta name="keywords" content="Untitled Document: Deriving a New Hash Table Type">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="BFD-Index.html#BFD-Index" rel="index" title="BFD Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Hash-Tables.html#Hash-Tables" rel="up" title="Hash Tables">
<link href="Define-the-Derived-Structures.html#Define-the-Derived-Structures" rel="next" title="Define the Derived Structures">
<link href="Traversing-a-Hash-Table.html#Traversing-a-Hash-Table" rel="prev" title="Traversing a Hash Table">

Previous: Traversing a Hash Table, Up: Hash Tables   [Contents][Index]

2.18.4 Deriving a new hash table type

Many uses of hash tables want to store additional information
which each entry in the hash table.  Some also find it
convenient to store additional information with the hash table
itself.  This may be done using a derived hash table.

Since C is not an object oriented language, creating a derived
hash table requires sticking together some boilerplate
routines with a few differences specific to the type of hash
table you want to create.

An example of a derived hash table is the linker hash table.
The structures for this are defined in bfdlink.h.  The
functions are in linker.c.

You may also derive a hash table from an already derived hash
table.  For example, the a.out linker backend code uses a hash
table derived from the linker hash table.

• Define the Derived Structures:

• Write the Derived Creation Routine:

• Write Other Derived Routines:


text:
@interface Alias : NSObject <IAlias> {
 @public
  long __Index_;
  NSString *__Name_;
  id __Reference_;
}

- (long)getIndex;
- (void)setIndexWithLong:(long)value;
- (NSString *)getName;
- (void)setNameWithNSString:(NSString *)value;
- (id)getReference;
- (void)setReferenceWithId:(id)value;
- (id)init;
- (id)initWithIndex:(long)index withName:(NSString *)name;
- (id)initWithIndex:(long)index withName:(NSString *)name withID:(id)reference;

@end


text:
<!DOCTYPE html>
<head>
  <title>built_value benchmark</title>
</head>
<body>

<html>
<head>
  <script type="application/dart" src="main.dart"></script>
  <script src="packages/browser/dart.js"></script>
</head>
<body>
</body>
</html>


text:
import React from 'react'
import { renderWithTheme } from '@looker/components-test-utils'
import { screen } from '@testing-library/react'
import { TextArea } from './TextArea'

describe('TextArea', () => {
  test('with placeholder', () => {
    renderWithTheme(<TextArea placeholder="this is a placeholder" />)
    expect(
      screen.getByPlaceholderText('this is a placeholder')
    ).toBeInTheDocument()
  })

  test('should accept disabled', () => {
    renderWithTheme(<TextArea disabled />)
    expect(screen.getByRole('textbox')).toBeDisabled()
  })

  test('with an error validation', () => {
    renderWithTheme(<TextArea validationType="error" />)
    expect(screen.getByRole('textbox')).toBeInvalid()
  })

  test('TextArea resizes with prop resize = true', () => {
    renderWithTheme(<TextArea resize />)
    expect(screen.getByRole('textbox')).toHaveStyle('resize: vertical')
  })

  test('TextArea resizes with prop resize = false', () => {
    renderWithTheme(<TextArea resize={false} />)
    expect(screen.getByRole('textbox')).toHaveStyle('resize: none')
  })

  test('TextArea resizes with prop resize = none', () => {
    renderWithTheme(<TextArea resize="none" />)
    expect(screen.getByRole('textbox')).toHaveStyle('resize: none')
  })

  test('TextArea resizes with prop resize = vertical', () => {
    renderWithTheme(<TextArea resize="vertical" />)
    expect(screen.getByRole('textbox')).toHaveStyle('resize: vertical')
  })
})


text:
/* eslint-env browser, jquery */
/* global serverurl, Reveal, RevealMarkdown */

require('../css/extra.css')
require('../css/site.css')

import { md, updateLastChange, removeDOMEvents, finishView } from './extra'

const body = $('.slides').text()

window.createtime = window.lastchangeui.time.attr('data-createtime')
window.lastchangetime = window.lastchangeui.time.attr('data-updatetime')
updateLastChange()
const url = window.location.pathname
$('.ui-edit').attr('href', `${url}/edit`)

$(document).ready(() => {
    // tooltip
  $('[data-toggle="tooltip"]').tooltip()
})

function extend () {
  const target = {}

  for (const source of arguments) {
    for (const key in source) {
      if (source.hasOwnProperty(key)) {
        target[key] = source[key]
      }
    }
  }

  return target
}

// Optional libraries used to extend on reveal.js
const deps = [{
  src: `${serverurl}/build/reveal.js/lib/js/classList.js`,
  condition () {
    return !document.body.classList
  }
}, {
  src: `${serverurl}/build/reveal.js/plugin/notes/notes.js`,
  async: true,
  condition () {
    return !!document.body.classList
  }
}]

const slideOptions = {
  separator: '^(\r\n?|\n)---(\r\n?|\n)$',
  verticalSeparator: '^(\r\n?|\n)----(\r\n?|\n)$'
}
const slides = RevealMarkdown.slidify(body, slideOptions)
$('.slides').html(slides)
RevealMarkdown.initialize()
removeDOMEvents($('.slides'))
$('.slides').show()

// default options to init reveal.js
const defaultOptions = {
  controls: true,
  progress: true,
  slideNumber: true,
  history: true,
  center: true,
  transition: 'none',
  dependencies: deps
}

// options from yaml meta
const meta = JSON.parse($('#meta').text())
var options = meta.slideOptions || {}

const view = $('.reveal')

// text language
if (meta.lang && typeof meta.lang === 'string') {
  view.attr('lang', meta.lang)
} else {
  view.removeAttr('lang')
}
// text direction
if (meta.dir && typeof meta.dir === 'string' && meta.dir === 'rtl') {
  options.rtl = true
} else {
  options.rtl = false
}
// breaks
if (typeof meta.breaks === 'boolean' && !meta.breaks) {
  md.options.breaks = false
} else {
  md.options.breaks = true
}

// options from URL query string
const queryOptions = Reveal.getQueryHash() || {}

options = extend(defaultOptions, options, queryOptions)
Reveal.initialize(options)

window.viewAjaxCallback = () => {
  Reveal.layout()
}

function renderSlide (event) {
  if (window.location.search.match(/print-pdf/gi)) {
    const slides = $('.slides')
    let title = document.title
    finishView(slides)
    document.title = title
    Reveal.layout()
  } else {
    const markdown = $(event.currentSlide)
    if (!markdown.attr('data-rendered')) {
      let title = document.title
      finishView(markdown)
      markdown.attr('data-rendered', 'true')
      document.title = title
      Reveal.layout()
    }
  }
}

Reveal.addEventListener('ready', event => {
  renderSlide(event)
  const markdown = $(event.currentSlide)
    // force browser redraw
  setTimeout(() => {
    markdown.hide().show(0)
  }, 0)
})
Reveal.addEventListener('slidechanged', renderSlide)

const isMacLike = !!navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i)

if (!isMacLike) $('.container').addClass('hidescrollbar')


text:
<!--[metadata]>
+++
title = "search"
description = "The search command description and usage"
keywords = ["search, hub, images"]
[menu.main]
parent = "smn_cli"
+++
<![end-metadata]-->

# search

    Usage: docker search [OPTIONS] TERM

    Search the Docker Hub for images

      --filter=[]          Filter output based on these conditions:
                           - is-automated=(true|false)
                           - is-official=(true|false)
                           - stars=<number> - image has at least 'number' stars
      --help               Print usage
      --limit=25           Maximum returned search results
      --no-trunc           Don't truncate output

Search [Docker Hub](https://hub.docker.com) for images

See [*Find Public Images on Docker Hub*](../../tutorials/dockerrepos.md#searching-for-images) for
more details on finding shared images from the command line.

> **Note:**
> Search queries will only return up to 25 results

## Examples

### Search images by name

This example displays images with a name containing 'busybox':

    $ docker search busybox
    NAME                             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
    busybox                          Busybox base image.                             316       [OK]
    progrium/busybox                                                                 50                   [OK]
    radial/busyboxplus               Full-chain, Internet enabled, busybox made...   8                    [OK]
    odise/busybox-python                                                             2                    [OK]
    azukiapp/busybox                 This image is meant to be used as the base...   2                    [OK]
    ofayau/busybox-jvm               Prepare busybox to install a 32 bits JVM.       1                    [OK]
    shingonoide/archlinux-busybox    Arch Linux, a lightweight and flexible Lin...   1                    [OK]
    odise/busybox-curl                                                               1                    [OK]
    ofayau/busybox-libc32            Busybox with 32 bits (and 64 bits) libs         1                    [OK]
    peelsky/zulu-openjdk-busybox                                                     1                    [OK]
    skomma/busybox-data              Docker image suitable for data volume cont...   1                    [OK]
    elektritter/busybox-teamspeak    Leightweight teamspeak3 container based on...   1                    [OK]
    socketplane/busybox                                                              1                    [OK]
    oveits/docker-nginx-busybox      This is a tiny NginX docker image based on...   0                    [OK]
    ggtools/busybox-ubuntu           Busybox ubuntu version with extra goodies       0                    [OK]
    nikfoundas/busybox-confd         Minimal busybox based distribution of confd     0                    [OK]
    openshift/busybox-http-app                                                       0                    [OK]
    jllopis/busybox                                                                  0                    [OK]
    swyckoff/busybox                                                                 0                    [OK]
    powellquiring/busybox                                                            0                    [OK]
    williamyeh/busybox-sh            Docker image for BusyBox's sh                   0                    [OK]
    simplexsys/busybox-cli-powered   Docker busybox images, with a few often us...   0                    [OK]
    fhisamoto/busybox-java           Busybox java                                    0                    [OK]
    scottabernethy/busybox                                                           0                    [OK]
    marclop/busybox-solr

### Display non-truncated description (--no-trunc)

This example displays images with a name containing 'busybox',
at least 3 stars and the description isn't truncated in the output:

    $ docker search --stars=3 --no-trunc busybox
    NAME                 DESCRIPTION                                                                               STARS     OFFICIAL   AUTOMATED
    busybox              Busybox base image.                                                                       325       [OK]
    progrium/busybox                                                                                50                   [OK]
    radial/busyboxplus   Full-chain, Internet enabled, busybox made from scratch. Comes in git and cURL flavors.   8                    [OK]

## Limit search results (--limit)

The flag `--limit` is the maximium number of results returned by a search. This value could
be in the range between 1 and 100. The default value of `--limit` is 25.

## Filtering

The filtering flag (`-f` or `--filter`) format is a `key=value` pair. If there is more
than one filter, then pass multiple flags (e.g. `--filter "foo=bar" --filter "bif=baz"`)

The currently supported filters are:

* stars (int - number of stars the image has)
* is-automated (true|false) - is the image automated or not
* is-official (true|false) - is the image official or not

### stars

This example displays images with a name containing 'busybox' and at
least 3 stars:

    $ docker search --filter stars=3 busybox
    NAME                 DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
    busybox              Busybox base image.                             325       [OK]
    progrium/busybox                                                     50                   [OK]
    radial/busyboxplus   Full-chain, Internet enabled, busybox made...   8                    [OK]

### is-automated

This example displays images with a name containing 'busybox'
and are automated builds:

    $ docker search --filter is-automated busybox
    NAME                 DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
    progrium/busybox                                                     50                   [OK]
    radial/busyboxplus   Full-chain, Internet enabled, busybox made...   8                    [OK]

### is-official

This example displays images with a name containing 'busybox', at least
3 stars and are official builds:

    $ docker search --filter "is-automated=true" --filter "stars=3" busybox
    NAME                 DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
    progrium/busybox                                                     50                   [OK]
    radial/busyboxplus   Full-chain, Internet enabled, busybox made...   8                    [OK]


text:
package org.guvnor.ala.ui.backend.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.guvnor.ala.services.api.backend.RuntimeProvisioningServiceBackend;
import org.guvnor.ala.ui.model.ProviderType;
import org.guvnor.ala.ui.model.ProviderTypeKey;
import org.guvnor.ala.ui.model.ProviderTypeStatus;
import org.guvnor.ala.ui.preferences.ProvisioningPreferences;
import org.guvnor.common.services.project.preferences.scope.GlobalPreferenceScope;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.uberfire.preferences.shared.PreferenceScope;

import static org.guvnor.ala.AlaSPITestCommons.mockProviderTypeListSPI;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class ProviderTypeServiceImplTest {

    private static final int PROVIDER_TYPES_COUNT = 5;

    @Mock
    private RuntimeProvisioningServiceBackend runtimeProvisioningService;

    @Mock
    private GlobalPreferenceScope globalPreferenceScope;

    @Mock
    private PreferenceScope preferenceScope;

    @Mock
    private ProvisioningPreferences provisioningPreferences;

    @Mock
    private ProviderTypeServiceImpl service;

    private List<org.guvnor.ala.runtime.providers.ProviderType> providerTypesSpi;

    private List<ProviderType> pickedProviderTypes;

    @Before
    public void setUp() {
        providerTypesSpi = mockProviderTypeListSPI(PROVIDER_TYPES_COUNT);

        when(globalPreferenceScope.resolve()).thenReturn(preferenceScope);
        provisioningPreferences = spy(new ProvisioningPreferences() {
            {
                setProviderTypeEnablements(new HashMap<>());
            }

            @Override
            public void load() {

            }

            @Override
            public void save(PreferenceScope customScope) {

            }
        });

        when(runtimeProvisioningService.getProviderTypes(anyInt(),
                                                         anyInt(),
                                                         anyString(),
                                                         anyBoolean())).thenReturn(providerTypesSpi);
        service = new ProviderTypeServiceImpl(runtimeProvisioningService,
                                              provisioningPreferences,
                                              globalPreferenceScope);
    }

    @Test
    public void testGetAvailableProviders() {
        Collection<ProviderType> result = service.getAvailableProviderTypes();
        assertEquals(PROVIDER_TYPES_COUNT,
                     result.size());

        int i = 0;
        for (ProviderType providerType : result) {
            assertNotNull(providerType.getKey());
            assertEquals(providerTypesSpi.get(i).getProviderTypeName(),
                         providerType.getKey().getId());
            assertEquals(providerTypesSpi.get(i).getVersion(),
                         providerType.getKey().getVersion());
            i++;
        }
    }

    @Test
    public void testGetProviderTypeExisting() {
        //pick an arbitrary existing provider type
        org.guvnor.ala.runtime.providers.ProviderType providerTypeSpi = providerTypesSpi.get(2);

        ProviderTypeKey providerTypeKey = new ProviderTypeKey(providerTypeSpi.getProviderTypeName(),
                                                              providerTypeSpi.getVersion());
        ProviderType providerType = service.getProviderType(providerTypeKey);
        assertNotNull(providerType);

        assertEquals(providerTypeSpi.getProviderTypeName(),
                     providerType.getKey().getId());
        assertEquals(providerTypeSpi.getVersion(),
                     providerType.getKey().getVersion());
    }

    @Test
    public void testGetProviderTypeNotExisting() {
        //invent a non existing provider type key
        ProviderTypeKey providerTypeKey = new ProviderTypeKey("NonExisting",
                                                              "NonExisting");
        ProviderType providerType = service.getProviderType(providerTypeKey);
        assertNull(providerType);
    }

    @Test
    public void testGetEnabledProviderTypes() {
        //pick some providers as the currently enabled ones by emulating their status in the preferences.
        pickSomeProviders();
        pickedProviderTypes.forEach(providerType -> provisioningPreferences.getProviderTypeEnablements().put(providerType,
                                                                                Boolean.TRUE));
        Collection<ProviderType> result = service.getEnabledProviderTypes();
        assertEquals(pickedProviderTypes.size(),
                     result.size());
        pickedProviderTypes.forEach(providerType -> assertTrue(result.contains(providerType)));
        verify(provisioningPreferences,
               times(1)).load();
    }

    @Test
    public void testEnableProviderTypes() {
        //pick some providers an emulate that they are currently disabled in the preferences.
        pickSomeProviders();
        pickedProviderTypes.forEach(providerType -> provisioningPreferences.getProviderTypeEnablements().put(providerType,
                                                                                Boolean.FALSE));
        service.enableProviderTypes(pickedProviderTypes);
        //they must now be enabled.
        pickedProviderTypes.forEach(providerType -> assertTrue(provisioningPreferences.getProviderTypeEnablements().get(providerType)));
        verify(provisioningPreferences,
               times(pickedProviderTypes.size())).save(preferenceScope);
    }

    @Test
    public void testDisableProviderType() {
        pickSomeProviders();
        //pick some providers an emulate that they are currently enabled in the preferences.
        pickSomeProviders();
        pickedProviderTypes.forEach(providerType -> provisioningPreferences.getProviderTypeEnablements().put(providerType,
                                                                                Boolean.TRUE));
        //pick a provider type to disable and disable it
        ProviderType providerTypeToDisable = pickedProviderTypes.get(0);

        service.disableProviderType(providerTypeToDisable);
        //it must be now enabled.
        assertFalse(provisioningPreferences.getProviderTypeEnablements().get(providerTypeToDisable));
        verify(provisioningPreferences,
               times(1)).save(preferenceScope);
    }

    @Test
    public void testGetProviderTypesStatus() {
        Map<ProviderType, ProviderTypeStatus> initialStatusMap = service.getProviderTypesStatus();
        assertEquals(PROVIDER_TYPES_COUNT,
                     initialStatusMap.size());
        //no provider is enabled
        initialStatusMap.values().forEach(status -> assertEquals(status,
                                                                 ProviderTypeStatus.DISABLED));

        //enable some providers
        pickSomeProviders();
        service.enableProviderTypes(pickedProviderTypes);

        Map<ProviderType, ProviderTypeStatus> currentStatusMap = service.getProviderTypesStatus();

        //only the enabled providers can have ENABLED status
        assertEquals(PROVIDER_TYPES_COUNT,
                     currentStatusMap.size());

        pickedProviderTypes.forEach(enabledProvider -> assertEquals(ProviderTypeStatus.ENABLED,
                                                                    currentStatusMap.get(pickedProviderTypes.get(0))));

        //all the remaining must be disabled.
        long expectedDisabled = PROVIDER_TYPES_COUNT - pickedProviderTypes.size();
        long currentDisabled = currentStatusMap.values().stream()
                .filter(status -> status == ProviderTypeStatus.DISABLED).count();
        assertEquals(expectedDisabled,
                     currentDisabled);
    }

    private void pickSomeProviders() {
        //pick an arbitrary set of providers for the available ones.
        Collection<ProviderType> providerTypes = service.getAvailableProviderTypes();
        Iterator<ProviderType> it = providerTypes.iterator();
        pickedProviderTypes = new ArrayList<>();
        pickedProviderTypes.add(it.next());
        pickedProviderTypes.add(it.next());
    }
}


text:
FROM pandastrike/arch_plus
MAINTAINER David Harper (david@pandastrike.com)
#===============================================================================
# Mint Example - Dockerfile
#===============================================================================
# This Dockerfile describes a container holding the Node server that is part of
# the Huxley Mint example.

RUN pacman -Syu --noconfirm
RUN pacman-db-upgrade
RUN pacman -S --noconfirm git nodejs

# Install Node dependencies that must be global.
RUN npm install -g coffee-script

# Install the Mint repository.
RUN git clone git://hook.flavor.cluster:2001/repos/mint.git mint

# Install local repository dependencies.
RUN cd mint && npm install


text:
//////////////////////////////////////////////////////////////////////////////
//
//                    Copyright 2021, Cornutum Project
//                             www.cornutum.org
//
//////////////////////////////////////////////////////////////////////////////

package org.cornutum.tcases.openapi;

import org.junit.Test;

/**
 * Runs tests to handle various media type formats.
 */
public class MediaTypesTest extends OpenApiTest
  {
  @Test
  public void withRequestBody()
    {
    verifyRequestInputModel( "media-types");
    }
  }


text:
package ibcni

import (
	"log"
	"os"
)

const defaultSocketDir = "/run/cni"

type DriverSocket struct {
	SocketDir  string
	DriverName string

	SocketFile string
}

func dirExists(dirname string) (bool, error) {
	fileInfo, err := os.Stat(dirname)
	if err == nil {
		if fileInfo.IsDir() {
			return true, nil
		} else {
			return false, nil
		}
	} else if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func createDir(dirname string) error {
	return os.MkdirAll(dirname, 0700)
}

func fileExists(filePath string) (bool, error) {
	_, err := os.Stat(filePath)

	if err == nil {
		return true, nil
	} else if os.IsNotExist(err) {
		return false, nil
	}

	return true, err
}

func deleteFile(filePath string) error {
	return os.Remove(filePath)
}

func GetDefaultSocketDir() string {
	return defaultSocketDir
}

func (s *DriverSocket) SetupSocket() string {
	exists, err := dirExists(s.SocketDir)
	if err != nil {
		log.Panicf("Stat Socket Directory error '%s'", err)
		os.Exit(1)
	}
	if !exists {
		err = createDir(s.SocketDir)
		if err != nil {
			log.Panicf("Create Socket Directory error: '%s'", err)
			os.Exit(1)
		}
		log.Printf("Created Socket Directory: '%s'", s.SocketDir)
	}

	log.Printf("SocketFile: '%s'", s.SocketFile)
	exists, err = fileExists(s.SocketFile)
	if err != nil {
		log.Panicf("Stat Socket File error: '%s'", err)
		os.Exit(1)
	}
	if exists {
		err = deleteFile(s.SocketFile)
		if err != nil {
			log.Panicf("Delete Socket File error: '%s'", err)
			os.Exit(1)
		}
		log.Printf("Deleted Old Socket File: '%s'", s.SocketFile)
	}

	return s.SocketFile
}

func (s *DriverSocket) GetSocketFile() string {
	return s.SocketFile
}

func NewDriverSocket(socketDir string, driverName string) *DriverSocket {
	if socketDir == "" {
		socketDir = GetDefaultSocketDir()
	}
	return &DriverSocket{
		SocketDir:  socketDir,
		DriverName: driverName,
		SocketFile: socketDir + "/" + driverName + ".sock"}
}