text:
use std::convert::From;
use std::str::FromStr;
use convert_ref::TryFromRef;

/// Default variable keeping an index on an [`Indexable`] variable container.
/// Like a [`Vec`] or an [`HashMap`] for example.
///
/// [`Indexable`]: https://doc.rust-lang.org/std/ops/trait.Index.html
/// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
/// [`hashMap`]: https://doc.rust-lang.org/nightly/std/collections/struct.HashMap.html
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct IndexVar(usize);

#[derive(Debug)]
pub enum VarIdxErr<'a, E> {
    InvalidVariableName(&'a str),
    ConvertErr(E),
}

impl<'a> TryFromRef<&'a str> for IndexVar {
    type Err = VarIdxErr<'a, <usize as FromStr>::Err>;

    fn try_from_ref(s: &&'a str) -> Result<Self, Self::Err> {
        match s.chars().next() {
            Some('$') => {
                match FromStr::from_str(&s[1..]) {
                    Ok(n) => Ok(IndexVar(n)),
                    Err(err) => Err(VarIdxErr::ConvertErr(err)),
                }
            }
            _ => Err(VarIdxErr::InvalidVariableName(s)),
        }
    }
}

impl From<IndexVar> for usize {
    fn from(var_idx: IndexVar) -> Self {
        var_idx.0
    }
}


text:
'use strict'
const server = require('./server/server')
const config = require('./config/config')
const mongoose = require('mongoose')

// Use native Node promises
mongoose.Promise = global.Promise

// connect to MongoDB
mongoose.connect(config.mongo_url, function (err) {
  if (err) {
    console.log('\x1b[31m==> Error when try to connect to db:', err, '\x1b[0m')
  } else {
    console.log('\x1b[32m==> Connection to db successful', '\x1b[0m')
  }
})

server.listen(config.port, (err) => {
  if (err) throw err
  console.log('\x1b[32m==> Server running on port', config.port, '\x1b[0m')
})

redpajama_set_name: RedPajamaGithub


text:
package com.shapesecurity.shift.es2018.reducer;

import junit.framework.TestCase;

import javax.annotation.Nonnull;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public abstract class VisitorTestCase extends TestCase {
    private static final String BASE_PATH = System.getenv("CONFIG_DIR") == null ? "src/test/resources" : System.getenv("CONFIG_DIR");

    protected static Path getPath(String path) {
        Path pathObj = Paths.get(BASE_PATH + '/' + path);
        if (Files.exists(pathObj)) {
            return pathObj;
        } else {
            return Paths.get(path);
        }
    }

    @Nonnull
    protected static String readFile(@Nonnull String path) throws IOException {
        byte[] encoded = Files.readAllBytes(getPath(path));
        return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString();
    }
}


text:
title: ego
hide_git_sync_repo_link: true
hide_git_repo_link: true
---

# überich

=======

* Python
* C++
* GitHub
* Freitags frei
* Fotografie
* WG
* redet gern
* System/Prozesse


text:
//------------------------------------------------------------------------------
// <auto-generated>This code was generated by LLBLGen Pro v4.2.</auto-generated>
//------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Collections.Generic;

namespace NH.Bencher.EntityClasses
{
	/// Class which represents the entity 'SalesOrderHeaderSalesReason'
	public partial class SalesOrderHeaderSalesReason
	{
		#region Class Member Declarations
		private SalesOrderHeader _salesOrderHeader;
		private SalesReason _salesReason;
		private System.DateTime _modifiedDate;
		#endregion

		/// Initializes a new instance of the <see cref="SalesOrderHeaderSalesReason"/> class.
		public SalesOrderHeaderSalesReason() : base()
		{
			OnCreated();
		}

		/// Method called from the constructor
		partial void OnCreated();

		/// Returns a hash code for this instance.
		/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. </returns>
		public override int GetHashCode()
		{
			int toReturn = base.GetHashCode();
			return toReturn;
		}

		/// Determines whether the specified object is equal to this instance.
		/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
		/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
		public override bool Equals(object obj)
		{
			return object.ReferenceEquals(this, obj);
		}

		#region Class Property Declarations
		/// Gets or sets the ModifiedDate field.
		public virtual System.DateTime ModifiedDate
		{
			get { return _modifiedDate; }
			set { _modifiedDate = value; }
		}

		/// Represents the navigator which is mapped onto the association 'SalesOrderHeaderSalesReason.SalesOrderHeader - SalesOrderHeader.SalesOrderHeaderSalesReasons (m:1)'
		public virtual SalesOrderHeader SalesOrderHeader
		{
			get { return _salesOrderHeader; }
			set { _salesOrderHeader = value; }
		}

		/// Represents the navigator which is mapped onto the association 'SalesOrderHeaderSalesReason.SalesReason - SalesReason.SalesOrderHeaderSalesReasons (m:1)'
		public virtual SalesReason SalesReason
		{
			get { return _salesReason; }
			set { _salesReason = value; }
		}

		#endregion
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Elektriska Fält</string>

    <!-- Notifications. -->
    <string name="finished">Ritningen är färdig.</string>

    <!-- Saved. -->
    <string name="menu_save_file">Spara till fil</string>
    <string name="saving_text">Spara bilden till fil…</string>
    <string name="saved_title">Elektriska fält sparas.</string>
    <string name="saved_text">Tryck här för att visa dina fält.</string>
    <string name="save_failed">Det gick inte att spara bilden.</string>

    <!-- Menu. -->
    <string name="menu_fullscreen">Fullskärm</string>
    <string name="menu_random">Slumpa</string>

    <!-- Palette -->
    <string name="palette_title">Palett</string>
    <string name="palette_density">Densitet</string>
    <string name="palette_hues">Hues</string>
</resources>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace MainMenu
{
    public class MainMenu
    {
        public string[] Option = new string[3] { "Play", "Options", "Exit" };
        public Rectangle[] box = new Rectangle[3];
        public Vector2[] position = new Vector2[3];
        public SpriteFont fontSmall, fontBig;
        public Texture2D backGround;
        public Rectangle Screen;
        public Vector2 origin;
        public int windowWidth, windowHeight;
        Color color = Color.Orange;
        public bool PisHighlighted, OisHighlighted, EisHighlighted;

        // mouse position & control
        public int mX, mY;
        public MouseState CurrentState, PastState;

        public MainMenu()
        {
            backGround = null;
            fontBig = null;
            fontSmall = null;
        }

        public void load(ContentManager Content)
        {
            fontSmall = Content.Load<SpriteFont>("MenuFont");
            fontBig = Content.Load<SpriteFont>("MenuFontBig");
            backGround = Content.Load<Texture2D>("bedrock");
        }

        public void draw(SpriteBatch spriteBatch)
        {
            // menu background
            spriteBatch.Draw(backGround, new Vector2(0,0), Screen, Color.White, 0f, origin, 1f, SpriteEffects.None, 1f );
            // text play // if mouse is inside it's box
            if (box[0].Contains(mX, mY))
            {
                spriteBatch.DrawString(fontBig, Option[0], position[0], color);
            }
            else
            {
                spriteBatch.DrawString(fontSmall, Option[0], position[0], Color.White);
            }
            // text options // if mouse is inside it's box
            if (box[1].Contains(mX, mY))
            {
                spriteBatch.DrawString(fontBig, Option[1], position[1], color);
            }
            else
            spriteBatch.DrawString(fontSmall, Option[1], position[1], Color.White);

            // text exit // if mouse is inside it's box
            if (box[2].Contains(mX, mY))
            {
                spriteBatch.DrawString(fontBig, Option[2], position[2], color);
            }
            else
            spriteBatch.DrawString(fontSmall, Option[2], position[2], Color.White);
        }

        public void update(GameTime gameTime)
        {
           MouseState mouse = Mouse.GetState();
            mX = mouse.X;
            mY = mouse.Y;

            // look through all the boxes to see if the mouse has it's cords in them
            // if so, if the mouse left clicks, change color to yellow
            // instead of turning to yellow, son will be used to change enum to different state
            for (int i = 0; i < box.Length; i++)
            {
                if (mouse.LeftButton == ButtonState.Pressed &&
                    PastState.LeftButton == ButtonState.Released)
                {
                    if (box[i].Contains(mX, mY))
                    {
                        color = Color.Yellow;
                    }
                }
                else color = Color.Orange;
            }
        }
        public void getResolution(int newWindowWidth, int newWindowHeight)
        {
            windowWidth = newWindowWidth;
            windowHeight = newWindowHeight;
            Screen = new Rectangle(0, 0, windowWidth, windowHeight);
        }
    }
}


text:
var expect = require('chai').expect,
	sinon = require('sinon'),
	_ = require('underscore'),
	Backbone = require('backbone'),
	SearchResultDropdown = require('SearchResultDropdown');

describe('SearchResultDropdown', function() {
	beforeEach(function() {
		this.vent = _.extend({}, Backbone.Events);

		this.displayDropdownSpy = sinon.spy(SearchResultDropdown.prototype, 'displayDropdown');
		this.hideDropdownSpy = sinon.spy(SearchResultDropdown.prototype, 'hideDropdown');
		this.displayResultsSpy = sinon.spy(SearchResultDropdown.prototype, 'displayResults');

		this.view = new SearchResultDropdown({
			vent: this.vent,
			el: '
' +
				'
' +
				'

' +
				'

' +
				'

'
		});
	});

	afterEach(function() {
		this.displayDropdownSpy.restore();
		this.hideDropdownSpy.restore();
		this.displayResultsSpy.restore();
	});

	it('displays the dropdown when the search button is clicked', function() {
		this.vent.trigger('search:active');

		expect(this.displayDropdownSpy.calledOnce).to.be.true;
		expect(this.view.$el.hasClass('in')).to.be.true;
		expect(this.view.$el.hasClass('out')).to.be.false;
		expect(this.view.$searchLabel.text()).to.equal('Search projects and blog posts');
	});

	it('hides the dropdown when the close button is clicked', function() {
		this.vent.trigger('search:active');
		this.view.$closeBtn.trigger('click');

		expect(this.hideDropdownSpy.calledOnce).to.be.true;
		expect(this.view.$el.hasClass('in')).to.be.false;
		expect(this.view.$el.hasClass('out')).to.be.true;
	});

	it('hides the dropdown when the search form losses focus', function() {
		this.vent.trigger('search:inactive');

		expect(this.hideDropdownSpy.calledOnce).to.be.true;
		expect(this.view.$el.hasClass('search-results-display')).to.be.false;
	});

	it('displays a message when no results are returned', function() {
		this.vent.trigger('search:active');
		this.vent.trigger('search:success', { model: { searchList: [] } });

		expect(this.view.$searchLabel.text()).to.equal('No results found');
	});

	it('displays results when returned', function() {
		this.vent.trigger('search:success', {
			model: {
				searchList: [
					{ type: 'project', title: 'project 1', description: 'first project' },
					{ type: 'blog', title: 'blog 1', description: 'first blog post' },
					{ type: 'project', title: 'project 2', description: 'second project' },
					{ type: 'project', title: 'project 3', description: 'third project' }
				]
			}
		});

		expect(this.displayResultsSpy.calledOnce).to.be.true;
		expect(this.view._titles.length).to.equal(2);
		expect(this.view.$resultsList.find('li').length).to.equal(6);
		expect(this.view.$resultsList.find('.list-title').length).to.equal(2);
		expect(this.view.$resultsList.find('.list-description').length).to.equal(4);
	});
});


text:
import { dirname, join, normalize, strings } from '@angular-devkit/core';
import {
  Rule,
  SchematicsException,
  Tree,
  apply,
  chain,
  externalSchematic,
  mergeWith,
  move,
  noop,
  template,
  url,
} from '@angular-devkit/schematics';
import { Schema as UniversalOptions } from '@schematics/angular/universal/schema';
import { DependencyType, addDependency, updateWorkspace } from '@schematics/angular/utility';
import { JSONFile } from '@schematics/angular/utility/json-file';
import * as ts from 'typescript';

import {
  addInitialNavigation,
  findImport,
  getImportOfIdentifier,
  getOutputPath,
  getProject,
  stripTsExtension,
} from '../utils';

import { Schema as AddUniversalOptions } from './schema';

const SERVE_SSR_TARGET_NAME = 'serve-ssr';
const PRERENDER_TARGET_NAME = 'prerender';

function addScriptsRule(options: AddUniversalOptions): Rule {
  return async (host) => {
    const pkgPath = '/package.json';
    const buffer = host.read(pkgPath);
    if (buffer === null) {
      throw new SchematicsException('Could not find package.json');
    }

    const serverDist = await getOutputPath(host, options.project, 'server');
    const pkg = JSON.parse(buffer.toString()) as any;
    pkg.scripts = {
      ...pkg.scripts,
      'dev:ssr': `ng run ${options.project}:${SERVE_SSR_TARGET_NAME}`,
      'serve:ssr': `node ${serverDist}/main.js`,
      'build:ssr': `ng build && ng run ${options.project}:server`,
      'prerender': `ng run ${options.project}:${PRERENDER_TARGET_NAME}`,
    };

    host.overwrite(pkgPath, JSON.stringify(pkg, null, 2));
  };
}

function updateWorkspaceConfigRule(options: AddUniversalOptions): Rule {
  return () => {
    return updateWorkspace((workspace) => {
      const projectName = options.project;
      const project = workspace.projects.get(projectName);
      if (!project) {
        return;
      }

      const serverTarget = project.targets.get('server');
      serverTarget.options.main = join(
        normalize(project.root),
        stripTsExtension(options.serverFileName) + '.ts',
      );

      const serveSSRTarget = project.targets.get(SERVE_SSR_TARGET_NAME);
      if (serveSSRTarget) {
        return;
      }

      project.targets.add({
        name: SERVE_SSR_TARGET_NAME,
        builder: '@nguniversal/builders:ssr-dev-server',
        defaultConfiguration: 'development',
        options: {},
        configurations: {
          development: {
            browserTarget: `${projectName}:build:development`,
            serverTarget: `${projectName}:server:development`,
          },
          production: {
            browserTarget: `${projectName}:build:production`,
            serverTarget: `${projectName}:server:production`,
          },
        },
      });

      const prerenderTarget = project.targets.get(PRERENDER_TARGET_NAME);
      if (prerenderTarget) {
        return;
      }

      project.targets.add({
        name: PRERENDER_TARGET_NAME,
        builder: '@nguniversal/builders:prerender',
        defaultConfiguration: 'production',
        options: {
          routes: ['/'],
        },
        configurations: {
          production: {
            browserTarget: `${projectName}:build:production`,
            serverTarget: `${projectName}:server:production`,
          },
          development: {
            browserTarget: `${projectName}:build:development`,
            serverTarget: `${projectName}:server:development`,
          },
        },
      });
    });
  };
}

function updateServerTsConfigRule(options: AddUniversalOptions): Rule {
  return async (host) => {
    const project = await getProject(host, options.project);
    const serverTarget = project.targets.get('server');
    if (!serverTarget || !serverTarget.options) {
      return;
    }

    const tsConfigPath = serverTarget.options.tsConfig;
    if (!tsConfigPath || typeof tsConfigPath !== 'string') {
      // No tsconfig path
      return;
    }

    const tsConfig = new JSONFile(host, tsConfigPath);
    const filesAstNode = tsConfig.get(['files']);
    const serverFilePath = stripTsExtension(options.serverFileName) + '.ts';
    if (Array.isArray(filesAstNode) && !filesAstNode.some(({ text }) => text === serverFilePath)) {
      tsConfig.modify(['files'], [...filesAstNode, serverFilePath]);
    }
  };
}

function routingInitialNavigationRule(options: UniversalOptions): Rule {
  return async (host) => {
    const project = await getProject(host, options.project);
    const serverTarget = project.targets.get('server');
    if (!serverTarget || !serverTarget.options) {
      return;
    }

    const tsConfigPath = serverTarget.options.tsConfig;
    if (!tsConfigPath || typeof tsConfigPath !== 'string' || !host.exists(tsConfigPath)) {
      // No tsconfig path
      return;
    }

    const parseConfigHost: ts.ParseConfigHost = {
      useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
      readDirectory: ts.sys.readDirectory,
      fileExists: function (fileName: string): boolean {
        return host.exists(fileName);
      },
      readFile: function (fileName: string): string {
        return host.read(fileName).toString();
      },
    };
    const { config } = ts.readConfigFile(tsConfigPath, parseConfigHost.readFile);
    const parsed = ts.parseJsonConfigFileContent(
      config,
      parseConfigHost,
      dirname(normalize(tsConfigPath)),
    );
    const tsHost = ts.createCompilerHost(parsed.options, true);
    // Strip BOM as otherwise TSC methods (Ex: getWidth) will return an offset,
    // which breaks the CLI UpdateRecorder.
    // See: https://github.com/angular/angular/pull/30719
    tsHost.readFile = function (fileName: string): string {
      return host
        .read(fileName)
        .toString()
        .replace(/^\uFEFF/, '');
    };
    tsHost.directoryExists = function (directoryName: string): boolean {
      // When the path is file getDir will throw.
      try {
        const dir = host.getDir(directoryName);

        return !!(dir.subdirs.length || dir.subfiles.length);
      } catch {
        return false;
      }
    };
    tsHost.fileExists = function (fileName: string): boolean {
      return host.exists(fileName);
    };
    tsHost.realpath = function (path: string): string {
      return path;
    };
    tsHost.getCurrentDirectory = function () {
      return host.root.path;
    };

    const program = ts.createProgram(parsed.fileNames, parsed.options, tsHost);
    const typeChecker = program.getTypeChecker();
    const sourceFiles = program
      .getSourceFiles()
      .filter((f) => !f.isDeclarationFile && !program.isSourceFileFromExternalLibrary(f));
    const printer = ts.createPrinter();
    const routerModule = 'RouterModule';
    const routerSource = '@angular/router';

    sourceFiles.forEach((sourceFile) => {
      const routerImport = findImport(sourceFile, routerSource, routerModule);
      if (!routerImport) {
        return;
      }

      let routerModuleNode: ts.CallExpression;
      ts.forEachChild(sourceFile, function visitNode(node: ts.Node) {
        if (
          ts.isCallExpression(node) &&
          ts.isPropertyAccessExpression(node.expression) &&
          ts.isIdentifier(node.expression.expression) &&
          node.expression.name.text === 'forRoot'
        ) {
          const imp = getImportOfIdentifier(typeChecker, node.expression.expression);

          if (imp && imp.name === routerModule && imp.importModule === routerSource) {
            routerModuleNode = node;
          }
        }

        ts.forEachChild(node, visitNode);
      });

      if (routerModuleNode) {
        const print = printer.printNode(
          ts.EmitHint.Unspecified,
          addInitialNavigation(routerModuleNode),
          sourceFile,
        );

        const recorder = host.beginUpdate(sourceFile.fileName);
        recorder.remove(routerModuleNode.getStart(), routerModuleNode.getWidth());
        recorder.insertRight(routerModuleNode.getStart(), print);
        host.commitUpdate(recorder);
      }
    });
  };
}

function addDependencies(): Rule {
  return (_host: Tree) => {
    return chain([
      addDependency('@nguniversal/builders', '^0.0.0-PLACEHOLDER', {
        type: DependencyType.Dev,
      }),
      addDependency('@nguniversal/express-engine', '^0.0.0-PLACEHOLDER', {
        type: DependencyType.Default,
      }),
      addDependency('express', 'EXPRESS_VERSION', {
        type: DependencyType.Default,
      }),
      addDependency('@types/express', 'EXPRESS_TYPES_VERSION', {
        type: DependencyType.Dev,
      }),
    ]);
  };
}

function addServerFile(options: UniversalOptions): Rule {
  return async (host) => {
    const project = await getProject(host, options.project);
    const browserDistDirectory = await getOutputPath(host, options.project, 'build');

    return mergeWith(
      apply(url('./files'), [
        template({
          ...strings,
          ...options,
          stripTsExtension,
          browserDistDirectory,
        }),
        move(project.root),
      ]),
    );
  };
}

export default function (options: AddUniversalOptions): Rule {
  return async (host) => {
    const project = await getProject(host, options.project);
    const universalOptions = {
      ...options,
      skipInstall: true,
    };

    delete universalOptions.serverFileName;
    delete universalOptions.serverPort;

    return chain([
      project.targets.has('server')
        ? noop()
        : externalSchematic('@schematics/angular', 'universal', universalOptions),
      addScriptsRule(options),
      updateServerTsConfigRule(options),
      updateWorkspaceConfigRule(options),
      routingInitialNavigationRule(options),
      addServerFile(options),
      addDependencies(),
    ]);
  };
}


text:
package android.net.http;

import java.security.KeyStore;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import junit.framework.TestCase;

import org.apache.harmony.xnet.provider.jsse.TrustManagerImpl;

public class X509TrustManagerExtensionsTest extends TestCase {

    private class NotATrustManagerImpl implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] chain, String authType) {}

        public void checkServerTrusted(X509Certificate[] chain, String authType) {}

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    public void testBadCast() throws Exception {
        NotATrustManagerImpl ntmi = new NotATrustManagerImpl();
        try {
            X509TrustManagerExtensions tme = new X509TrustManagerExtensions(ntmi);
            fail();
        } catch (IllegalArgumentException expected) {
        }
    }

    public void testGoodCast() throws Exception {
        String defaultType = KeyStore.getDefaultType();
        TrustManagerImpl tmi = new TrustManagerImpl(KeyStore.getInstance(defaultType));
        X509TrustManagerExtensions tme = new X509TrustManagerExtensions(tmi);
    }

    public void testNormalUseCase() throws Exception {
        String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
        String defaultKeystoreType = KeyStore.getDefaultType();
        tmf.init(KeyStore.getInstance(defaultKeystoreType));
        TrustManager[] tms = tmf.getTrustManagers();
        for (TrustManager tm : tms) {
            if (tm instanceof X509TrustManager) {
                new X509TrustManagerExtensions((X509TrustManager)tm);
                return;
            }
        }
        fail();
    }
}


text:
module StatsD
  # A visitor for the parser. It adapts the parser messages to the storage interface.
  #
  # @see StatsD::Parser
  # @see StatsD::StatAggregation
  class StoreParsedStats
    # @param [StatsD::StatAggregation] storage provides storage for the stats
    def initialize(storage)
      @storage = storage
    end

    # @param [StatsD::StatAggregation] new_storage the replacement storage object
    # @yieldparam [StatsD::StatAggregation] old_storage the storage object being replaced
    def swap_storage(new_storage)
      yield(@storage) if block_given?
      @storage = new_storage
    end

    # @param [String] name
    # @param [Numeric] value
    def visit_Gauge(name, value)
      @storage.gauges[name] = value
    end

    # @param [String] name
    # @param [Numeric] value
    def visit_Timer(name, value)
      @storage.timers.add(name, value)
    end

    # @param [String] name
    # @param [Numeric] value
    # @param [Float] sample_rate
    def visit_Counter(name, value, sample_rate)
      @storage.counters.add(name, value, sample_rate)
    end
  end
end


text:
package org.hawkular.alerts.actions.tests;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hawkular.alerts.api.model.condition.AvailabilityCondition;
import org.hawkular.alerts.api.model.condition.AvailabilityConditionEval;
import org.hawkular.alerts.api.model.condition.ConditionEval;
import org.hawkular.alerts.api.model.dampening.Dampening;
import org.hawkular.alerts.api.model.data.AvailabilityType;
import org.hawkular.alerts.api.model.data.Data;
import org.hawkular.alerts.api.model.event.Alert;
import org.hawkular.alerts.api.model.trigger.Mode;
import org.hawkular.alerts.api.model.trigger.Trigger;

/**
 * Provide test data for Data Alerts on Url resources
 *
 * @author Jay Shaughnessy
 * @author Lucas Ponce
 */
public class UrlAvailabilityData extends CommonData {

    public static Trigger trigger;
    public static AvailabilityCondition firingCondition;
    public static AvailabilityCondition autoResolveCondition;
    public static Dampening firingDampening;

    static {

        Map<String, String> context = new HashMap<>();
        context.put("resourceType", "URL");
        context.put("resourceName", "http://www.jboss.org");

        String triggerId = "jboss-url-availability-trigger";
        String triggerDescription = "Data for http://www.jboss.org";
        String dataId = "jboss-url-availability-data-id";

        trigger = new Trigger(TENANT,
                triggerId,
                triggerDescription,
                context);

        firingCondition = new AvailabilityCondition(TENANT, trigger.getId(),
                Mode.FIRING,
                dataId,
                AvailabilityCondition.Operator.NOT_UP);
        firingCondition.getContext().put("description", "Availability");

        autoResolveCondition = new AvailabilityCondition(TENANT, trigger.getId(),
                Mode.AUTORESOLVE,
                dataId,
                AvailabilityCondition.Operator.UP);
        autoResolveCondition.getContext().put("description", "Availability");

        firingDampening = Dampening.forStrictTime(TENANT, trigger.getId(),
                Mode.FIRING,
                10000);
    }

    public static Alert getOpenAlert() {

        List<Set<ConditionEval>> satisfyingEvals = new ArrayList<>();

        Data avBadData1 = Data.forAvailability(TENANT, firingCondition.getDataId(),
                System.currentTimeMillis(),
                AvailabilityType.DOWN);
        AvailabilityConditionEval eval1 = new AvailabilityConditionEval(firingCondition, avBadData1);

        Set<ConditionEval> evalSet1 = new HashSet<>();
        evalSet1.add(eval1);
        satisfyingEvals.add(evalSet1);

        // 5 seconds later
        Data avBadData2 = Data.forAvailability(TENANT, firingCondition.getDataId(),
                System.currentTimeMillis() + 5000,
                AvailabilityType.DOWN);
        AvailabilityConditionEval eval2 = new AvailabilityConditionEval(firingCondition, avBadData2);

        Set<ConditionEval> evalSet2 = new HashSet<>();
        evalSet2.add(eval2);
        satisfyingEvals.add(evalSet2);

        Alert openAlert = new Alert(trigger.getTenantId(), trigger, firingDampening, satisfyingEvals);

        return openAlert;
    }

    public static Alert resolveAlert(Alert unresolvedAlert) {
        List<Set<ConditionEval>> resolvedEvals = new ArrayList<>();

        Data avGoodData = Data.forAvailability(TENANT, autoResolveCondition.getDataId(),
                System.currentTimeMillis() + 20000,
                AvailabilityType.UP);
        AvailabilityConditionEval eval1 = new AvailabilityConditionEval(autoResolveCondition, avGoodData);
        Set<ConditionEval> evalSet1 = new HashSet<>();
        evalSet1.add(eval1);
        resolvedEvals.add(evalSet1);

        unresolvedAlert.setResolvedEvalSets(resolvedEvals);
        unresolvedAlert.setStatus(Alert.Status.RESOLVED);
        unresolvedAlert.setResolvedBy(RESOLVED_BY);
        unresolvedAlert.addNote(RESOLVED_BY, RESOLVED_NOTES);
        unresolvedAlert.setResolvedTime(System.currentTimeMillis());

        return unresolvedAlert;
    }

}


text:
package com.gilt.aws.lambda.wrapper

import com.amazonaws.auth.DefaultAWSCredentialsProviderChain
import com.amazonaws.services.lambda.AWSLambdaClientBuilder
import com.amazonaws.services.lambda.model._
import scala.util.Try

import com.gilt.aws.lambda.Region

trait AwsLambda {
  def createFunction(req: CreateFunctionRequest): Try[CreateFunctionResult]
  def updateFunctionCode(req: UpdateFunctionCodeRequest): Try[UpdateFunctionCodeResult]
  def getFunctionConfiguration(req: GetFunctionConfigurationRequest): Try[GetFunctionConfigurationResult]
  def updateFunctionConfiguration(req: UpdateFunctionConfigurationRequest): Try[UpdateFunctionConfigurationResult]
  def tagResource(req: TagResourceRequest): Try[TagResourceResult]
  def publishVersion(
      request: PublishVersionRequest): Try[PublishVersionResult]
}

object AwsLambda {
  def instance(region: Region): AwsLambda = {
    val auth = new DefaultAWSCredentialsProviderChain()
    val client = AWSLambdaClientBuilder.standard()
      .withCredentials(auth)
      .withRegion(region.value)
      .build

    new AwsLambda {
      def createFunction(req: CreateFunctionRequest) = Try(client.createFunction(req))
      def updateFunctionCode(req: UpdateFunctionCodeRequest) = Try(client.updateFunctionCode(req))
      def getFunctionConfiguration(req: GetFunctionConfigurationRequest) = Try(client.getFunctionConfiguration(req))
      def updateFunctionConfiguration(req: UpdateFunctionConfigurationRequest) = Try(client.updateFunctionConfiguration(req))
      def tagResource(req: TagResourceRequest) = Try(client.tagResource(req))
      def publishVersion(request: PublishVersionRequest) = Try(client.publishVersion(request))
    }
  }
}


text:
=begin
Copyright 2011 Inside Systems, Inc.

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

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

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

module CassandraCQL
  module Types
    class DecimalType < AbstractType
      def self.cast(value)
        BigDecimal.new(bytes_to_int(value[4..-1]).to_s) * BigDecimal.new('10')**(bytes_to_int(value[0..3])*-1)
      rescue
        raise Error::CastException.new("Unable to convert bytes to decimal", value)
      end
    end
  end
end


text:
#ifndef ZBE_ARCHETYPES_IMPLEMENTATIONS_SIMPLEMOBILE_H
#define ZBE_ARCHETYPES_IMPLEMENTATIONS_SIMPLEMOBILE_H

#include <initializer_list>

#include "ZBE/core/tools/math/Point.h"
#include "ZBE/core/tools/math/Vector.h"

#include "ZBE/archetypes/Mobile.h"
#include "ZBE/archetypes/implementations/SimplePosition.h"

#include "ZBE/core/system/system.h"

namespace zbe {

/** \brief Simple implementation of the Mobile<s> interface.
 */
template <unsigned s>
class SimpleMobile : virtual public Mobile<s>, public SimplePosition<s> {
public:
  /** \brief Empty constructor. Position and velocity are set to 0.
   */
  SimpleMobile() : SimplePosition<s>(), v() {}

  /** \brief Position is set by an initilizer list, velocity is set to 0.
   */
  SimpleMobile(std::initializer_list<double> position) : SimplePosition<s>(position), v() {}

  /** \brief Position is set by a Point, velocity will be set to 0.
   */
  SimpleMobile(Point<s> position) : SimplePosition<s>(position), v() {}

  /** \brief Position is set to 0, velocity is set by a vector.
   */
  SimpleMobile(Vector<s> velocity) : SimplePosition<s>(), v(velocity) {}

  /** \brief Position and velocity are set by an initializer list.
   */
  SimpleMobile(std::initializer_list<double> position, std::initializer_list<double> velocity) : SimplePosition<s>(position), v(velocity) {}

  /** \brief Position is set by a Point, velocity is set by an initializer list.
   */
  SimpleMobile(Point<s> position, std::initializer_list<double> velocity) : SimplePosition<s>(position), v(velocity) {}

  /** \brief Position is set by a Point, velocity is set by a Vector.
   */
  SimpleMobile(Point<s> position, Vector<s> velocity) : SimplePosition<s>(position), v(velocity) {}

  /** \brief Position is set by an initializer list, velocity is set by a Vector.
   */
  SimpleMobile(std::initializer_list<double> position, Vector<s> velocity) : SimplePosition<s>(position), v(velocity) {}

  /** \brief Virtual destructor.
   */
  virtual ~SimpleMobile() {}

  /** \brief Sets velocity using a Vector.
   *  \param velocity Vector with the values of the velocity.
   *  \sa setVelocity, getVelocity
   */
  void setVelocity(Vector<s> velocity) {v = velocity;}

  /** \brief Sets velocity using an initializer list.
   *  \param l Initializer list with the values of the velocity.
   *  \sa setVelocity, getVelocity
   */
  void setVelocity(std::initializer_list<double> l) {v = l;}

  /** \brief Gets the velocity.
   *  \return Return a reference to the actual velocity in a vector.
   *  \sa setVelocity
   */
  Vector<s>& getVelocity() {return (v);}

private:
  Vector<s> v;
};

}  // namespace zbe

#endif //ZBE_ARCHETYPES_IMPLEMENTATIONS_SIMPLEMOBILE_H


text:
require 'spec_helper'

describe RailsAdmin::Config::Model do

  describe "#excluded?" do
    before do
      RailsAdmin.config do |config|
        config.included_models = [Comment]
      end
    end

    it "returns false when included, true otherwise" do
      expect(RailsAdmin.config(Player).excluded?).to be_true
      expect(RailsAdmin.config(Comment).excluded?).to be_false
    end
  end

  describe "#object_label" do
    before do
      RailsAdmin.config(Comment) do
        object_label_method :content
      end
    end

    it "sends object_label_method to binding[:object]" do
      c = Comment.new(:content => 'test')
      expect(RailsAdmin.config(Comment).with(:object => c).object_label).to eq('test')
    end
  end

  describe "#object_label_method" do
    it "is first of Config.label_methods if found as a column on model, or :rails_admin_default_object_label_method" do
      expect(RailsAdmin.config(Comment).object_label_method).to eq(:rails_admin_default_object_label_method)
      expect(RailsAdmin.config(Division).object_label_method).to eq(:name)
    end
  end

  describe "#label" do
    it "is pretty" do
      expect(RailsAdmin.config(Comment).label).to eq('Comment')
    end
  end

  describe "#label_plural" do
    it "is pretty" do
      expect(RailsAdmin.config(Comment).label_plural).to eq('Comments')
    end

    context "when using i18n as label source", skip_mongoid: true do
      around do |example|
        I18n.backend.class.send(:include, I18n::Backend::Pluralization)
        I18n.backend.store_translations :xx, {
          activerecord: {
            models: {
              comment: {
                one: 'one', two: 'two', other: 'other'
              }
            }
          }
        }
        I18n.locale = :xx

        example.run

        I18n.locale = :en
      end

      context "and the locale uses a specific pluralization rule" do
        before do
          I18n.backend.store_translations :xx, {
            i18n: {
              plural: {
                rule: ->(count) {
                  if count == 0
                    :zero
                  elsif count == 1
                    :one
                  elsif count == 2
                    :two
                  else
                    :other
                  end
                }
              }
            },
          }
        end

        it "always uses :other as pluralization key" do
          expect(RailsAdmin.config(Comment).label_plural).to eq('other')
        end
      end
    end
  end

  describe "#weight" do
    it "is 0" do
      expect(RailsAdmin.config(Comment).weight).to eq(0)
    end
  end

  describe "#parent" do
    it "is nil for ActiveRecord::Base inherited models" do
      expect(RailsAdmin.config(Comment).parent).to be_nil
    end

    it "is parent model otherwise" do
      expect(RailsAdmin.config(Hardball).parent).to eq(Ball)
    end
  end

  describe "#navigation_label" do
    it "is nil if parent module is Object" do
      expect(RailsAdmin.config(Comment).navigation_label).to be_nil
    end

    it "is parent module otherwise" do
      expect(RailsAdmin.config(Cms::BasicPage).navigation_label).to eq("Cms")
    end
  end
end


text:
package com.lmax.disruptor.dsl;

import com.lmax.disruptor.BatchEventProcessor;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.EventProcessor;
import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.ExceptionHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.Sequence;
import com.lmax.disruptor.SequenceBarrier;
import com.lmax.disruptor.TimeoutException;
import com.lmax.disruptor.dsl.stubs.DelayedEventHandler;
import com.lmax.disruptor.dsl.stubs.EventHandlerStub;
import com.lmax.disruptor.dsl.stubs.EvilEqualsEventHandler;
import com.lmax.disruptor.dsl.stubs.ExceptionThrowingEventHandler;
import com.lmax.disruptor.dsl.stubs.SleepingEventHandler;
import com.lmax.disruptor.dsl.stubs.StubExceptionHandler;
import com.lmax.disruptor.dsl.stubs.StubExecutor;
import com.lmax.disruptor.dsl.stubs.StubPublisher;
import com.lmax.disruptor.dsl.stubs.TestWorkHandler;
import com.lmax.disruptor.support.TestEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;

import static java.lang.Thread.yield;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

@SuppressWarnings(value = {"unchecked"})
public class DisruptorTest
{
    private static final int TIMEOUT_IN_SECONDS = 2;
    private Disruptor<TestEvent> disruptor;
    private StubExecutor executor;
    private final Collection<DelayedEventHandler> delayedEventHandlers = new ArrayList<DelayedEventHandler>();
    private final Collection<TestWorkHandler> testWorkHandlers = new ArrayList<TestWorkHandler>();
    private RingBuffer<TestEvent> ringBuffer;
    private TestEvent lastPublishedEvent;

    @Before
    public void setUp() throws Exception
    {
        createDisruptor();
    }

    @After
    public void tearDown() throws Exception
    {
        for (DelayedEventHandler delayedEventHandler : delayedEventHandlers)
        {
            delayedEventHandler.stopWaiting();
        }
        for (TestWorkHandler testWorkHandler : testWorkHandlers)
        {
            testWorkHandler.stopWaiting();
        }

        disruptor.halt();
        executor.joinAllThreads();
    }

    @Test
    public void shouldCreateEventProcessorGroupForFirstEventProcessors()
        throws Exception
    {
        executor.ignoreExecutions();
        final EventHandler<TestEvent> eventHandler1 = new SleepingEventHandler();
        EventHandler<TestEvent> eventHandler2 = new SleepingEventHandler();

        final EventHandlerGroup<TestEvent> eventHandlerGroup =
            disruptor.handleEventsWith(eventHandler1, eventHandler2);
        disruptor.start();

        assertNotNull(eventHandlerGroup);
        assertThat(Integer.valueOf(executor.getExecutionCount()), equalTo(Integer.valueOf(2)));
    }

    @Test
    public void shouldMakeEntriesAvailableToFirstHandlersImmediately() throws Exception
    {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        EventHandler<TestEvent> eventHandler = new EventHandlerStub(countDownLatch);

        disruptor.handleEventsWith(createDelayedEventHandler(), eventHandler);

        ensureTwoEventsProcessedAccordingToDependencies(countDownLatch);
    }

    @Test
    public void shouldWaitUntilAllFirstEventProcessorsProcessEventBeforeMakingItAvailableToDependentEventProcessors()
        throws Exception
    {
        DelayedEventHandler eventHandler1 = createDelayedEventHandler();

        CountDownLatch countDownLatch = new CountDownLatch(2);
        EventHandler<TestEvent> eventHandler2 = new EventHandlerStub(countDownLatch);

        disruptor.handleEventsWith(eventHandler1).then(eventHandler2);

        ensureTwoEventsProcessedAccordingToDependencies(countDownLatch, eventHandler1);
    }

    @Test
    public void shouldAllowSpecifyingSpecificEventProcessorsToWaitFor()
        throws Exception
    {
        DelayedEventHandler handler1 = createDelayedEventHandler();
        DelayedEventHandler handler2 = createDelayedEventHandler();

        CountDownLatch countDownLatch = new CountDownLatch(2);
        EventHandler<TestEvent> handlerWithBarrier = new EventHandlerStub(countDownLatch);

        disruptor.handleEventsWith(handler1, handler2);
        disruptor.after(handler1, handler2).handleEventsWith(handlerWithBarrier);

        ensureTwoEventsProcessedAccordingToDependencies(countDownLatch, handler1, handler2);
    }

    @Test
    public void shouldWaitOnAllProducersJoinedByAnd()
        throws Exception
    {
        DelayedEventHandler handler1 = createDelayedEventHandler();
        DelayedEventHandler handler2 = createDelayedEventHandler();

        CountDownLatch countDownLatch = new CountDownLatch(2);
        EventHandler<TestEvent> handlerWithBarrier = new EventHandlerStub(countDownLatch);

        disruptor.handleEventsWith(handler1);
        final EventHandlerGroup<TestEvent> handler2Group = disruptor.handleEventsWith(handler2);
        disruptor.after(handler1).and(handler2Group).handleEventsWith(handlerWithBarrier);

        ensureTwoEventsProcessedAccordingToDependencies(countDownLatch, handler1, handler2);
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowExceptionIfHandlerIsNotAlreadyConsuming()
        throws Exception
    {
        disruptor.after(createDelayedEventHandler()).handleEventsWith(createDelayedEventHandler());
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldTrackEventHandlersByIdentityNotEquality()
        throws Exception
    {
        EvilEqualsEventHandler handler1 = new EvilEqualsEventHandler();
        EvilEqualsEventHandler handler2 = new EvilEqualsEventHandler();

        disruptor.handleEventsWith(handler1);

        // handler2.equals(handler1) but it hasn't yet been registered so should throw exception.
        disruptor.after(handler2);
    }

    @Test
    public void shouldSupportSpecifyingADefaultExceptionHandlerForEventProcessors()
        throws Exception
    {
        AtomicReference<Throwable> eventHandled = new AtomicReference<Throwable>();
        ExceptionHandler exceptionHandler = new StubExceptionHandler(eventHandled);
        RuntimeException testException = new RuntimeException();
        ExceptionThrowingEventHandler handler = new ExceptionThrowingEventHandler(testException);

        disruptor.handleExceptionsWith(exceptionHandler);
        disruptor.handleEventsWith(handler);

        publishEvent();

        final Throwable actualException = waitFor(eventHandled);
        assertSame(testException, actualException);
    }

    @Test
    public void shouldBlockProducerUntilAllEventProcessorsHaveAdvanced()
        throws Exception
    {
        final DelayedEventHandler delayedEventHandler = createDelayedEventHandler();
        disruptor.handleEventsWith(delayedEventHandler);

        final RingBuffer<TestEvent> ringBuffer = disruptor.start();
        delayedEventHandler.awaitStart();

        final StubPublisher stubPublisher = new StubPublisher(ringBuffer);
        try
        {
            executor.execute(stubPublisher);

            assertProducerReaches(stubPublisher, 4, true);

            delayedEventHandler.processEvent();
            delayedEventHandler.processEvent();
            delayedEventHandler.processEvent();
            delayedEventHandler.processEvent();
            delayedEventHandler.processEvent();

            assertProducerReaches(stubPublisher, 5, false);
        }
        finally
        {
            stubPublisher.halt();
        }
    }

    @Test
    public void shouldBeAbleToOverrideTheExceptionHandlerForAEventProcessor()
        throws Exception
    {
        final RuntimeException testException = new RuntimeException();
        final ExceptionThrowingEventHandler eventHandler = new ExceptionThrowingEventHandler(testException);
        disruptor.handleEventsWith(eventHandler);

        AtomicReference<Throwable> reference = new AtomicReference<Throwable>();
        StubExceptionHandler exceptionHandler = new StubExceptionHandler(reference);
        disruptor.handleExceptionsFor(eventHandler).with(exceptionHandler);

        publishEvent();

        waitFor(reference);
    }

    @Test(expected = IllegalStateException.class)
    public void shouldThrowExceptionWhenAddingEventProcessorsAfterTheProducerBarrierHasBeenCreated()
        throws Exception
    {
        executor.ignoreExecutions();
        disruptor.handleEventsWith(new SleepingEventHandler());
        disruptor.start();
        disruptor.handleEventsWith(new SleepingEventHandler());
    }

    @Test(expected = IllegalStateException.class)
    public void shouldThrowExceptionIfStartIsCalledTwice()
        throws Exception
    {
        executor.ignoreExecutions();
        disruptor.handleEventsWith(new SleepingEventHandler());
        disruptor.start();
        disruptor.start();
    }

    @Test
    public void shouldSupportCustomProcessorsAsDependencies()
        throws Exception
    {
        RingBuffer<TestEvent> ringBuffer = disruptor.getRingBuffer();

        final DelayedEventHandler delayedEventHandler = createDelayedEventHandler();

        CountDownLatch countDownLatch = new CountDownLatch(2);
        EventHandler<TestEvent> handlerWithBarrier = new EventHandlerStub(countDownLatch);

        final BatchEventProcessor<TestEvent> processor =
            new BatchEventProcessor<TestEvent>(ringBuffer, ringBuffer.newBarrier(), delayedEventHandler);
        disruptor.handleEventsWith(processor);
        disruptor.after(processor).handleEventsWith(handlerWithBarrier);

        ensureTwoEventsProcessedAccordingToDependencies(countDownLatch, delayedEventHandler);
    }

    @Test
    public void shouldSupportHandlersAsDependenciesToCustomProcessors()
        throws Exception
    {
        final DelayedEventHandler delayedEventHandler = createDelayedEventHandler();
        disruptor.handleEventsWith(delayedEventHandler);

        RingBuffer<TestEvent> ringBuffer = disruptor.getRingBuffer();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        EventHandler<TestEvent> handlerWithBarrier = new EventHandlerStub(countDownLatch);

        final SequenceBarrier sequenceBarrier = disruptor.after(delayedEventHandler).asSequenceBarrier();
        final BatchEventProcessor<TestEvent> processor =
            new BatchEventProcessor<TestEvent>(ringBuffer, sequenceBarrier, handlerWithBarrier);
        disruptor.handleEventsWith(processor);

        ensureTwoEventsProcessedAccordingToDependencies(countDownLatch, delayedEventHandler);
    }

    @Test
    public void shouldSupportCustomProcessorsAndHandlersAsDependencies() throws Exception
    {
        final DelayedEventHandler delayedEventHandler1 = createDelayedEventHandler();
        final DelayedEventHandler delayedEventHandler2 = createDelayedEventHandler();
        disruptor.handleEventsWith(delayedEventHandler1);

        RingBuffer<TestEvent> ringBuffer = disruptor.getRingBuffer();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        EventHandler<TestEvent> handlerWithBarrier = new EventHandlerStub(countDownLatch);

        final SequenceBarrier sequenceBarrier = disruptor.after(delayedEventHandler1).asSequenceBarrier();
        final BatchEventProcessor<TestEvent> processor =
            new BatchEventProcessor<TestEvent>(ringBuffer, sequenceBarrier, delayedEventHandler2);

        disruptor.after(delayedEventHandler1).and(processor).handleEventsWith(handlerWithBarrier);

        ensureTwoEventsProcessedAccordingToDependencies(countDownLatch, delayedEventHandler1, delayedEventHandler2);
    }

    @Test
    public void shouldProvideEventsToWorkHandlers() throws Exception
    {
        final TestWorkHandler workHandler1 = createTestWorkHandler();
        final TestWorkHandler workHandler2 = createTestWorkHandler();
        disruptor.handleEventsWithWorkerPool(workHandler1, workHandler2);

        publishEvent();
        publishEvent();

        workHandler1.processEvent();
        workHandler2.processEvent();
    }

    @Test
    public void shouldSupportUsingWorkerPoolAsDependency() throws Exception
    {
        final TestWorkHandler workHandler1 = createTestWorkHandler();
        final TestWorkHandler workHandler2 = createTestWorkHandler();
        final DelayedEventHandler delayedEventHandler = createDelayedEventHandler();
        disruptor.handleEventsWithWorkerPool(workHandler1, workHandler2).then(delayedEventHandler);

        publishEvent();
        publishEvent();

        assertThat(disruptor.getBarrierFor(delayedEventHandler).getCursor(), equalTo(-1L));

        workHandler2.processEvent();
        workHandler1.processEvent();

        delayedEventHandler.processEvent();
    }

    @Test
    public void shouldSupportUsingWorkerPoolAsDependencyAndProcessFirstEventAsSoonAsItIsAvailable() throws Exception
    {
        final TestWorkHandler workHandler1 = createTestWorkHandler();
        final TestWorkHandler workHandler2 = createTestWorkHandler();
        final DelayedEventHandler delayedEventHandler = createDelayedEventHandler();
        disruptor.handleEventsWithWorkerPool(workHandler1, workHandler2).then(delayedEventHandler);

        publishEvent();
        publishEvent();

        workHandler1.processEvent();
        delayedEventHandler.processEvent();

        workHandler2.processEvent();
        delayedEventHandler.processEvent();
    }

    @Test
    public void shouldSupportUsingWorkerPoolWithADependency() throws Exception
    {
        final TestWorkHandler workHandler1 = createTestWorkHandler();
        final TestWorkHandler workHandler2 = createTestWorkHandler();
        final DelayedEventHandler delayedEventHandler = createDelayedEventHandler();
        disruptor.handleEventsWith(delayedEventHandler).thenHandleEventsWithWorkerPool(workHandler1, workHandler2);

        publishEvent();
        publishEvent();

        delayedEventHandler.processEvent();
        delayedEventHandler.processEvent();

        workHandler1.processEvent();
        workHandler2.processEvent();
    }

    @Test
    public void shouldSupportCombiningWorkerPoolWithEventHandlerAsDependencyWhenNotPreviouslyRegistered() throws Exception
    {
        final TestWorkHandler workHandler1 = createTestWorkHandler();
        final DelayedEventHandler delayedEventHandler1 = createDelayedEventHandler();
        final DelayedEventHandler delayedEventHandler2 = createDelayedEventHandler();
        disruptor.handleEventsWith(delayedEventHandler1).and(disruptor.handleEventsWithWorkerPool(workHandler1)).then(delayedEventHandler2);

        publishEvent();
        publishEvent();

        delayedEventHandler1.processEvent();
        delayedEventHandler1.processEvent();

        workHandler1.processEvent();
        delayedEventHandler2.processEvent();

        workHandler1.processEvent();
        delayedEventHandler2.processEvent();
    }

    @Test(expected = TimeoutException.class, timeout = 2000)
    public void shouldThrowTimeoutExceptionIfShutdownDoesNotCompleteNormally() throws Exception
    {
        //Given
        final DelayedEventHandler delayedEventHandler = createDelayedEventHandler();
        disruptor.handleEventsWith(delayedEventHandler);
        publishEvent();

        //When
        disruptor.shutdown(1, SECONDS);

        //Then
    }

    @Test(timeout = 1000)
    public void shouldTrackRemainingCapacity() throws Exception
    {
        final long[] remainingCapacity = {-1};
        //Given
        final EventHandler<TestEvent> eventHandler = new EventHandler<TestEvent>()
        {
            @Override
            public void onEvent(final TestEvent event, final long sequence, final boolean endOfBatch) throws Exception
            {
                remainingCapacity[0] = disruptor.getRingBuffer().remainingCapacity();
            }
        };

        disruptor.handleEventsWith(eventHandler);

        //When
        publishEvent();

        //Then
        while (remainingCapacity[0] == -1)
        {
            Thread.sleep(100);
        }
        assertThat(remainingCapacity[0], is(ringBuffer.getBufferSize() - 1L));
        assertThat(disruptor.getRingBuffer().remainingCapacity(), is(ringBuffer.getBufferSize() - 0L));
    }

    @Test
    public void shouldAllowEventHandlerWithSuperType() throws Exception
    {
        final CountDownLatch latch = new CountDownLatch(2);
        final EventHandler<Object> objectHandler = new EventHandlerStub<Object>(latch);

        disruptor.handleEventsWith(objectHandler);

        ensureTwoEventsProcessedAccordingToDependencies(latch);
    }

    @Test
    public void shouldAllowChainingEventHandlersWithSuperType() throws Exception
    {
        final CountDownLatch latch = new CountDownLatch(2);
        final DelayedEventHandler delayedEventHandler = createDelayedEventHandler();
        final EventHandler<Object> objectHandler = new EventHandlerStub<Object>(latch);

        disruptor.handleEventsWith(delayedEventHandler).then(objectHandler);

        ensureTwoEventsProcessedAccordingToDependencies(latch, delayedEventHandler);
    }

    @Test
    public void shouldMakeEntriesAvailableToFirstCustomProcessorsImmediately() throws Exception
    {
        final CountDownLatch countDownLatch = new CountDownLatch(2);
        final EventHandler<TestEvent> eventHandler = new EventHandlerStub(countDownLatch);

        disruptor.handleEventsWith(new EventProcessorFactory<TestEvent>()
        {
            @Override
            public EventProcessor createEventProcessor(final RingBuffer<TestEvent> ringBuffer, final Sequence[] barrierSequences)
            {
                assertEquals("Should not have had any barrier sequences", 0, barrierSequences.length);
                return new BatchEventProcessor<TestEvent>(disruptor.getRingBuffer(), ringBuffer.newBarrier(barrierSequences), eventHandler);
            }
        });

        ensureTwoEventsProcessedAccordingToDependencies(countDownLatch);
    }

    @Test
    public void shouldHonourDependenciesForCustomProcessors() throws Exception
    {
        final CountDownLatch countDownLatch = new CountDownLatch(2);
        final EventHandler<TestEvent> eventHandler = new EventHandlerStub(countDownLatch);
        final DelayedEventHandler delayedEventHandler = createDelayedEventHandler();

        disruptor.handleEventsWith(delayedEventHandler).then(new EventProcessorFactory<TestEvent>()
        {
            @Override
            public EventProcessor createEventProcessor(final RingBuffer<TestEvent> ringBuffer, final Sequence[] barrierSequences)
            {
                assertSame("Should have had a barrier sequence", 1, barrierSequences.length);
                return new BatchEventProcessor<TestEvent>(disruptor.getRingBuffer(), ringBuffer.newBarrier(barrierSequences), eventHandler);
            }
        });

        ensureTwoEventsProcessedAccordingToDependencies(countDownLatch, delayedEventHandler);
    }

    private TestWorkHandler createTestWorkHandler()
    {
        final TestWorkHandler testWorkHandler = new TestWorkHandler();
        testWorkHandlers.add(testWorkHandler);
        return testWorkHandler;
    }

    private void ensureTwoEventsProcessedAccordingToDependencies(final CountDownLatch countDownLatch,
                                                                 final DelayedEventHandler... dependencies)
        throws InterruptedException, BrokenBarrierException
    {
        publishEvent();
        publishEvent();

        for (DelayedEventHandler dependency : dependencies)
        {
            assertThatCountDownLatchEquals(countDownLatch, 2L);
            dependency.processEvent();
            dependency.processEvent();
        }

        assertThatCountDownLatchIsZero(countDownLatch);
    }

    private void assertProducerReaches(final StubPublisher stubPublisher,
                                       final int expectedPublicationCount,
                                       boolean strict)
    {
        long loopStart = System.currentTimeMillis();
        while (stubPublisher.getPublicationCount() < expectedPublicationCount && System.currentTimeMillis() - loopStart < 5000)
        {
            yield();
        }

        if (strict)
        {
            assertThat(Integer.valueOf(stubPublisher.getPublicationCount()), equalTo(Integer.valueOf(expectedPublicationCount)));
        }
        else
        {
            final int actualPublicationCount = stubPublisher.getPublicationCount();
            assertTrue("Producer reached unexpected count. Expected at least " + expectedPublicationCount +
                       " but only reached " + actualPublicationCount, actualPublicationCount >= expectedPublicationCount);
        }
    }

    private void createDisruptor()
    {
        executor = new StubExecutor();
        createDisruptor(executor);
    }

    private void createDisruptor(final Executor executor)
    {
        disruptor = new Disruptor<TestEvent>(TestEvent.EVENT_FACTORY, 4, executor,
                                             ProducerType.SINGLE, new BlockingWaitStrategy());
    }

    private TestEvent publishEvent() throws InterruptedException, BrokenBarrierException
    {
        if (ringBuffer == null)
        {
            ringBuffer = disruptor.start();

            for (DelayedEventHandler eventHandler : delayedEventHandlers)
            {
                eventHandler.awaitStart();
            }
        }

        disruptor.publishEvent(new EventTranslator<TestEvent>()
        {
            @Override
            public void translateTo(final TestEvent event, final long sequence)
            {
                lastPublishedEvent = event;
            }
        });

        return lastPublishedEvent;
    }

    private Throwable waitFor(final AtomicReference<Throwable> reference)
    {
        while (reference.get() == null)
        {
            yield();
        }

        return reference.get();
    }

    private DelayedEventHandler createDelayedEventHandler()
    {
        final DelayedEventHandler delayedEventHandler = new DelayedEventHandler();
        delayedEventHandlers.add(delayedEventHandler);
        return delayedEventHandler;
    }

    private void assertThatCountDownLatchEquals(final CountDownLatch countDownLatch,
                                                final long expectedCountDownValue)
    {
        assertThat(Long.valueOf(countDownLatch.getCount()), equalTo(Long.valueOf(expectedCountDownValue)));
    }

    private void assertThatCountDownLatchIsZero(final CountDownLatch countDownLatch)
        throws InterruptedException
    {
        boolean released = countDownLatch.await(TIMEOUT_IN_SECONDS, SECONDS);
        assertTrue("Batch handler did not receive entries: " + countDownLatch.getCount(), released);
    }
}


text:
<?php if (!defined('PRETZEL_EXCEPTION_SERVER')) exit('No Pretzel No (Server) Exception');

class Pretzel_Exception_Server_ViewSelectVariable extends Pretzel_Exception_Server
{
}


text:
package org.optaplanner.core.impl.localsearch.decider.forager.finalist;

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

import org.optaplanner.core.impl.localsearch.event.LocalSearchPhaseLifecycleListenerAdapter;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchMoveScope;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchPhaseScope;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchStepScope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Abstract superclass for {@link FinalistPodium}.
 * @see FinalistPodium
 */
public abstract class AbstractFinalistPodium extends LocalSearchPhaseLifecycleListenerAdapter implements FinalistPodium {

    protected final transient Logger logger = LoggerFactory.getLogger(getClass());

    protected boolean finalistIsAccepted;
    protected List<LocalSearchMoveScope> finalistList;

    @Override
    public void stepStarted(LocalSearchStepScope stepScope) {
        super.stepStarted(stepScope);
        finalistIsAccepted = false;
        finalistList = new ArrayList<LocalSearchMoveScope>(1024);
    }

    public LocalSearchMoveScope pickMove(LocalSearchStepScope stepScope) {
        if (finalistList.isEmpty()) {
            return null;
        }
        if (finalistList.size() == 1) {
            return finalistList.get(0);
        }
        int randomIndex = stepScope.getWorkingRandom().nextInt(finalistList.size());
        return finalistList.get(randomIndex);
    }

    @Override
    public void phaseEnded(LocalSearchPhaseScope phaseScope) {
        super.phaseEnded(phaseScope);
        finalistIsAccepted = false;
        finalistList = null;
    }

}


text:
require "rails_helper"

RSpec.feature "Users can edit existing subjects" do
  before do
    FactoryGirl.create(:subject, name: "RoR 101")

    visit "/subjects"
    click_link "RoR 101"
    click_link "Edit Subject"
  end

  scenario  "with valid attributes" do
    fill_in "Name", with: "RoR 202"
    click_button "Update Subject"

    expect(page).to have_content "Subject has been updated."
    expect(page).to have_content "RoR 202"
  end

  scenario "when providing invalid attributes" do
    fill_in "Name", with: ""
    click_button "Update Subject"

    expect(page).to have_content "Subject has not been updated."
  end

end


text:
**TODO(kriszt)-description**

## Development
> Please red the instructions in order to start contributing to this project

## Front-end
In order to start developing on the front-end side we used some **npm modules**. Basically we setup the environment to live reload pages, to compile our system templates **jade** and **sass** to **html** and **css**. All of this task are automated by one of the javascript task runner called **Grunt**.

#### Environment

**Windows/Mac**
 * Node
 * Npm
[download](https://nodejs.org/en/)

**Linux**

- Debian based:

```shell
sudo apt-get install nodejs
```

- ArchLinux:

```shell
yaourt -S nodejs npm
```

```shell
pacman -S nodejs npm
```

If you need  check [here](https://nodejs.org/en/download/package-manager/) !

Now from the cmd/terminal `cd` into the folder you just downloaded with:
```shell
    git clone https://github.com/kriszt/sblog.git
```
Now type the following command :
```shell
    npm install
```
This command creates a folder called **node_modules** in there it  will download all dev-dependencies and install them.
For the final part please install **grunt-cli** tool in order to run the **grunt** commands.

**LINUX/MAC**
```shell
    sudo npm install -g grunt-cli
```
**Windows**
```text
Just open cmd with administrator privileges.And execute the same command above without sudo.
```

#### Grunt Commands:
```shell
	grunt compile
```

Compiles all the Sass and Jade files. All sass files compiles to css.
All jade files are separate. (ex index.jade --> index.html).
Jade files are compiled to html.
Using this template system we:
- write less clunky markup;
- maintaining is eazy;
- time saver;

```shell
grunt see
```

It does all the things that grunt compile command does  but it reruns automatically for every modification on any  template, js files in assets/ folder

```
grunt live
```
Start a http server to live reload all pages in the browser whenever something changes. **NOTE** this dosen't work for livereloading **PHP** files.In order to see the result in the browser please install and use **xampp/apache/nginx** etc.

## Back-end
**TODO(kriszt)**


text:
<?php defined('COREPATH') or exit('No direct script access allowed'); ?>

INFO - 2014-07-04 15:11:39 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "news"
INFO - 2014-07-04 15:11:39 --> Fuel\Core\Request::execute - Called
INFO - 2014-07-04 15:11:39 --> Fuel\Core\Request::execute - Setting main Request


text:
"""Shows how to set a physics engine and send torque commands to the robot
"""
from openravepy import *
import numpy, time
env=Environment()
env.Load('data/lab1.env.xml')
env.SetViewer('qtcoin')
with env:
    # set a physics engine
    physics = RaveCreatePhysicsEngine(env,'ode')
    env.SetPhysicsEngine(physics)
    physics.SetGravity(numpy.array((0,0,-9.8)))

    robot = env.GetRobots()[0]
    robot.GetLinks()[0].SetStatic(True)
    env.StopSimulation()
    env.StartSimulation(timestep=0.001)

for itry in range(5):
    torques = 100*(numpy.random.rand(robot.GetDOF())-0.5)
    for i in range(100):
        # have to lock environment when calling robot methods
        with env:
            robot.SetDOFTorques(torques,True)
        time.sleep(0.01)

# reset the physics engine
env.SetPhysicsEngine(None)


text:
<?php
/**
 *
 * PHP version 5.5
 *
 * @package TTS
 * @author  Sergey V.Kuzin <sergey@kuzin.name>
 * @license MIT
 */

namespace TTS;

class Result
{
    protected $source;

    protected $cacheKey;

    protected $file;

    /** @var \DateTime */
    protected $createdAt;

    /** @var \DateTime */
    protected $lastAccess;

    protected $count = 0;

    protected $cached = false;

    /**
     * @return mixed
     */
    public function getSource()
    {
        return $this->source;
    }

    /**
     * @param mixed $source
     */
    public function setSource($source)
    {
        $this->source = $source;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCacheKey()
    {
        return $this->cacheKey;
    }

    /**
     * @param mixed $cacheKey
     */
    public function setCacheKey($cacheKey)
    {
        $this->cacheKey = $cacheKey;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * @param mixed $file
     */
    public function setFile($file)
    {
        $this->file = $file;
        $this->import();
        return $this;
    }

    public function setCached($cached = true)
    {
        $this->cached = (bool)$cached;
        return $this;
    }

    public function isCached()
    {
        return $this->cached;
    }

    public function import()
    {
        $file = $this->file . '.json';

        if (file_exists($file)) {
            $data = json_decode(
                file_get_contents($file),
                true
            );
            $this->createdAt = new \DateTime($data['createdAt']);
            $this->count = $data['count'];
        } else {
            $this->createdAt = new \DateTime();
            $this->count = 1;
        }
    }

    /**
     *
     */
    public function export()
    {
        $file = $this->file . '.json';

        file_put_contents($file, json_encode([
            'createdAt' => $this->createdAt->format(\DateTime::RFC3339),
            'source' => $this->source,
            'count' => ++$this->count,
            'lastAccess' => date(\DateTime::RFC3339)
        ], JSON_UNESCAPED_UNICODE));

    }
}


text:
<?php

	require_once('libs/phpFlickr.php');

	 /**
	 * sammlr Flickr wrapper
	 *
	 * based on http://phpflickr.com
	 *
	 * @version    @package_version@
	 * @link       https://github.com/kriskbx/sammlr-lite
	 * @since      0.100
	 *
	 * Name: Flickr
	 * Class: sammlrFlickr
	 * Credentials: flickr_key
	 */

	class sammlrFlickr extends phpFlickr {

		/**
		 * Construct
		 *
		 * @param array $credentials credentials to use oauth
		 *
		 * @version    @package_version@
		 * @since      0.100
		 */
		function __construct($credentials) {
			parent::__construct($credentials['flickr_key']);
		}

		/**
		 * Get Data
		 *
		 * @param int $network_id id of the network that will be put into database
		 * @param array $hashtags the search parameters
		 * @param array $latest $latest['entry_id'] equals the entry_id, $latest['datetime'] equals the last datetime of the last post of this network in the database
		 * @return array
		 *
		 * @version    @package_version@
		 * @since      0.100
		 */
		function getData($network_id, $hashtags, $latest) {

			$fr_query = '';
			foreach($hashtags as $i => $h):
				$fr_query .= $h;
				if($i+1 != count($hashtags)):
					$fr_query .= ',';
				endif;
			endforeach;

			$latestpost = strtotime($latest['datetime']);
			$args = array('text' => $fr_query, 'min_upload_date' => $latestpost, 'content_type' => 1, 'per_page' => 100);

			$results = $this->photos_search($args);
			$data = array();

			foreach($results['photo'] as $photo):
				$info = $this->photos_getInfo($photo['id'], $photo['secret']);
				$sizes = $this->photos_getSizes($photo['id']);
				$people = $this->people_getInfo($photo['owner']);
				if($people['iconserver'] > 0):
					$avatar = 'http://farm'.$people['iconfarm'].'.staticflickr.com/'.$people['iconserver'].'/buddyicons/'.$people['nsid'].'.jpg';
				else:
					$avatar = 'http://www.flickr.com/images/buddyicon.gif';
				endif;
				$data[] = array(
					'network' => $network_id,
					'entry_id' => $photo['id'],
					'userid' => $people['id'],
					'datetime' => date('Y-m-d H:i:s', $info['photo']['dates']['posted']),
					'username' => $info['photo']['owner']['username'],
					'avatar' => $avatar,
					'text' => $photo['title'],
					'picture' => $sizes[count($sizes)-1]['source']
				);
			endforeach;

			return $data;

		}

	}

?>


text:
curl -X POST \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__:requestVerification" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
-d '{
  "agentVerificationContact": {
    "partnerName": "Partner name",
    "partnerEmailAddress": "partner@email.com",
    "brandContactName": "Brand contact name",
    "brandContactEmailAddress": "brand-contact@email.com",
    "brandWebsiteUrl": "https://www.your-company-website.com"
  }
}'


text:
package pet

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"net/http"

	"github.com/go-swagger/go-swagger/httpkit"
)

/*UpdatePetWithFormMethodNotAllowed Invalid input

swagger:response updatePetWithFormMethodNotAllowed
*/
type UpdatePetWithFormMethodNotAllowed struct {
}

// NewUpdatePetWithFormMethodNotAllowed creates UpdatePetWithFormMethodNotAllowed with default headers values
func NewUpdatePetWithFormMethodNotAllowed() UpdatePetWithFormMethodNotAllowed {
	return UpdatePetWithFormMethodNotAllowed{}
}

// WriteResponse to the client
func (o *UpdatePetWithFormMethodNotAllowed) WriteResponse(rw http.ResponseWriter, producer httpkit.Producer) {

	rw.WriteHeader(405)
}


text:
(function() {
  var vm, nodeREPL, jisp, replDefaults, start;
  vm = require("vm");
  nodeREPL = require("repl");
  jisp = require("./jisp");
  replDefaults = {
    useGlobal: true,
    prompt: "jisp> ",
    eval: (function(input, context, filename, cb) {
      var js, result, _ref;
      input = input.replace(/\uFF00/g, "\n");
      input = input.replace(/^\(([^]*)\n\)$/g, "$1");
      try {
        js = jisp.compile(input, {
          wrap: false,
          repl: true
        });
        console.log("-- compiled:");
        console.log(js);
        console.log("-- executing:");
        result = vm.runInThisContext(js, filename);
        _ref = cb(null, result);
      } catch (err) {
        _ref = cb(err);
      }
      return _ref;
    })
  };

  function enableMultiline(repl) {
    var rli, inputStream, outputStream, origPrompt, multiline, lineListener;
    rli = repl.rli;
    inputStream = repl.inputStream;
    outputStream = repl.outputStream;
    origPrompt = (((typeof repl !== 'undefined') && (typeof repl._prompt !== 'undefined')) ? repl._prompt : repl.prompt);
    multiline = {
      enabled: false,
      prompt: origPrompt.replace(/^[^>\s]*>?/, (function(x) {
        return x.replace(/./g, ".");
      })),
      buffer: ""
    };
    lineListener = rli.listeners("line")[0];
    rli.removeListener("line", lineListener);
    return rli.on("line", (function(cmd) {
      var m, opened, closed, _ref, _ref0, _ref1;
      if (multiline.enabled) {
        multiline.buffer += (cmd + "\n");
        opened = ((typeof(m = multiline.buffer.match(/\(/g)) !== 'undefined') ? m.length : 0);
        closed = ((typeof(m = multiline.buffer.match(/\)/g)) !== 'undefined') ? m.length : 0);
        if ((opened > closed)) {
          rli.setPrompt(multiline.prompt);
          _ref = rli.prompt(true);
        } else {
          multiline.enabled = false;
          multiline.buffer = multiline.buffer.replace(/\n/g, "\uFF00");
          rli.emit("line", multiline.buffer);
          multiline.buffer = "";
          rli.setPrompt(origPrompt);
          _ref = rli.prompt(true);
        }
        _ref1 = _ref;
      } else {
        opened = ((typeof(m = cmd.match(/\(/g)) === "string") ? m.length : 0);
        closed = ((typeof(m = cmd.match(/\)/g)) === "string") ? m.length : 0);
        if ((opened > closed)) {
          multiline.enabled = true;
          multiline.buffer += (cmd + "\n");
          rli.setPrompt(multiline.prompt);
          _ref0 = rli.prompt(true);
        } else {
          _ref0 = lineListener(cmd);
        }
        _ref1 = _ref0;
      }
      return _ref1;
    }));
  }
  enableMultiline;
  return exports.start = (start = (function() {
    var repl;
    repl = nodeREPL.start(replDefaults);
    repl.on("exit", (function() {
      return repl.outputStream.write("\n");
    }));
    enableMultiline(repl);
    return repl;
  }));
})['call'](this);


text:
Available scripts
-----------------

The following scripts are used by the unified release process:

| File                 | Description |
|----------------------|-------------|
| get_version          | Returns the current version |
| set_version          | Sets the current version in all places where change is required. Doesn't commit changes. |
| deploy               | Builds all artifacts for the officially supported Beats |

Other scripts:

| File                 | Description |
|----------------------|-------------|
| aggregate_coverage.py | Used to create coverage reports that contain both unit and system tests data |
| merge_pr | Used to make it easier to open a PR that merges one branch into another. |

Import / export the dashboards of a single Beat:

| File                  | Description |
|-----------------------|-------------|
| import_dashboards.sh  | Bash script to import the Beat dashboards from a local directory in Elasticsearch |
| import_dashboards.ps1 | Powershell script to import the Beat dashboards from a local directory in Elasticsearch |
| export_dashboards.py  | Python script to export the Beat dashboards from Elasticsearch to a local directory|

Running export_dashboards.py in environment
----------------------------------------------

If you are running the python script for the first time, you need to create the
environment by running the following commands in the `beats/dev-tools`
directory:

```
virtualenv env
. env/bin/activate
pip install -r requirements.txt
```

This creates the environment that contains all the python packages required to
run the `export_dashboards.py` script. Thus, for the next runs you just need
to enable the environment:

```
. env/bin/activate
```


text:
// This file is automatically generated.

package adila.db;

/*
 * ZTE Kis T3
 *
 * DEVICE: roamer2
 * MODEL: Kis T3
 */
final class roamer2_kis20t3 {
    public static final String DATA = "ZTE|Kis T3|";
}


text:
Extopts is a C library that helps to quickly build your C-applications
with sane standardized CLI. See
https://github.com/githaff/extopts/wiki for more info.


text:
declare module "file-loader!*";

declare module "file-loader?name=[name].js!*";


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>basic_static_string::insert (1 of 11 overloads)</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../../index.html" title="Boost.StaticString">
<link rel="up" href="../insert.html" title="basic_static_string::insert">
<link rel="prev" href="../insert.html" title="basic_static_string::insert">
<link rel="next" href="overload2.html" title="basic_static_string::insert (2 of 11 overloads)">

Home
Libraries
People
FAQ
More

basic_static_string::insert
          (1 of 11 overloads)

            Insert into the string.

            Synopsis

constexpr basic_static_string&
insert(
    size_type index,
    size_type count,
    value_type ch);

            Description

            Inserts count copies
            of ch at the position
            index.

            Exception
            Safety

            Strong guarantee.

            Remarks

            All references, pointers, or iterators referring to contained elements
            are invalidated. Any past-the-end iterators are also invalidated.

            Return
            Value

            *this

            Parameters

<colgroup>
<col>
<col>
</colgroup>

                      Name

                      Description

                      index

                      The index to insert at.

                      count

                      The number of characters to insert.

                      ch

                      The character to insert.

            Exceptions

<colgroup>
<col>
<col>
</colgroup>

                      Type

                      Thrown On

                      std::length_error

                      size()
                      + count > max_size()

                      std::out_of_range

                      index > size()

Copyright © 2019, 2020 Krystian Stasiowski
Copyright © 2016-2019 Vinnie
      Falco

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
function Block (board, x, y) {
  this.board  = board;
  this.x      = x;
  this.y      = y;
  this.width  = 10;
  this.height = 10;
}

Block.prototype.draw = function (context) {
  context.beginPath();
  context.arc(this.x, this.y, 10, 0, 2 * Math.PI, false);
  context.fillStyle = 'brown';
  context.fill();
  return this;
}

Block.prototype.blockBelow = function () {
  return this.board.findBlock(this.x, this.y + 1);
}

Block.prototype.blockToTheRight = function () {
  return this.board.findBlock(this.x + 1, this.y);
}

module.exports = {Block: Block};


text:
import threading
import logging
import datetime
import socket

import dns.resolver
import dns.reversename
import dns.exception
from dns.exception import Timeout

from rdnsmonitor import handy

log = logging.getLogger(__name__)

class SERVFAIL(dns.exception.DNSException):
    pass

class CommException(dns.exception.DNSException):
    pass

class Worker():

    COMMERR_TRESH = 10

    def __init__(self, nameservers=[], use_tcp=False):
        self.current_job = None
        self.default_nameserver = dns.resolver.get_default_resolver().nameservers[0]
        self.nameservers = nameservers + [self.default_nameserver]
        self.cur_nameserver = None
        self.resolver = dns.resolver.Resolver()
        self.nameserver_stats = {nsname:{"good":True} for nsname in self.nameservers}
        self._switchDNS()
        self.timeout = 3
        self.jobstats = {"timeoutcnt":0,
                         "resolvecnt":0,
                         "nxdcnt":0,
                         "tot_duration":datetime.timedelta(0),
                         "errcnt":0}
        self.use_tcp = use_tcp
        return

    def work(self):
        self._fetchJob()
        while self.current_job:
            self._workJob()
            self._finishJob()
            self._fetchJob()
        return

    def _fetchJob(self):
        raise NotImplementedError

    def _finishJob(self):
        raise NotImplementedError

    def _workJob(self):
        raise NotImplementedError

    def _sendResults(self):
        return

    def _resolveIP(self, ipAddress):
        log.debug("Resolving %s...", ipAddress)
        addr =  dns.reversename.from_address(ipAddress)
        try:
            start = datetime.datetime.now()
            data = self.resolver.query(addr, "PTR", tcp=self.use_tcp)[0].to_text()
            duration = datetime.datetime.now() - start
            self.nameserver_stats[self.cur_nameserver]["tot_duration"] += duration
            self.jobstats["tot_duration"] += duration
            self.jobstats["resolvecnt"] += 1
            self.nameserver_stats[self.cur_nameserver]["resolvecnt"] += 1
        except dns.resolver.NXDOMAIN:
            log.debug("%s -> NXDOMAIN", ipAddress)
            data = "NXDOMAIN"
            duration = datetime.datetime.now() - start
            self.nameserver_stats[self.cur_nameserver]["resolvecnt"] += 1
            self.nameserver_stats[self.cur_nameserver]["nxdcnt"] += 1
            self.jobstats["resolvecnt"] += 1
            self.jobstats["nxdcnt"] += 1
            self.nameserver_stats[self.cur_nameserver]["tot_duration"] += duration
            self.jobstats["tot_duration"] += duration
        except Timeout as exc: #no answer within lifetime. This is often not the fault of the open resolver.
            log.warning("Timeout occured @%s querying %s", self.cur_nameserver, addr)
            self.nameserver_stats[self.cur_nameserver]["timeoutcnt"] += 1
            self.jobstats["timeoutcnt"] += 1
            data = "TIMEOUT"
        except CommException:
            log.warning("CommuException occured @%s querying %s", self.cur_nameserver, addr)
            self.nameserver_stats[self.cur_nameserver]["errcnt"] += 1
            self.jobstats["errcnt"] += 1
            data = "ERROR"
            if self.nameserver_stats[self.cur_nameserver]["errcnt"] > LocalWorker.COMMERR_TRESH:
                log.warning("Comm error count for %s exceeded threshold", self.cur_nameserver)
                self._switchDNS()
        except SERVFAIL:
            log.warning("SERVFAIL received @%s querying %s", self.cur_nameserver, addr)
            self.nameserver_stats[self.cur_nameserver]["servfailcnt"] += 1
            self.jobstats["servfailcnt"] += 1
            data = "SERVFAIL"
        except Exception as exc:
            log.error("Uncaught exception: %s", repr(exc))
            raise exc

        log.debug("Got %s", data)
        return data

    def query(self, qname, nameserver, tcp=False):
        """
        Rip from the dns.resolver.query so that I can differntiate between SERVFAIL responses and connection problems.
        """
        source_port=0
        source=None
        qname = dns.name.from_text(qname, None)
        rdtype = dns.rdatatype.from_text("PTR")
        rdclass = dns.rdataclass.from_text(dns.rdataclass.IN)
        request = dns.message.make_query(qname, rdtype, rdclass)
        request.use_edns(self.resolver.edns, self.resolver.ednsflags, self.resolver.payload)
        if self.resolver.flags is not None:
            request.flags = self.resolver.flags
        response = None
        timeout = self.resolver.timeout
        try:
            if tcp:
                response = dns.query.tcp(request, nameserver,
                                         timeout, self.resolver.port,
                                         source=source,
                                         source_port=source_port)
            else:
                response = dns.query.udp(request, nameserver,
                                         timeout, self.resolver.port,
                                         source=source,
                                         source_port=source_port)
                if response.flags & dns.flags.TC:
                    # Response truncated; retry with TCP.
                    timeout = self.resolver.timeout
                    response = dns.query.tcp(request, nameserver,
                                           timeout, self.resolver.port,
                                           source=source,
                                           source_port=source_port)

        except (socket.error, dns.query.UnexpectedSource, dns.exception.FormError, EOFError):
            # These all indicate comm problem with this nameserver.
            raise CommException

        rcode = response.rcode()
        if rcode == dns.rcode.YXDOMAIN:
            raise dns.resolver.YXDOMAIN
        if rcode == dns.rcode.NXDOMAIN:
            raise dns.resolver.NXDOMAIN
        if rcode == dns.rcode.SERVFAIL:
            raise SERVFAIL

        answer = dns.resolver.Answer(qname, rdtype, rdclass, response, True)
        return answer

    def _switchDNS(self):
        if self.cur_nameserver:
            log.info("Abandoning nameserver %s, stats: %s", self.cur_nameserver, repr(self.nameserver_stats[self.cur_nameserver]))
            self.nameserver_stats[self.cur_namserver]["good"] = False
        available = [ns for ns in self.nameserver_stats if self.nameserver_stats[ns]["good"]]
        if not len(available):
            log.warning("No more available nameservers")
            raise Exception("No more available nameservers")

        self.cur_nameserver = available[0]
        self.nameserver_stats[self.cur_nameserver].update({"timeoutcnt":0,
                         "resolvecnt":0,
                         "nxdcnt":0,
                         "tot_duration":datetime.timedelta(0),
                         "errcnt":0})
        log.info("Switched to nameserver %s", self.cur_nameserver)
        return True

    def __repr__(self):
        raise NotImplementedError()

class LocalWorker(Worker, threading.Thread):
    workers = []
    SMAX_RESULTBATCH = 1024

    def __init__(self, c2server, nameservers=None, use_tcp=False, **kwargs):
        threading.Thread.__init__(self, daemon=False, **kwargs)
        Worker.__init__(self, nameservers=nameservers, use_tcp=use_tcp)
        LocalWorker.workers.append(self)
        self._c2server = c2server
        return

    def run(self):
        log.info("Worker started: %s",repr(self))
        self.work()

    def _fetchJob(self):
        log.info("fetching new job...")
        self.current_job = self._c2server.retrieveNewJob()
        self.jobstats = {"timeoutcnt":0,
                         "resolvecnt":0,
                         "servfailcnt":0,
                         "nxdcnt":0,
                         "tot_duration":datetime.timedelta(0),
                         "errcnt":0}
        log.info("Got new job: %s", repr(self.current_job))
        return self.current_job

    def _workJob(self):
        self.current_job.started = datetime.datetime.now()
        log.info("Working %s", repr(self.current_job))
        results = []
        for i in range(self.current_job.ipfrom, self.current_job.ipto):
            ipaddr = handy.intToIp(i)
            res = self._resolveIP(ipaddr)
            results.append((i, res))
            if len(results) >= LocalWorker.SMAX_RESULTBATCH:
                self._sendResults(results)
                results = []
        self._sendResults(results)
        log.info("Work done!")
        return True

    def _sendResults(self, results):
        log.info("Sending %d results to server... jobstats:%s", len(results), repr(self.jobstats))
        self._c2server.storeResults(results)
        log.info("Results sent!")
        return True

    def _finishJob(self):
        self.current_job.completed = datetime.datetime.now()
        self.current_job.nameserver = self.cur_nameserver
        self.current_job.error_count = self.jobstats["errcnt"] + self.jobstats["timeoutcnt"] + self.jobstats["servfailcnt"]
        self.current_job.nxdomain_count = self.jobstats["nxdcnt"]
        log.info("Sending finished job %s to server...", self.current_job)
        self._c2server.finishJob(self.current_job)
        self.current_job = None
        log.info("job sent!")

    def __repr__(self):
        return "<LocalWorker(nameserver={}, name={}, use_tcp={:b})".format(self.cur_nameserver, self.name, self.use_tcp)


text:
package com.gnahraf.io.store.karoon;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;

import com.gnahraf.io.buffer.Covenant;
import com.gnahraf.io.store.Sorted;
import com.gnahraf.io.store.table.del.DeleteCodec;
import com.gnahraf.io.store.table.iter.Direction;
import com.gnahraf.io.store.table.order.RowOrder;

/**
 * A logical table sorted table. Interface extracted from {@linkplain TStore} (which implements it
 * as a stack of on disk tables).
 */
public interface TableStore extends Channel, Sorted {

  /**
   * Returns the table name.
   */
  String name();

  /**
   * Returns the row width in bytes.
   */
  int rowWidth();

  /**
   * Returns the row order.
   */
  RowOrder rowOrder();

  /**
   * Returns the optional deleteCodec. If this method returns <tt>null</tt>,
   * then deletes are not supported.
   */
  DeleteCodec deleteCodec();

  /**
   * Returns the row with the given matching <tt>key</tt>; or <tt>null</tt>, if not found.
   */
  ByteBuffer getRow(ByteBuffer key) throws IOException;

  /**
   * Searches and returns the next row starting from the given <tt>key</tt>.
   *
   * @return the next row, or <tt>null</tt> if no such row exists
   */
  ByteBuffer nextRow(ByteBuffer key, Direction direction, boolean includeKey) throws IOException;

  /**
   * Inserts or updates the given <tt>row</tt> with no promise/covenant. Shorthand for
   * {@linkplain #setRow(ByteBuffer, Covenant) setRow(row, Covenant.NONE)}
   *
   * @param row
   *        the remaining bytes in this buffer represent the row being input. The
   *        remaining bytes must be exactly equal to {@linkplain #rowWidth()}.
   */
  default void setRow(ByteBuffer row) throws IOException {
    setRow(row, Covenant.NONE);
  }

  /**
   * Inserts or updates the given <tt>row</tt>. The operation is fail-safe (all-or-nothing).
   *

   * Pay attention to the <tt>promise</tt> parameter. It has a huge impact on performance,
   * but just as importantly, if you break the promise, you break the data set.
   *
   * @param row
   *        the remaining bytes in this buffer represent the row being input. The
   *        remaining bytes must be exactly equal to {@linkplain #rowWidth()}.
   * @param promise
   *        declares how and whether the caller agrees not to later modify the
   *        given <tt>rows</tt> parameter. If the caller breaks the promise, then
   *        the table will almost certainly get corrupted!. May be <tt>NONE</tt>
   *        (no promise), but that would be a shame.
   */
  void setRow(ByteBuffer row, Covenant promise) throws IOException;

  /**
   * Inserts or updates the given <tt>rows</tt>. The rows are passed in en bloc:
   * they may be ordered in any way. The operation is fail-safe (all-or-nothing).
   *

   * Pay attention to the <tt>promise</tt> parameter. It has a huge impact on performance,
   * but just as importantly, if you break the promise, you break the data set.
   *
   * @param rows
   *        the remaining bytes in this buffer represent the rows being input. The
   *        remaining bytes must be an exact multiple of the
   *        {@linkplain TStoreConfig#getRowWidth() row width}. If the
   *        same row (recall, the identity of a row is defined by the table's
   *        {@linkplain RowOrder}) occurs twice in this buffer, then the last occurance
   *        wins.
   * @param promise
   *        declares how and whether the caller agrees not to later modify the
   *        given <tt>rows</tt> parameter. If the caller breaks the promise, then
   *        the table will almost certainly get corrupted!. May be <tt>NONE</tt>
   *        (no promise), but that would be a shame.
   */
  void setRows(ByteBuffer rows, Covenant promise) throws IOException;

  /**
   * Deletes the row with the given matching <tt>key</tt>, if any.
   */
  void deleteRow(ByteBuffer key) throws IOException;

}


text:
from __future__ import absolute_import

from django.core.urlresolvers import reverse

from sentry.app import tsdb
from sentry.testutils import APITestCase

class ProjectGroupStatsTest(APITestCase):
    def test_simple(self):
        self.login_as(user=self.user)

        project = self.create_project()
        group1 = self.create_group(project=project)
        group2 = self.create_group(project=project)

        url = reverse('sentry-api-0-project-group-stats', kwargs={
            'organization_slug': project.organization.slug,
            'project_slug': project.slug,
        })
        response = self.client.get('%s?id=%s&id=%s' % (url, group1.id, group2.id),
                                   format='json')

        tsdb.incr(tsdb.models.group, group1.id, count=3)

        response = self.client.get('%s?id=%s&id=%s' % (url, group1.id, group2.id),
                                   format='json')

        assert response.status_code == 200, response.content
        assert len(response.data) == 2
        assert str(group1.id) in response.data
        assert str(group2.id) in response.data

        group_data = response.data[str(group1.id)]
        assert group_data[-1][1] == 3, response.data
        for point in group_data[:-1]:
            assert point[1] == 0
        assert len(group_data) == 24


text:
@interface CheckinViewController : PSViewController <UIWebViewDelegate>

- (id)initWithDictionary:(NSDictionary *)dictionary;

@end


text:
<?php

namespace Tests\Feature;

use App\Actions\MigrateDatabase;
use App\Shell;
use App\Tools\Database;
use Tests\Feature\Fakes\FakeProcess;
use Tests\TestCase;

class MigrateDatabaseTest extends TestCase
{
    private $database;

    public function setUp(): void
    {
        parent::setUp();
        $this->database = $this->mock(Database::class);
    }

    /** @test */
    function it_migrates_the_database()
    {
        $fakeStore = [
            'migrate_database' => true,
            'database_host' => 'example.test',
            'database_port' => 3306,
            'database_username' => 'user',
            'database_password' => 'password',
            'database_name' => 'foo',
        ];

        config(['lambo.store' => $fakeStore]);

        $this->database->shouldReceive('fillFromLamboStore')
            ->with($fakeStore)
            ->once()
            ->andReturnSelf();

        $this->database->shouldReceive('ensureExists')
            ->once()
            ->andReturnTrue();

        $this->shell->shouldReceive('execInProject')
            ->with('php artisan migrate --quiet')
            ->once()
            ->andReturn(FakeProcess::success());

        app(MigrateDatabase::class)();
    }

    /** @test */
    function failed_migrations_do_not_halt_execution()
    {
        $fakeStore = [
            'migrate_database' => true,
            'database_host' => 'example.test',
            'database_port' => 3306,
            'database_username' => 'user',
            'database_password' => 'password',
            'database_name' => 'foo',
        ];

        config(['lambo.store' => $fakeStore]);

        $this->database->shouldReceive('fillFromLamboStore')
            ->with($fakeStore)
            ->once()
            ->andReturnSelf();

        $this->database->shouldReceive('ensureExists')
            ->once()
            ->andReturnTrue();

        $this->shell->shouldReceive('execInProject')
            ->with('php artisan migrate --quiet')
            ->once()
            ->andReturn(FakeProcess::fail('php artisan migrate --quiet'));

        app(MigrateDatabase::class)();
    }

    /** @test */
    function it_skips_migrations()
    {
        $databaseSpy = $this->spy(Database::class);
        $shellSpy = $this->spy(Shell::class);

        // Mock the Database->url() so that if it is called it
        // returns properly.
        $databaseSpy->shouldReceive('url')->andReturnSelf();

        config(['lambo.store.migrate_database' => false]);

        config(['lambo.store.database_host' => 'example.test']);
        config(['lambo.store.database_port' => 3306]);
        config(['lambo.store.database_username' => 'user']);
        config(['lambo.store.database_password' => 'password']);
        config(['lambo.store.database_name' => 'foo']);

        app(MigrateDatabase::class)();

        $databaseSpy->shouldNotHaveReceived('fillFromLamboStore');
        $databaseSpy->shouldNotHaveReceived('ensureExists');
        $shellSpy->shouldNotHaveReceived('execInProject');
    }
}


text:
var conversationGreeting = require('../conversations/greeting');
var conversationSetup = require('../conversations/setup');

/**
 * Reponds with a private message when someone says "hi"
 * @param  {Object} bot
 * @param  {Object} message
 */
module.exports = function hi(bot, message) {
    bot.startPrivateConversation(message, function(err, convo) {
        if (err) {
            return console.trace(err);
        }

        conversationGreeting(convo, message);
        conversationSetup(convo, message);
    });
};