text:
using Tokens = std::vector<Token>;

class ComplexTestSuite : public CxxTest::TestSuite {
public:
	void testTokenize() {
		ComplexType complexType;

		TS_ASSERT_EQUALS(
			Tokenizer::tokenize("2i", complexType),
			Tokens({ Token(NumericConstant({ NumericConstantChar::Two, NumericConstantChar::ImaginaryUnit })) }));

		TS_ASSERT_EQUALS(
			Tokenizer::tokenize("i", complexType),
			Tokens({ Token(NumericConstant({ NumericConstantChar::ImaginaryUnit })) }));

		TS_ASSERT_EQUALS(
			Tokenizer::tokenize("10", complexType),
			Tokens({ Token(NumericConstant({ NumericConstantChar::One, NumericConstantChar::Zero })) }));

		TS_ASSERT_EQUALS(
			Tokenizer::tokenize("0", complexType),
			Tokens({ Token(NumericConstant({ NumericConstantChar::Zero })) }));
	}

	void testEval() {
		CalculationEngine engine;
		engine.setEvalMode(ResultValueType::COMPLEX);
		TS_ASSERT_EQUALS(engine.evaluate("i"), ResultValue(Complex(0, 1)));
		TS_ASSERT_EQUALS(engine.evaluate("3i"), ResultValue(Complex(0, 3)));
		TS_ASSERT_EQUALS(engine.evaluate("1+3i"), ResultValue(Complex(1, 3)));
		TS_ASSERT_EQUALS(engine.evaluate("(2+3i)*(2+6i)"), ResultValue(Complex(-14, 18)));
		TS_ASSERT_EQUALS(engine.evaluate("2-i"), ResultValue(Complex(2, -1)));
		TS_ASSERT_EQUALS(engine.evaluate("-2i"), ResultValue(Complex(0, -2)));
	}

	void testEvalVariables() {
		CalculationEngine engine;
		engine.setEvalMode(ResultValueType::COMPLEX);
		TS_ASSERT_EQUALS(engine.evaluate("e^(pi*i)"), ResultValue(Complex(-1, 0)));
	}

	void testEvalFunctions() {
		CalculationEngine engine;
		engine.setEvalMode(ResultValueType::COMPLEX);
		TS_ASSERT_EQUALS(engine.evaluate("sin(-2i)"), ResultValue(std::sin(Complex(0, -2))));

		TS_ASSERT_EQUALS(engine.evaluate("real(5-2i)"), ResultValue(Complex(5, 0)));
		TS_ASSERT_EQUALS(engine.evaluate("imag(5-2i)"), ResultValue(Complex(-2, 0)));
		TS_ASSERT_EQUALS(engine.evaluate("arg(5-2i)"), ResultValue(Complex(std::arg(Complex(5, -2)), 0)));
		TS_ASSERT_EQUALS(engine.evaluate("abs(5-2i)"), ResultValue(Complex(std::abs(Complex(5, -2)), 0)));
		TS_ASSERT_EQUALS(engine.evaluate("polar(10, 5.12)"), ResultValue(std::polar(10.0, 5.12)));
		TS_ASSERT_EQUALS(engine.evaluate("conj(5-2i)"), ResultValue(Complex(5, 2)));
	}

	void testToString() {
		TS_ASSERT_EQUALS("2", ResultValue(Complex(2, 0)).toString());
		TS_ASSERT_EQUALS("-2", ResultValue(Complex(-2, 0)).toString());
		TS_ASSERT_EQUALS("2+i", ResultValue(Complex(2, 1)).toString());
		TS_ASSERT_EQUALS("i", ResultValue(Complex(0, 1)).toString());
		TS_ASSERT_EQUALS("-i", ResultValue(Complex(0, -1)).toString());
		TS_ASSERT_EQUALS("2-7i", ResultValue(Complex(2, -7)).toString());
		TS_ASSERT_EQUALS("-2-7i", ResultValue(Complex(-2, -7)).toString());
	}
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace LiteApi.Tests
{
    public class LiteApiRegistrationExceptionTests
    {
        [Fact]
        public void LiteApiRegistrationException_NotSetErrors_ErrorsAreNotNull()
        {
            var ex1 = new LiteApiRegistrationException("123");
            var ex2 = new LiteApiRegistrationException("123", new Exception());
            Assert.NotNull(ex1.Errors);
            Assert.NotNull(ex2.Errors);
        }

        [Fact]
        public void LiteApiRegistrationException_SetErrors_SetsErrors()
        {
            var ex = new LiteApiRegistrationException("message", new[] { "error" });
            Assert.True(ex.Errors.Any());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.geronimo.gshell.artifact.ivy;

import org.apache.ivy.Ivy;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.util.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;

import java.net.URL;

/**
 * {@link Ivy} factory bean.
 *
 * @version $Rev$ $Date$
 */
public class IvyFactoryBean
    implements FactoryBean
{
    static {
        Message.setDefaultLogger(new Slf4jMessageLogger());
    }

    private final Logger log = LoggerFactory.getLogger(getClass());

    private URL settingsUrl;

    public void setSettingsUrl(final URL url) {
        this.settingsUrl = url;
    }

    public URL getSettingsUrl() {
        if (settingsUrl == null) {
            throw new IllegalStateException("Missing property: settingsUrl");
        }

        return settingsUrl;
    }

    public Object getObject() throws Exception {
        IvySettings settings = new IvySettings();
        URL url = getSettingsUrl();
        log.debug("Settings URL: {}", url);
        settings.load(url);

        //
        // TODO: Need to hook up a TransferListener to show progress, not really sure how to do that with Ivy...
        //

        settings.setVariable("ivy.default.configuration.m2compatible", "true");

        Ivy ivy = Ivy.newInstance(settings);

        log.debug("Ivy: {}", ivy);

        return ivy;
    }

    public Class getObjectType() {
        return Ivy.class;
    }

    public boolean isSingleton() {
        return true;
    }
}


text:
package git4idea;

import com.intellij.dvcs.test.MockVcsHelper;
import com.intellij.idea.IdeaTestApplication;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.AbstractVcsHelper;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.ui.UIUtil;
import cucumber.annotation.After;
import cucumber.annotation.Before;
import cucumber.annotation.Order;
import git4idea.commands.Git;
import git4idea.commands.GitHttpAuthService;
import git4idea.config.GitVcsSettings;
import git4idea.remote.GitHttpAuthTestService;
import git4idea.repo.GitRepository;
import git4idea.test.GitExecutor;
import git4idea.test.GitTestInitUtil;
import git4idea.test.TestNotificator;
import javax.annotation.Nonnull;
import org.jetbrains.ide.BuiltInServerManager;
import org.jetbrains.ide.BuiltInServerManagerImpl;
import org.junit.Assert;
import org.picocontainer.MutablePicoContainer;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;

import static com.intellij.dvcs.test.Executor.cd;
import static com.intellij.dvcs.test.Executor.mkdir;
import static junit.framework.Assert.assertNotNull;
import static org.junit.Assume.assumeTrue;

/**
 *
The container of test environment variables which should be visible from any step definition script.

 *
Most of the fields are populated in the Before hook of the {@link GeneralStepdefs}.

 *
 * @author Kirill Likhodedov
 */
public class GitCucumberWorld {

  public static String myTestRoot;
  public static String myProjectRoot;
  public static VirtualFile myProjectDir;
  public static Project myProject;

  public static GitPlatformFacade myPlatformFacade;
  public static Git myGit;
  public static GitRepository myRepository;
  public static GitVcsSettings mySettings;
  public static ChangeListManagerImpl myChangeListManager;
  public static GitVcs myVcs;

  public static MockVcsHelper myVcsHelper;
  public static TestNotificator myNotificator;

  public static GitHttpAuthTestService myHttpAuthService; // only with @remote tag

  public static GitTestVirtualCommitsHolder virtualCommits;

  private static Collection<Future> myAsyncTasks;

  private IdeaProjectTestFixture myProjectFixture;

  @Before
  @Order(0)
  public void setUp() throws Throwable {
    IdeaTestApplication.getInstance(null);

    String tempFileName = getClass().getName() + "-" + new Random().nextInt();
    myProjectFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(tempFileName).getFixture();

    edt(new ThrowableRunnable<Exception>() {
      @Override
      public void run() throws Exception {
        myProjectFixture.setUp();
      }
    });

    myProject = myProjectFixture.getProject();

    ((ProjectComponent)ChangeListManager.getInstance(myProject)).projectOpened();
    ((ProjectComponent)VcsDirtyScopeManager.getInstance(myProject)).projectOpened();

    myProjectRoot = myProject.getBasePath();
    myProjectDir = myProject.getBaseDir();
    myTestRoot = myProjectRoot;

    myPlatformFacade = ServiceManager.getService(myProject, GitPlatformFacade.class);
    myGit = ServiceManager.getService(myProject, Git.class);
    mySettings = myPlatformFacade.getSettings(myProject);
    mySettings.getAppSettings().setPathToGit(GitExecutor.GIT_EXECUTABLE);

    // dynamic overriding is used instead of making it in plugin.xml,
    // because MockVcsHelper is not ready to be a full featured implementation for all tests.
    myVcsHelper = overrideService(myProject, AbstractVcsHelper.class, MockVcsHelper.class);
    myChangeListManager = (ChangeListManagerImpl)myPlatformFacade.getChangeListManager(myProject);
    myNotificator = (TestNotificator)ServiceManager.getService(myProject, Notificator.class);
    myVcs = GitVcs.getInstance(myProject);

    virtualCommits = new GitTestVirtualCommitsHolder();
    myAsyncTasks = new ArrayList<Future>();

    cd(myProjectRoot);
    myRepository = createRepo(myProjectRoot);

    ProjectLevelVcsManagerImpl vcsManager = (ProjectLevelVcsManagerImpl)ProjectLevelVcsManager.getInstance(myProject);
    AbstractVcs vcs = vcsManager.findVcsByName("Git");
    Assert.assertEquals(1, vcsManager.getRootsUnderVcs(vcs).length);

    assumeSupportedGitVersion();
  }

  private static void assumeSupportedGitVersion() {
    assumeTrue(myVcs.getVersion().isSupported());
  }

  @Nonnull
  private static GitRepository createRepo(String root) {
    GitTestInitUtil.initRepo(root);
    ProjectLevelVcsManagerImpl vcsManager = (ProjectLevelVcsManagerImpl)ProjectLevelVcsManager.getInstance(myProject);
    vcsManager.setDirectoryMapping(root, GitVcs.NAME);
    VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(new File(root));
    GitRepository repository = myPlatformFacade.getRepositoryManager(myProject).getRepositoryForRoot(file);
    assertNotNull("Couldn't find repository for root " + root, repository);
    return repository;
  }

  @Before("@remote")
  @Order(1)
  public void setUpRemoteOperations() {
    ((BuiltInServerManagerImpl)BuiltInServerManager.getInstance()).setEnabledInUnitTestMode(true);
    // default port will be occupied by main idea instance => define the custom default to avoid searching of free port
    System.setProperty(BuiltInServerManagerImpl.PROPERTY_RPC_PORT, "64463");
    myHttpAuthService = (GitHttpAuthTestService)ServiceManager.getService(GitHttpAuthService.class);
  }

  @Before("@nestedroot")
  @Order(2)
  public void setUpStandardMultipleRootsConfig() {
    cd(myProjectRoot);
    String community = mkdir("community");
    createRepo(community);
  }

  @After("@remote")
  @Order(1)
  public void tearDownRemoteOperations() {
    ((BuiltInServerManagerImpl)BuiltInServerManager.getInstance()).setEnabledInUnitTestMode(false);
  }

  @After
  public void tearDown() throws Throwable {
    waitForPendingTasks();
    nullifyStaticFields();
    edt(new ThrowableRunnable<Exception>() {
      @Override
      public void run() throws Exception {
        myProjectFixture.tearDown();
      }
    });
  }

  public static void executeOnPooledThread(Runnable runnable) {
    myAsyncTasks.add(ApplicationManager.getApplication().executeOnPooledThread(runnable));
  }

  private static void waitForPendingTasks() throws InterruptedException, ExecutionException, TimeoutException {
    for (Future future : myAsyncTasks) {
      future.get(30, TimeUnit.SECONDS);
    }
  }

  private static void nullifyStaticFields() throws IllegalAccessException {
    for (Field field : GitCucumberWorld.class.getDeclaredFields()) {
      if (Modifier.isStatic(field.getModifiers())) {
        field.set(null, null);
      }
    }
  }

  @SuppressWarnings("unchecked")
  private static <T> T overrideService(@Nonnull Project project, Class<? super T> serviceInterface, Class<T> serviceImplementation) {
    String key = serviceInterface.getName();
    MutablePicoContainer picoContainer = (MutablePicoContainer) project.getPicoContainer();
    picoContainer.unregisterComponent(key);
    picoContainer.registerComponentImplementation(key, serviceImplementation);
    return (T) ServiceManager.getService(project, serviceInterface);
  }

  private static void edt(@Nonnull final ThrowableRunnable<Exception> runnable) throws Exception {
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        try {
          runnable.run();
        }
        catch (Exception throwable) {
          exception.set(throwable);
        }
      }
    });
    //noinspection ThrowableResultOfMethodCallIgnored
    if (exception.get() != null) {
      throw exception.get();
    }
  }

}


text:
package org.fabric3.samples.bigbank.account;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import java.math.BigDecimal;

import org.fabric3.api.annotation.model.Component;
import org.fabric3.api.annotation.model.EndpointUri;
import org.fabric3.api.annotation.monitor.Monitor;
import org.fabric3.api.annotation.scope.Composite;
import org.fabric3.api.binding.ws.annotation.WebServiceBinding;
import org.fabric3.samples.bigbank.api.backend.account.AccountLedger;
import org.fabric3.samples.bigbank.api.backend.account.AccountsSystem;
import org.fabric3.samples.bigbank.api.backend.account.InternalAccountData;
import org.fabric3.samples.bigbank.api.backend.account.LedgerEntry;
import org.fabric3.samples.bigbank.api.backend.account.LedgerSystem;
import org.fabric3.samples.bigbank.api.services.account.Account;
import org.oasisopen.sca.annotation.Reference;

/**
 * Controller for account resources.
 *
 * This controller is wired to legacy systems that expose WS-* (Web Services) APIs via {@code Reference} annotations. It is responsible for aggregating account
 * balance with ledger entries to provide additional information to end-users such as the "safe-to-spend" calculation.
 */
@EndpointUri("accounts")
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Composite
@Component
public class AccountController {
    private static final BigDecimal MULTIPLIER = BigDecimal.valueOf(100);
    private static final BigDecimal MINIMUM_BALANCE = BigDecimal.valueOf(100);

    @Monitor
    protected AccountMonitor monitor;

    @Reference
    @WebServiceBinding(uri = "http://localhost:8182/accountsSystem")
    protected AccountsSystem accountsSystem;

    @Reference
    @WebServiceBinding(uri = "http://localhost:8182/ledgerSystem")
    protected LedgerSystem ledgerSystem;

    @Path("{accountNumber}")
    @GET
    public Account getAccount(@PathParam("accountNumber") String number) {
        monitor.invoked(number);

        // retrieve account information from the account system
        InternalAccountData internalData = accountsSystem.getAccountData(number);

        // retrieve recent ledger entries for the account
        AccountLedger accountLedger = ledgerSystem.getLedger(number);

        // calculate the safe-to-spend value
        BigDecimal balance = internalData.getBalance();
        BigDecimal safeToSpend = balance.subtract(MINIMUM_BALANCE);
        for (LedgerEntry entry : accountLedger.getEntries()) {
            if (LedgerEntry.TYPE_DEBIT == entry.getType() && LedgerEntry.STATUS_PROCESSING == entry.getStatus()) {
                safeToSpend = safeToSpend.subtract(entry.getAmount());
            }
        }
        return new Account(number, balance.multiply(MULTIPLIER).intValue(), safeToSpend.multiply(MULTIPLIER).intValue());
    }

}


text:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Achordeon.Lib.Chords;

namespace Achordeon.Shell.Wpf.Controls.Fretboard
{
    public class FretboardString : IEnumerable<FretboardPositionControl>
    {
        private readonly List<FretboardPositionControl> m_Positions = new List<FretboardPositionControl>();

        public int StringNumber { get; }

        public FretboardString(int AStringNumber)
        {
            StringNumber = AStringNumber;
        }

        public void AddPosition(FretboardPositionControl APosition)
        {
            m_Positions.Add(APosition);
        }

        public FretboardPositionControl this[int AIndex] => m_Positions[AIndex];

        public IEnumerator<FretboardPositionControl> GetEnumerator()
        {
            return m_Positions.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable) m_Positions).GetEnumerator();
        }

        public bool IsMuted
        {
            get => m_Positions.FirstOrDefault()?.IsMuted ?? false;
            set
            {
                var FirstPos = m_Positions.FirstOrDefault();
                if (FirstPos != null)
                    FirstPos.IsMuted = value;
            }
        }

        public bool IsOpen
        {
            get { return !IsMuted && !m_Positions.Any(APos => APos.IsSelected); }
            set => SelectedFret = 0;
        }

        public int SelectedFret
        {
            get { return m_Positions.FirstOrDefault(APos => APos.IsSelected)?.FretNumber ?? CommonConstants.UNUSED_FRET; }
            set
            {
                m_Positions.ForEach(APos => APos.IsSelected = false);
                if (value == CommonConstants.UNUSED_FRET)
                    return;
                var Pos = m_Positions.FirstOrDefault(APos => APos.FretNumber == value);
                if (Pos != null)
                    Pos.IsSelected = true;
            }
        }
    }
}


text:
import { StyleSheet } from 'react-native';

export default StyleSheet.create({
  icon: {
    padding: 10
  }
});


text:
require 'time'
require 'chef/rest'
require 'chef/data_bag'
require 'chef/data_bag_item'

module KnifeBoxer
  class LogEntry

    attr_accessor :user
    attr_accessor :message
    attr_accessor :constraint_updates
    attr_accessor :environment

    def initialize(config)
      @user = config[:node_name]
      @time = Time.new.utc
      @environment = ""
      @constraint_updates = []
      @message = "(No message)"
      yield self if block_given?
    end

    def entry_id
      @time.strftime("%Y%m%d%H%M%S")
    end

    def timestamp
      @time.to_i
    end

    def datetime
      @time.iso8601
    end

    def updated_cookbooks
      constraint_updates.inject({}) do |update_map, update|
        update_map[update.name] = {
          "old_version" => update.old_version,
          "new_version" => update.new_version
        }
        update_map
      end
    end

    def to_data_item
      item = Chef::DataBagItem.new
      item.data_bag("cookbook-up-log")
      item.raw_data = {"id" => entry_id,
                       "timestamp" => timestamp,
                       "datetime" => datetime,
                       "user" => user,
                       "environment" => environment,
                       "message" => message,
                       "updates" => updated_cookbooks
      }
      item
    end

    def write
      api.post("data/cookbook-up-log", to_data_item)
    rescue Net::HTTPServerException => e
      if e.response.code.to_s == "404"
        create_log_data_bag
        retry
      end
    end

    def create_log_data_bag
      bag = Chef::DataBag.new.tap {|b| b.name("cookbook-up-log") }
      api.post("data", bag)
    end

    def api
      Chef::REST.new(Chef::Config[:chef_server_url])
    end

  end
end


text:
module ApiHelpers

 def format_text_to_model(text_to_model)
      data = [{
         :contenttype => "text/plain",
         :sourceid => "wex",
         :userid => "anon",
         :language => "en",
         :content => text_to_model,
         :id => "wex_id" #uniq Id for the content being analyzed.  Might be a URL or GUID
      }]

      data
   end

   def find_tweets_for_user(handle)
    config = {
      :consumer_key    => settings.twitter_api_key,
      :consumer_secret => settings.twitter_api_secret
    }

    max_fetches = 5

    client = Twitter::REST::Client.new(config)

    options = {
      :count => 200,
      :include_rts => false
    }

    messages_to_model = []

    puts "fetching tweets.."
    tweets = client.user_timeline(handle, options)

    fetch_count = 0
    while not tweets.empty? and
          fetch_count < max_fetches and
          messages_to_model.length < 200 do
      messages_to_model << tweets.map do |t|
        message = Hash.new
        message[:id] = t.id.to_s
        message[:created] = t.created_at.to_i
        message[:content] = t.text
        message[:contenttype] = "text/plain"
        message[:sourceid] = "Twitter"
        message[:language] = t.lang
        message[:userid] = handle

        message
      end

      messages_to_model.flatten!

      puts "Got #{messages_to_model.length} so far. Fetching more tweets.."

      fetch_count += 1
      if fetch_count == max_fetches then break end

      options[:max_id] = tweets.last.id
      tweets = client.user_timeline(handle, options)
    end

    puts "Fetched #{messages_to_model.length} status updates for #{handle}."

    messages_to_model

    # catch the exception for a handle that does not exist
   rescue Twitter::Error::NotFound => error
     puts error.message
     { :error => error.message }

    # catch the exception for too many requests.  Should just fail immediately, no retry
   rescue Twitter::Error::TooManyRequests => error
     puts error.message
     { :error => error.message }

   end

   def calculate_model(data)
      payload = { :contentItems => data }

      function = "/v2/profile"
      response = post(settings.endpoint[:url] + function,
                      settings.endpoint[:username],
                      settings.endpoint[:password],
                      payload)
      response
   end

   def post(url, username, password, payload)
     headers = {
        "Content-Type" => "application/json"
     }

     response = Excon.post(url,
                          :body => payload.to_json,
                          :headers => headers,
                          :user => username,
                          :password => password)

    response.body

  rescue => e
    puts "Something went wrong communicating with backend service..."
    puts e.message
    puts e.backtrace
    {
      :message => "Something went wrong communicating with backend service...",
      :error => e.message,
      :backtrace => e.backtrace
    }.to_json
  end

end


text:
"""
Predefined useful physical constants

Note that all of these names can be imported from the top-level unyt namespace.
For example::

    >>> from unyt.physical_constants import gravitational_constant, solar_mass
    >>> from unyt import AU
    >>> from math import pi
    >>>
    >>> period = 2 * pi * ((1 * AU)**3 / (gravitational_constant * solar_mass))**0.5
    >>> period.in_units('day')
    unyt_quantity(365.26236846, 'day')

.. show_all_constants::

"""

# -----------------------------------------------------------------------------
# Copyright (c) 2018, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the LICENSE file, distributed with this software.
# -----------------------------------------------------------------------------

from unyt.unit_registry import default_unit_registry as _default_unit_registry
from unyt.unit_systems import add_constants as _add_constants

_add_constants(globals(), registry=_default_unit_registry)


text:
var Promise = require('bluebird/js/main/promise')();

Promise.prototype.yield = function(value) {
  return this.then(function() {
    return value;
  });
};

Promise.prototype.tap = function(handler) {
  return this.then(handler).yield(this);
};

Promise.prototype.ensure = Promise.prototype.lastly;
Promise.prototype.otherwise = Promise.prototype.caught;

Promise.resolve = Promise.fulfilled;
Promise.reject  = Promise.rejected;

exports.Promise = Promise;


text:
<?php
/**
 * @author bookerb
 * @package iform
 */

namespace iform;

use IForm;

/**
 * Class Resource
 * @package iform
 */
class Resource
{
    protected $httpurl;
    protected $token;
    protected $params;

    /**
     * Resource constructor.
     * @param $token
     */
    public function __construct(Token $token)
    {
        $this->token = $token;
    }

    /**
     * @param $method
     * @param $httpurl
     * @return array
     */
    protected function getResponse($method, $httpurl)
    {
        $request = new IForm\Request($this->token);
        return $request->getResponse($method, $httpurl, $this->params);
    }

    /**
     * @param $key
     * @param $value
     */
    protected function setParams($key, $value)
    {
        $this->params[$key] = $value;
    }

    /**
     * @param $params
     */
    protected function setParamArray($params)
    {

        if (sizeof($params) && is_array($params)) {
            foreach ($params as $key => $value) {
                $this->setParams($key, $value);
            }
        }
    }

    /**
     * @param $params
     */
    protected function setParamRaw($params)
    {
        $this->params = $params;

    }
}


text:
@class ONEHomeItem;

@interface ONEDetailViewController : UIViewController

@property (strong, nonatomic) ONEHomeItem *homeItem;

@end


text:
require File.expand_path('../../../../spec_helper', __FILE__)
require File.expand_path('../../fixtures/classes', __FILE__)
require File.expand_path('../shared/basic', __FILE__)
require File.expand_path('../shared/numeric_basic', __FILE__)

describe :array_pack_8bit, shared: true do
  it "encodes the least significant eight bits of a positive number" do
    [ [[49],           "1"],
      [[0b11111111],   "\xFF"],
      [[0b100000000],  "\x00"],
      [[0b100000001],  "\x01"]
    ].should be_computed_by(:pack, pack_format)
  end

  it "encodes the least significant eight bits of a negative number" do
    [ [[-1],           "\xFF"],
      [[-0b10000000],  "\x80"],
      [[-0b11111111],  "\x01"],
      [[-0b100000000], "\x00"],
      [[-0b100000001], "\xFF"]
    ].should be_computed_by(:pack, pack_format)
  end

  it "encodes a Float truncated as an Integer" do
    [ [[5.2], "\x05"],
      [[5.8], "\x05"]
    ].should be_computed_by(:pack, pack_format)
  end

  it "calls #to_int to convert the pack argument to an Integer" do
    obj = mock('to_int')
    obj.should_receive(:to_int).and_return(5)
    [obj].pack(pack_format).should == "\x05"
  end

  it "encodes the number of array elements specified by the count modifier" do
    [ [[1, 2, 3], pack_format(3), "\x01\x02\x03"],
      [[1, 2, 3], pack_format(2) + pack_format(1), "\x01\x02\x03"]
    ].should be_computed_by(:pack)
  end

  it "encodes all remaining elements when passed the '*' modifier" do
    [1, 2, 3, 4, 5].pack(pack_format('*')).should == "\x01\x02\x03\x04\x05"
  end

  it "ignores NULL bytes between directives" do
    [1, 2, 3].pack(pack_format("\000", 2)).should == "\x01\x02"
  end

  it "ignores spaces between directives" do
    [1, 2, 3].pack(pack_format(' ', 2)).should == "\x01\x02"
  end
end

describe "Array#pack with format 'C'" do
  it_behaves_like :array_pack_basic, 'C'
  it_behaves_like :array_pack_basic_non_float, 'C'
  it_behaves_like :array_pack_8bit, 'C'
  it_behaves_like :array_pack_arguments, 'C'
  it_behaves_like :array_pack_numeric_basic, 'C'
  it_behaves_like :array_pack_integer, 'C'
  it_behaves_like :array_pack_no_platform, 'C'
end

describe "Array#pack with format 'c'" do
  it_behaves_like :array_pack_basic, 'c'
  it_behaves_like :array_pack_basic_non_float, 'c'
  it_behaves_like :array_pack_8bit, 'c'
  it_behaves_like :array_pack_arguments, 'c'
  it_behaves_like :array_pack_numeric_basic, 'c'
  it_behaves_like :array_pack_integer, 'c'
  it_behaves_like :array_pack_no_platform, 'c'
end


text:
'use strict';

var unicorns = '<3 cake'


text:
<!-- This CSS is definately different from the original. Which is the point, Duh -->
<!-- TestReposSkin CSS -->

body {
    display: block;
    page: main;
}


text:
package org.klose.payment.service.notification;

import java.util.Map;

public interface ProcessNotificationService {

	/**
	 *
	 * @param orderNo
	 * @param notifyDatagram
	 * @param payId
	 * @param notifyMessage
	 * @param notifyParams
	 */
	void handlePaymentCallback(
			String orderNo,
			String notifyDatagram,
			String payId,
			String notifyMessage,
			Map<String, String> notifyParams);

	/**
	 *
	 * @param transactionId
	 * @param notifyDatagram
	 * @param payId
	 * @param notifyMessage
	 * @param notifyParams
	 */
	void handlePaymentCallback(
			Long transactionId,
			String notifyDatagram,
			String payId,
			String notifyMessage,
			Map<String, String> notifyParams);

}


text:
require_relative 'helper'
require 'tempfile'

describe Debunker do
  before do
    Debunker.history.clear

    @saved_history = "1\n2\n3\n"

    Debunker.history.loader = proc do |&blk|
      @saved_history.lines.each { |l| blk.call(l) }
    end

    Debunker.load_history
  end

  after do
    Debunker.history.clear
    Debunker.history.restore_default_behavior
    Debunker.history.instance_variable_set(:@original_lines, 0)
  end

  describe '#push' do
    it "does not record duplicated lines" do
      Debunker.history << '3'
      Debunker.history << '_ += 1'
      Debunker.history << '_ += 1'
      expect(Debunker.history.to_a.grep('_ += 1').count).to eq 1
    end

    it "does not record empty lines" do
      c = Debunker.history.to_a.count
      Debunker.history << ''
      expect(Debunker.history.to_a.count).to eq c
    end
  end

  describe "#clear" do
    before do
      @old_file = Debunker.config.history.file
      @hist_file_path = File.expand_path('spec/fixtures/debunker_history')
      Debunker.config.history.file = @hist_file_path
      Debunker.history.clear
      Debunker.history.restore_default_behavior
      Debunker.load_history
    end

    after do
      Debunker.config.history.file = @old_file
    end

    it "clears this session's history" do
      expect(Debunker.history.to_a.size).to be > 0
      Debunker.history.clear
      expect(Debunker.history.to_a.size).to eq 0
      expect(Debunker.history.original_lines).to eq 0
    end

    it "doesn't affect the contents of the history file" do
      expect(Debunker.history.to_a.size).to eq 3
      Debunker.history.clear

      File.open(@hist_file_path, 'r') { |fh|
        file = fh.to_a

        expect(file.length).to eq 3
        expect(file.any? { |a| a =~ /athos/ }).to eq true
      }
    end
  end

  describe "#history_line_count" do
    it "counts entries in history" do
      Debunker.history.clear
      saved_history = "olgierd\ngustlik\njanek\ngrzes\ntomek\n"
      Debunker.history.loader = proc do |&blk|
        saved_history.lines.each { |l| blk.call(l) }
      end
      Debunker.load_history

      expect(Debunker.history.history_line_count).to eq 5
    end
  end

  describe "#restore_default_behavior" do
    it "restores loader" do
      Debunker.history.loader = proc {}
      Debunker.history.restore_default_behavior
      expect(Debunker.history.loader.class).to eq Method
      expect(Debunker.history.loader.name.to_sym).to eq :read_from_file
    end

    it "restores saver" do
      Debunker.history.saver = proc {}
      Debunker.history.restore_default_behavior
      expect(Debunker.history.saver.class).to eq Method
      expect(Debunker.history.saver.name.to_sym).to eq :save_to_file
    end

    it "restores pusher" do
      Debunker.history.pusher = proc {}
      Debunker.history.restore_default_behavior
      expect(Debunker.history.pusher.class).to eq Method
      expect(Debunker.history.pusher.name.to_sym).to eq :push_to_readline
    end

    it "restores clearer" do
      Debunker.history.clearer = proc {}
      Debunker.history.restore_default_behavior
      expect(Debunker.history.clearer.class).to eq Method
      expect(Debunker.history.clearer.name.to_sym).to eq :clear_readline
    end
  end

  describe "#session_line_count" do
    it "returns the number of lines in history from just this session" do
      Debunker.history << 'you?'
      Debunker.history << 'you are so precious'
      expect(Debunker.history.session_line_count).to eq 2
    end
  end

  describe ".load_history" do
    it "reads the contents of the file" do
      expect(Debunker.history.to_a[-2..-1]).to eq %w(2 3)
    end
  end

  describe "saving to a file" do
    before do
      @histfile = Tempfile.new(["debunkerhistory", "txt"])
      @history = Debunker::History.new(:file_path => @histfile.path)
      Debunker.config.history.should_save = true
      @history.pusher = proc{ }
    end

    after do
      @histfile.close(true)
      Debunker.config.history.should_save = false
    end

    it "saves lines to a file as they are written" do
      @history.push "5"
      expect(File.read(@histfile.path)).to eq "5\n"
    end

    it "interleaves lines from many places" do
      @history.push "5"
      File.open(@histfile.path, 'a'){ |f| f.puts "6" }
      @history.push "7"

      expect(File.read(@histfile.path)).to eq "5\n6\n7\n"
    end
  end

  describe "expanding the history file path" do
    before { Debunker.config.history.should_save = true  }
    after  { Debunker.config.history.should_save = false }

    it "recognizes ~ (#1262)" do
      # This is a pretty dumb way of testing this, but at least it shouldn't
      # succeed spuriously.
      history = Debunker::History.new(file_path: '~/test_history')
      error = Class.new(RuntimeError)

      expect(File).to receive(:open).
        with(File.join(ENV['HOME'].to_s, "/test_history"), 'a', 0600).
        and_raise(error)

      expect { history.push 'a line' }.to raise_error error
    end
  end
end


text:
const bcrypt = require('bcrypt');
const LocalStrategy = require('passport-local').Strategy;
// Custom Helper with MongoDB
const userData = require('../data/').user;

module.exports = exports = (passport) => {
	passport.use(new LocalStrategy(
		(username, password, done) => {
			userData.getUser(username).then((user) => {
				if (!user) {
					return done('Incorrect username');
				}
				bcrypt.compare(password, user.password, (err, isEqual) => {
					if (err || !isEqual) {
						// TODO: Increment attempt and create a lockout feature
						return done(null, null, { message: 'Invalid username and/or password'});
					}
					return done(null, user);
				})
			}).catch((err) => {
				return done(null, null, { message: `${err}` });
			})
		})
	);
};


text:
'use strict'

import list from './list'
import scroller from './scroller'
import refresh from './refresh'
import loading from './loading'

export default {
  init: function (Weex) {
    Weex.install(list)
    Weex.install(scroller)
    Weex.install(refresh)
    Weex.install(loading)
  }
}

/* eslint-disable */
;
/* eslint-enable */


text:
describe('tests work', function () {
  it('should do something', function () {
    expect(true).to.be.true;
  });
});

describe('Global variable we want in our tests', function () {
  it('should declare global libraries', function () {
    expect(Handlebars, "Handlebars is global").to.be.ok;
    expect(Handlebars.compile, "Handlebars.compile is global").to.be.ok;
    expect(Backbone, "Backbone is global").to.be.ok;
    expect(Handlebones, "Handlebones is global").to.be.ok;
    expect(fixtures, "fixtures is global").to.be.ok;
    expect(sinon, "sinon is global").to.be.ok;
    expect(sinon.stub, "sinon.stub is global").to.be.ok;
  });
});


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/ads/googleads/v10/enums/positive_geo_target_type.proto

namespace Google\Ads\GoogleAds\V10\Enums;

if (false) {
    /**
     * This class is deprecated. Use Google\Ads\GoogleAds\V10\Enums\PositiveGeoTargetTypeEnum\PositiveGeoTargetType instead.
     * @deprecated
     */
    class PositiveGeoTargetTypeEnum_PositiveGeoTargetType {}
}
class_exists(PositiveGeoTargetTypeEnum\PositiveGeoTargetType::class);
@trigger_error('Google\Ads\GoogleAds\V10\Enums\PositiveGeoTargetTypeEnum_PositiveGeoTargetType is deprecated and will be removed in the next major release. Use Google\Ads\GoogleAds\V10\Enums\PositiveGeoTargetTypeEnum\PositiveGeoTargetType instead', E_USER_DEPRECATED);


text:
package main

// #cgo CFLAGS: -std=gnu11 -Wvla -Werror -fvisibility=hidden -Winit-self
// #cgo CFLAGS: -Wformat=2 -Wshadow -Wendif-labels -fasynchronous-unwind-tables
// #cgo CFLAGS: -pipe --param=ssp-buffer-size=4 -g -Wunused
// #cgo CFLAGS: -Werror=implicit-function-declaration
// #cgo CFLAGS: -Werror=return-type -Wendif-labels -Werror=overflow
// #cgo CFLAGS: -Wnested-externs -fexceptions
// #cgo CFLAGS: -I include
// #cgo pkg-config: lxc
// #cgo pkg-config: libcap
import "C"


text:
use strict;
use warnings;
use Getopt::Long;

my ($seq, $seq_name, %seqhash);
my ($fasta, $table, $bpperline, $header, $lclrm);
my $help;

sub prompt {
	print <<EOF;
	Usage: perl fasta.cancatenate.pl --fasta <Input Fasta Files> --table
	--fasta (str):		 fasta sequence file
	--table (str):		 reorganizing info file in the following format (6 columns separated by tab)
				 		(oldcontig	start	end	strand	newcontig	order)
	--bpperline(num):	bp per line, default=80
	--header:			table contains the header if specified (default: no header)
	--lclrm: 			rm "lcl|" from the beginning of each sequence name for BLAST/Genbank sort of format (default = not remove)
	--help:				help information
EOF
exit;
}
# read the parameters:
&GetOptions("fasta=s" => \$fasta, "table=s" => \$table, "bpperline=i" => \$bpperline,
			"header" => \$header, "lclrm" => \$lclrm, "help" => \$help) || &prompt;

if ($help) { &prompt; }
$bpperline = defined $bpperline ? $bpperline : 80;

###
### main
###
open(IN, $fasta) || die;
while (<IN>) {
	chomp;
	if (/^>(\S+)/) {
		if (defined $seq_name) {
			$seqhash{$seq_name} = $seq;
		}
    	$seq_name = $1;
		if ($lclrm) {
			$seq_name =~ s/lcl\|//g;
		}
		$seq = "";
 	 } else {
		$seq .= $_;
	}
}
# last element:
$seqhash{$seq_name} = $seq;
close IN;

### deal with each seq
my (@newseq, %newseq);
open(IN, $table) || die;
if ($header) {
	$_ = <IN>; ### skip first row
}
while (<IN>) {
	my @line = split(/\t/, $_);
	my ($oldctg, $start, $end, $strand, $newctg, $order) = @line;

	### extract sequences:
	my $frag;
	if (exists $seqhash{$oldctg}) {
		$frag = substr($seqhash{$oldctg}, $start - 1, $end - $start + 1);
		if ($strand eq "minus") {
			$frag = &revcom($frag);
		}
	} else {
		print "$oldctg does NOT exist\n";
		exit;
	}

	### add seqname to an array
	if (!exists $newseq{$newctg}) {
		push(@newseq, $newctg);
		print STDERR "$newctg\n";
	}

	### add sequence to hash
	$newseq{$newctg}{$order} = $frag;
}

### for each new sequence, merge according to the order and print
foreach my $eachnew (@newseq) {
	print ">$eachnew\n";
	my %newseq_order = %{$newseq{$eachnew}};
	my $eachnewseq;
	foreach (sort {$a <=> $b} keys %newseq_order) {
		$eachnewseq .= $newseq_order{$_};
	}
	&format_print($eachnewseq, $bpperline);
}

### module for formatted output:
sub format_print {
	my ($inseq, $formatlen) = @_;
	while (my $chunk = substr($inseq, 0, $formatlen, "")) {
		print "$chunk\n";
	}
}

### module for reverse complement sequences
sub revcom {
	my $ori_seq = shift @_;
	my $revcomseq = reverse($ori_seq);
	$revcomseq =~ tr/AGCTagct/TCGAtcga/;
	return $revcomseq;
}


text:
<?php

class OC_Connector_Sabre_ExceptionLoggerPlugin extends Sabre_DAV_ServerPlugin
{
	private $appName;

	/**
	 * @param string $loggerAppName app name to use when logging
	 */
	public function __construct($loggerAppName = 'webdav') {
		$this->appName = $loggerAppName;
	}

	/**
	 * This initializes the plugin.
	 *
	 * This function is called by Sabre_DAV_Server, after
	 * addPlugin is called.
	 *
	 * This method should set up the required event subscriptions.
	 *
	 * @param Sabre_DAV_Server $server
	 * @return void
	 */
	public function initialize(Sabre_DAV_Server $server) {

		$server->subscribeEvent('exception', array($this, 'logException'), 10);
	}

	/**
	 * Log exception
	 *
	 * @internal param Exception $e exception
	 */
	public function logException($e) {
		$exceptionClass = get_class($e);
		if ($exceptionClass !== 'Sabre_DAV_Exception_NotAuthenticated') {
			\OCP\Util::logException($this->appName, $e);
		}
	}
}


text:
package de.liz3.liz3web;

import com.jfoenix.controls.JFXButton;
import com.teamdev.jxbrowser.chromium.BrowserCore;
import com.teamdev.jxbrowser.chromium.BrowserPreferences;
import com.teamdev.jxbrowser.chromium.BrowserType;
import com.teamdev.jxbrowser.chromium.internal.Environment;
import de.liz3.liz3web.browserinc.FavoriteManager;
import de.liz3.liz3web.browserinc.History;
import de.liz3.liz3web.core.BrowserWindow;
import de.liz3.liz3web.core.BrowserSettings;
import de.liz3.liz3web.util.ClientSocket;
import de.liz3.liz3web.util.FavIconGetter;
import de.liz3.liz3web.util.extension.ExtensionManager;
import javafx.application.Application;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;

/**
 * Created by yannh on 15.04.2017.
 */
public class Liz3Web extends Application {

    public static Liz3Web liz3Web;
    private Vector<BrowserWindow> windows;
    private int debugLevel;
    private History history;
    private BrowserSettings settings;
    private FavoriteManager favoriteManager;
    private FavIconGetter favIconGetter;
    private ClientSocket clientSocket;
    private HashMap<String, JFXButton> generatedToolBar;
    private ExtensionManager extensionManager;

    public Liz3Web() {

        debug("Starting...", 0);
        debug("init..", 3);
        debug("setting static vars", 3);
        liz3Web = this;
        windows = new Vector<>();
        settings = new BrowserSettings();
        generatedToolBar = new HashMap<>();
        try {
            extensionManager = new ExtensionManager(new File(new File(".").getCanonicalPath(), "extensions"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            history = new History(new File(".").getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        history.loadIn();
        try {
            favoriteManager = new FavoriteManager(new File(".").getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        favoriteManager.loadIn();
        try {
            favIconGetter = new FavIconGetter(new File(".").getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        clientSocket = new ClientSocket();
        clientSocket.startSocket();

        debug("Setting Chromium preferences...", 2);

    }

    public static void run(String[] args) {

        BrowserPreferences.setUserAgent("Mozilla/5.0 (" + System.getProperty("os.name") + ") AppleWebKit/537.36 (KHTML, like Gecko) Liz3Web/1.0 Runtime/55.0.2883.87");
        BrowserPreferences.setChromiumSwitches("--remote-debugging-port=9223");
        BrowserPreferences.setChromiumVariable("GOOGLE_API_KEY", "AIzaSyBXo9GdKdTjWi6X_ZK0wyh8OfiIJLDc3yg");
        BrowserPreferences.setChromiumVariable("GOOGLE_DEFAULT_CLIENT_ID","347102639012-mfih61u3run5qkvfslr76f86k6e4gdkh.apps.googleusercontent.com");
        BrowserPreferences.setChromiumVariable("GOOGLE_DEFAULT_CLIENT_SECRET","qgU9nMYuTYuE3c0ahtXbqbIk");

       if(Environment.isMac()) BrowserCore.initialize();

       launch(args);

    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        Parameters parameters = getParameters();
        for(String x : parameters.getRaw()) {
            if(x.startsWith("-debug=")) {
                debugLevel = Integer.valueOf(x.split("=")[1]);
            }
        }
       debug("Starting gui...", 0);
        debug("Creating first window instance: ", 3);
        BrowserWindow window = new BrowserWindow(primaryStage);
        debug("Instance is: " + window.toString(), 3);
        windows.add(window);
        debug("Creating first tab", 2);
        window.newTab(null, BrowserType.HEAVYWEIGHT);
    }

    public void debug(String message, int debugLevel) {

        if (debugLevel <= this.debugLevel) {
            System.out.println("Liz3Web: [" + getFromDebug(debugLevel) + "]: " + message);
        }

    }

    private String getFromDebug(int level) {

        switch (level) {
            case 0:
                return "DEFAULT";
            case 1:
                return "ERROR";
            case 2:
                return "INFO";
            case 3:
                return "SERVE";
            default:
                return "DEFAULT";
        }
    }

    @Override
    public void stop() {
        System.exit(0);
    }

    public Vector<BrowserWindow> getWindows() {
        return windows;
    }

    public History getHistory() {
        return history;
    }

    public BrowserSettings getSettings() {
        return settings;
    }

    public FavoriteManager getFavoriteManager() {
        return favoriteManager;
    }

    public FavIconGetter getFavIconGetter() {
        return favIconGetter;
    }

    public HashMap<String, JFXButton> getGeneratedToolBar() {
        return generatedToolBar;
    }

    public void setGeneratedToolBar(HashMap<String, JFXButton> generatedToolBar) {
        this.generatedToolBar = generatedToolBar;
    }

    public ExtensionManager getExtensionManager() {
        return extensionManager;
    }
}


text:
import logging
import time
from struct import pack

try:
    import threading as _threading
except ImportError:
    import dummy_threading as _threading

from . import BaseBackend, BaseConnection
from ..certificate import BaseCertificate

# python 3 support
import six

# module level logger
LOG = logging.getLogger(__name__)

class Certificate(BaseCertificate):
    """ Dummy certificate """

    def load_context(self, cert_string=None, cert_file=None, key_string=None, key_file=None, passphrase=None):
        """ Returns None as we don't handle any context. """
        return None, None

    def dump_certificate(self, raw_certificate):
        """ Returns dummy contents. All dummy certificates are equal. """
        return "CERTIFICATE"

    def dump_digest(self, raw_certificate, digest):
        """ Returns dummy digsst. All dummy certificates are equal. """
        return self.dump_certificate(raw_certificate)

class Backend(BaseBackend):
    """ Dummy backend designed for testing without performing real IO. Serves
        as an exmple for your custom backends.
    """
    # simulate stdio behavior
    can_detect_close = False

    def __init__(self, push=None, feedback=None, **options):
        """ Create new backend.

            :Arguments:
                - push (list): list of status codes to return while sending messages.
                - feedback (int): number of tokens to generate in the feedback stream.
        """
        super(Backend, self).__init__(**options)
        self.push_results = push
        self.push_result_pos = -1
        self.feedback_results = feedback
        self.new_connections = 0
        assert (push is not None) ^ (feedback is not None), "Push results or feedback stream must be provided"

    def get_new_connection(self, address, certificate, timeout=None):
        """ Open a new connection.

            :Arguments:
                - address (tuple): target (host, port).
                - certificate (:class:`Certificate`): certificate instance.
                - timeout (float): connection timeout in seconds
        """
        self.new_connections += 1
        self.push_result_pos += 1
        return Connection(self, address, certificate)

    def get_certificate(self, cert_params):
        """ Create/load certificate from parameters. """
        return Certificate(**cert_params)

    def create_lock(self):
        """ Provides semaphore with ``threading.Lock`` interface. """
        return _threading.Lock()

class Connection(BaseConnection):
    """ Dummy connection. """

    def __init__(self, pool, address, certificate):
        """ Create new dummy connection.

            :Arguments:
                - pool (:class:`Backend`): dummy backend.
                - address (tuple): target host and port.
                - certificate (:class:`Certificate`): provider certificate.
        """
        super(Connection, self).__init__(address, certificate)
        self.pool = pool
        self._closed = False

    def closed(self):
        """ Returns True if :func:`close` has been explicitly called. """
        return self._closed

    def close(self):
        """ Marks this connection as closed. """
        self._closed = True

    def reset(self):
        """ Reset dummy connection to use next result record. """
        pass

    def write(self, data, timeout):
        """ Does nothing, always succeeds. """
        if self.closed():
            raise IOError("Connection closed")

    def peek(self, size):
        """ Always returns None as we never fail prematurely. """
        return None

    def read(self, size, timeout):
        """ Iterates over preconfigured send/feedback responses. """
        if self.closed():
            return None

        if self.pool.push_results is not None:
            # we are push connection
            ret = self.pool.push_results[self.pool.push_result_pos % len(self.pool.push_results)]
            if ret is not None:
                ret = pack(">BBI", 8, ret, 0)

            return ret
        else: # feedback mode
            ret = []
            for x in range(0, self.pool.feedback_results):
                token = six.b("test_{}".format(x))
                ret.append(pack(">IH{}s".format(len(token)), int(time.time()), len(token), token))

            self.close()
            return six.binary_type().join(ret)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Python: module telemetry.internal.browser.browser</title>
<meta charset="utf-8">

<big><big>telemetry.internal.browser.browser</big></big>	index
telemetry/internal/browser/browser.py

<tt># Copyright 2012 The Chromium Authors. All rights reserved.

# Use of this source code is governed by a BSD-style license that can be

# found in the LICENSE file.</tt>

<big>Modules</big>

<tt>      </tt>

telemetry.internal.app

telemetry.internal.backends.browser_backend

telemetry.internal.browser.browser_credentials

catapult_base.cloud_storage

	telemetry.decorators

telemetry.internal.util.exception_formatter

telemetry.core.exceptions

telemetry.internal.browser.extension_dict

	logging

telemetry.core.profiling_controller

sys

telemetry.internal.browser.tab_list

	telemetry.internal.browser.web_contents

<big>Classes</big>

<tt>      </tt>

telemetry.internal.app.App(__builtin__.object)

Browser

class Browser(telemetry.internal.app.App)

<tt>   </tt>
<tt>A running browser instance that can be controlled in a limited way.

To create a browser instance, use browser_finder.FindBrowser.

Be sure to clean up after yourself by calling Close() when you are done with

the browser. Or better yet:

  browser_to_create = FindBrowser(options)

  with browser_to_create.Create(options) as browser:

    ... do all your operations on browser here
 </tt>

Method resolution order:

Browser

telemetry.internal.app.App

__builtin__.object

Methods defined here:

Close(self)

<tt>Closes this browser.</tt>

DumpMemory(self, timeout=90)

GetStackTrace(self)

GetStandardOutput(self)

GetSystemInfo(self)

<tt>Returns low-level information about the system, if available.

See the documentation of the SystemInfo class for more details.</tt>

SetMemoryPressureNotificationsSuppressed(self, suppressed, timeout=90)

SimulateMemoryPressureNotification(self, pressure_level, timeout=90)

__init__(self, backend, platform_backend, credentials_path)

Data descriptors defined here:

browser_type

cpu_stats

<tt>Returns a dict of cpu statistics for the system.

{ 'Browser': {

    'CpuProcessTime': S,

    'TotalTime': T

  },

  'Gpu': {

    'CpuProcessTime': S,

    'TotalTime': T

  },

  'Renderer': {

    'CpuProcessTime': S,

    'TotalTime': T

  }

}

Any of the above keys may be missing on a per-platform basis.</tt>

extensions

foreground_tab

memory_stats

<tt>Returns a dict of memory statistics for the browser:

{ 'Browser': {

    'VM': R,

    'VMPeak': S,

    'WorkingSetSize': T,

    'WorkingSetSizePeak': U,

    'ProportionalSetSize': V,

    'PrivateDirty': W

  },

  'Gpu': {

    'VM': R,

    'VMPeak': S,

    'WorkingSetSize': T,

    'WorkingSetSizePeak': U,

    'ProportionalSetSize': V,

    'PrivateDirty': W

  },

  'Renderer': {

    'VM': R,

    'VMPeak': S,

    'WorkingSetSize': T,

    'WorkingSetSizePeak': U,

    'ProportionalSetSize': V,

    'PrivateDirty': W

  },

  'SystemCommitCharge': X,

  'SystemTotalPhysicalMemory': Y,

  'ProcessCount': Z,

}

Any of the above keys may be missing on a per-platform basis.</tt>

profiling_controller

supports_cpu_metrics

supports_extensions

supports_memory_dumping

supports_memory_metrics

supports_overriding_memory_pressure_notifications

supports_power_metrics

supports_system_info

supports_tab_control

tabs

Methods inherited from telemetry.internal.app.App:

__enter__(self)

__exit__(self, *args)

Data descriptors inherited from telemetry.internal.app.App:

__dict__

<tt>dictionary for instance variables (if defined)</tt>

__weakref__

<tt>list of weak references to the object (if defined)</tt>

app_type

platform


text:
package com.dci.intellij.dbn.data.editor.color;

import com.dci.intellij.dbn.common.ui.DBNColor;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.ColorKey;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.ui.SimpleTextAttributes;

import java.awt.Color;

public interface DataGridTextAttributesKeys {
    Color DEFAULT_SELECTION_FG_COLOR = new Color(255, 255, 255);
    Color DEFAULT_SELECTION_BG_COLOR = new Color(82, 109, 165);

    interface Colors {
        Color DEFAULT_BACKGROUND   = HighlighterColors.TEXT.getDefaultAttributes().getBackgroundColor();
        Color DEFAULT_FOREGROUND   = HighlighterColors.TEXT.getDefaultAttributes().getForegroundColor();
        Color LIGHT_BACKGROUND     = new DBNColor(new Color(0xf4f4f4), new Color(0x393939));
        Color LIGHT_FOREGROUND     = new DBNColor(new Color(0x646464), new Color(0x999999));
        Color ERROR_BACKGROUND     = HighlighterColors.BAD_CHARACTER.getDefaultAttributes().getBackgroundColor();
        Color PK_FOREGROUND        = new DBNColor(new Color(0x4569A7), new Color(0x95A8B4));
        Color PK_BACKGROUND        = new DBNColor(new Color(0xF7F7FF), new Color(0x2B3447));
        Color FK_FOREGROUND        = new DBNColor(new Color(0x3F6B3F), new Color(0xA1A8A1));
        Color FK_BACKGROUND        = new DBNColor(new Color(0xF7FFF7), new Color(0x2A3B2A));
        Color CARET_ROW_BACKGROUND = EditorColorsManager.getInstance().getGlobalScheme().getColor(EditorColors.CARET_ROW_COLOR);
    }

    interface Attributes {
        TextAttributes DEFAULT     = new TextAttributes(Colors.DEFAULT_FOREGROUND, Colors.DEFAULT_BACKGROUND, null, null, SimpleTextAttributes.STYLE_PLAIN);
        TextAttributes DELETED     = new TextAttributes(Colors.LIGHT_FOREGROUND, Colors.LIGHT_BACKGROUND, null, null, SimpleTextAttributes.STYLE_PLAIN);
        TextAttributes READONLY    = new TextAttributes(Colors.LIGHT_FOREGROUND, Colors.LIGHT_BACKGROUND, null, null, SimpleTextAttributes.STYLE_PLAIN);
        TextAttributes ERROR       = new TextAttributes(Colors.DEFAULT_FOREGROUND, Colors.ERROR_BACKGROUND, null, null, SimpleTextAttributes.STYLE_PLAIN);
        TextAttributes PRIMARY_KEY = new TextAttributes(Colors.PK_FOREGROUND,Colors.PK_BACKGROUND, null, null, SimpleTextAttributes.STYLE_PLAIN);
        TextAttributes FOREIGN_KEY = new TextAttributes(Colors.FK_FOREGROUND, Colors.FK_BACKGROUND, null, null, SimpleTextAttributes.STYLE_PLAIN);
    }

    ColorKey CARET_ROW_BACKGROUND = ColorKey.createColorKey("DBNavigator.TextAttributes.DataEditor.CaretRowBackground", Colors.CARET_ROW_BACKGROUND);

    TextAttributesKey PLAIN_DATA     = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.DataEditor.PlainData",    Attributes.DEFAULT);
    TextAttributesKey MODIFIED_DATA  = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.DataEditor.ModifiedData", new TextAttributes(null, null, null, null, SimpleTextAttributes.STYLE_BOLD));
    TextAttributesKey DELETED_DATA   = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.DataEditor.DeletedData",  Attributes.DELETED);
    TextAttributesKey ERROR_DATA     = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.DataEditor.ErrorData",    Attributes.ERROR);
    TextAttributesKey READONLY_DATA  = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.DataEditor.ReadonlyData", Attributes.READONLY);
    TextAttributesKey LOADING_DATA   = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.DataEditor.LoadingData",  Attributes.READONLY);
    TextAttributesKey PRIMARY_KEY    = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.DataEditor.PrimaryKey",   Attributes.PRIMARY_KEY);
    TextAttributesKey FOREIGN_KEY    = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.DataEditor.ForeignKey",   Attributes.FOREIGN_KEY);
    TextAttributesKey SELECTION      = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.DataEditor.Selection",    new TextAttributes(DEFAULT_SELECTION_FG_COLOR, DEFAULT_SELECTION_BG_COLOR, null, null, SimpleTextAttributes.STYLE_PLAIN));
}


text:
'use strict';
var Aggregator = require('../aggregator');

module.exports = new Aggregator('scoreGPSI', 'Google Page Speed Insights Score',
  'The score calculated by our friends at Google.', 'rule',
  '', 0,
  function(pageData) {
    if (pageData.gpsi) {
      this.stats.push(pageData.gpsi.score);
    }
  });


text:
angular-jmpress
===============

An angular module adapter for jmpress

[![Build Status](https://travis-ci.org/web-stories/angular-jmpress.svg)](https://travis-ci.org/web-stories/angular-jmpress)
[![Build status](https://ci.appveyor.com/api/projects/status/uvnv7ugeempbottw?svg=true)](https://ci.appveyor.com/project/FagnerMartinsBrack/angular-jmpress)
[![devDependency Status](https://david-dm.org/web-stories/angular-jmpress/dev-status.svg)](https://david-dm.org/web-stories/angular-jmpress#info=devDependencies)

**DISCLAIMER:**
This project is a **WORK IN PROGRESS**, and currently supports only some basic features of jmpress. Feel free to open a pull request and implement additional features.

## Get started

1. jmpress is a jquery plugin, so first you need to include the latest [jquery](jquery.com) version in your page.

2. Also download and include the latest [angular](https://angularjs.org/) version.

3. jmpress does a lot of things angular can do out of the box, so not all modules are necessary, but a custom build of jmpress with the following modules are required:

    * `core.js` - Necessary to expose plugin facility
    * `near.js` - It is used a dependency for several modules
    * `transform.js` - Necessary to apply transformation on steps
    * `active.js` - Necessary to apply active classes

It is necessary that you pick `circular.js`, which handles the default mechanism for selecting the slides using the default methods (next, prev, home, etc.), or you can roll your own using jmpress plugin facility.

Also, it is necessary to specify the viewport width, so jmpress is able to adjust itself to fit the screen accordingly:

```javascript
// A viewport config is necessary to enable auto resize of the content on window resize
$.jmpress( "beforeActive", function( step, eventData ) {
	eventData.stepData.viewPortWidth = 2000;
});
```

*Note1: The relationship between the size of the viewport and the steps width determines the size of the contents, to fit the whole screen, also declare `.step { width: 2000px; }` in the css.*

*Note2: This project supports AMD, so you can create a custom jquery.jmpress.js module with all dependencies. For details see [here](https://github.com/web-stories/angular-jmpress/blob/master/src/main/jquery.jmpress.js).*

4. Last, but no least, you should include the `angular-jmpress.js` to enable angular functionalities.

*Note: Due to some quirks in the original jmpress project, it is necessary some changes to make it work with angular-jmpress. Theres is a [fork](https://github.com/web-stories/jmpress.js) adapted and being tested on angular-jmpress. You can try to build a custom jmpress build from original repo, but do it at your own risk.*

## Usage

First thing you should do is specify a container for jmpress inside a controller, the container directive is called `jmpress-root`:

```html
<div ng-controller="MyController">
  <div jmpress-root></div>
</div>
```

After that you need to specify the property that is going to be watched for an array of step objects, in this case we use `presentation.slides`:

```html
<div ng-controller="MyController">
  <div jmpress-root
      jmpress-steps="presentation.slides"></div>
</div>
```

We also need to declare the step elements. The steps are updated for each change in the array of step objects, but we still need to declare the HTML structure:

```html
<div ng-controller="PresentationController">
  <div jmpress-root
      jmpress-steps="presentation.slides">
    <div class="step" ng-repeat="step in steps">
      Step {{ step.number }}
    </div>
  </div>
</div>
```

*Note that `ng-repeat` uses `step in steps` instead of `step in presentation.slides`. The inner content of the root directive is bound to the isolated scope of the root directive, not the outside controller scope.*

After that you just need to start your angular module and include `jmpress` as its dependency:

```javascript
angular.module( "myModule", [ "jmpress" ] )
  .controller( "PresentationController", function( $scope ) {
    $scope.presentation = {
      slides: [{
        number: 1
      }, {
        number: 2
      }]
    };
  });
```

If you want to see thing working, check out the [demo](https://github.com/web-stories/angular-jmpress/tree/master/src/gh-pages/demo) and the [test files](https://github.com/web-stories/angular-jmpress/tree/master/src/test)

## jmpress service

angular-jmpress has a service called `jmpress`, which contains some utility methods to
retrieve the presentation information.

Example:

```javascript
angular.module( "myModule", [ "jmpress" ] )
  .controller(function( $scope, jmpress ) {
    $scope.steps = [{
      active: true
    }];
    var active = jmpress.getActive( $scope.steps );
  });
```

### getActive( steps )

Retrieves the current active step or `undefined` if there's no active step.

```javascript
jmpress.getActive( steps ); // { active: true }
```

### getActive( steps, index )

Retrieves the step relative to the current active step, or `undefined` if there's no active step or
if the step is out of range.

```javascript
var steps = [{
  number: 1
}, {
  number: 2,
  active: true
}, {
  number: 3
}];

jmpress.getActive( steps, 1 ); // { number: 3 }
jmpress.getActive( steps, -1 ); // { number: 1 }
```

### activate( steps, callback( step ) )

Changes the current activated step according to the condition of a given callback.

The callback will be executed for each step in the steps array. If it returns `true`, it changes the
activated step for the one in which the callback returned `true`.

* If more than one condition returns `true`, the behavior is undefined.
* If the "active" property of a step is manipulated inside a callback, the behavior is undefined.

```javascript
var steps = [{
  number: 1
}, {
  number: 2
}];

// [{ number: 1, active: true }, { number: 2 }]
jmpress.activate( steps, function( step ) {
	return step.number === 1;
});
```

## Initial step

angular-jmpress was built to be able to load all steps asynchronously using angular. There are some specific rules for how angular-jmpress decides which one will be the initial step after the first digest cycle. The jmpress default plugin mechanism is ignored.

1. If an active step is defined before loading the first steps, then angular-jmpress will use that as the initial step.
2. If an active step is not defined before loading the first steps, then angular-jmpress will fire the callback registration (see below).

### Callback registration

Along with jmpress default callback registration, angular-jmpress provides one of its own through the jmpress service for some specific cases like this one. In this case, instead of returning the DOM element, it returns the step object that is going to start activated.

The returned step object from the callback should be the same instance of the object that should start activated.

```javascript
jmpress.register( "selectInitialStep", function( firstSteps ) {
	// Start with the last step activated
	return firstSteps[ firstSteps.length - 1 ];
});
```

## Manual release process

1. Remove `-pre` suffix on `package.json` and `bower.json` version
2. Commit "Create version x.x.x"
3. Create tag
4. Create github release
5. Bump the version and add the `-pre` suffix on on `package.json` and `bower.json`


text:
var app = angular.module('KubernetesScaleDemo', ['ngMaterial', 'chart.js'])
    .config(['ChartJsProvider', function (ChartJsProvider) {
		// Configure all charts
		ChartJsProvider.setOptions({
			animation: false
		    });
	    }]);

var limit = 40;

var ScaleApp = function(http, scope, q) {
    this.http = http;
    this.scope = scope;
    this.q = q;

    this.labels = [];
    for (var i = 0; i < limit; i++) {
	this.labels.push(i);
    }

    this.qpsData = [ [] ];
    this.qpsSeries = ['QPS'];
    this.qpsOptions = {
	"scaleOverride" : true,
        "scaleSteps" : 10,
        "scaleStepWidth" : 100000,
        "scaleStartValue" : 0,
	"bezierCurve": false
    }
    this.qpsColors = [{
	"fillColor": 'rgba(232, 127, 12, 0.2)',
	"strokeColor": 'rgba(232, 127, 12, 0.8)',
	"highlightFill": 'rgba(232, 127, 12, 0.8)',
	"highlightStroke": 'rgba(232, 127, 12, 0.8)'
	}];

    this.latencyData = [ [], [] ];
    this.latencySeries = ['Mean', '99th'];
    this.latencyOptions = {
	"scaleOverride" : true,
        "scaleSteps" : 10,
        "scaleStepWidth" : 100,
        "scaleStartValue" : 0,
	"scaleLabel": "<%=value + 'ms'%>"
    }

    this.availData = [ [], [] ];
    this.availSeries = ['Availability', 'Errors' ];
    this.availOptions = {
	"scaleOverride": true,
	"scaleSteps": 10,
	"scaleStepWidth": 10,
	"scaleStartValue": 0,
    };
    this.availColors = [{
	"fillColor": 'rgba(47, 132, 71, 0.2)',
	"strokeColor": 'rgba(47, 132, 71, 0.8)',
	"highlightFill": 'rgba(47, 132, 71, 0.8)',
	"highlightStroke": 'rgba(47, 132, 71, 0.8)'
    },
    {
	"fillColor": 'rgba(132, 47, 71, 0.2)',
	"strokeColor": 'rgba(132, 47, 71, 0.8)',
	"highlightFill": 'rgba(132, 47, 71, 0.8)',
	"highlightStroke": 'rgba(132, 47, 71, 0.8)'
   }];
};

ScaleApp.prototype.onClick = function(data) {
};

// Fetch data from the server and update the data to display
ScaleApp.prototype.refresh = function() {
    if (this.refreshInProgress) {
	return;
    }
    this.refreshInProgress = true;
    var promises = [];
    promises.push(this.http.get("/api/v1/proxy/namespaces/default/services/aggregator/")
    .success(function(data) {
	    this.fullData = data;
	}.bind(this))
    .error(function(data) {
	    console.log("Error!");
	    console.log(data);
	}));

    promises.push(this.http.get("/api/v1/pods?labelSelector=run=nginx")
    .success(function(data) {
	    this.servers = data;
	}.bind(this))
    .error(function(data) {
	    console.log("Error!");
	    console.log(data);
	}));

    promises.push(this.http.get("/api/v1/pods?labelSelector=run=vegeta")
    .success(function(data) {
	    this.loadbots = data;
	}.bind(this))
    .error(function(data) {
	    console.log("Error!");
	    console.log(data);
	}));
    var doneFn = function() { this.refreshInProgress = false; }.bind(this);
    this.q.all(promises).then(doneFn, doneFn);
};

ScaleApp.prototype.getServerCount = function() {
    if (!this.servers || !this.servers.items) {
	return 0;
    }
    var count = 0;
    angular.forEach(this.servers.items, function(pod) {
	    if (pod.status.phase == "Running") {
		count++;
	    }
	});
    return count;
};

ScaleApp.prototype.getLoadbotCount = function() {
    if (!this.loadbots || !this.loadbots.items) {
	return 0;
    }
    var count = 0;
    angular.forEach(this.loadbots.items, function(pod) {
	    if (pod.status.phase == "Running") {
		count++;
	    }
	});
    return count;
};

ScaleApp.prototype.getLoadbotReports = function() {
    if (!this.loadbots) {
	return nil
    }
    var promises = []
    for (var i = 0; i < this.loadbots.items.length; i++) {
	var pod = this.loadbots.items[i];
	var promise = this.http.get("/api/v1/proxy/namespaces/default/pods/" + pod.metadata.name + ":8080/")
	.success(function(data) {
		this.loadData = data;
	    }.bind(pod))
	.error(function(data) {
		console.log("Error loading loadbot");
		console.log(data);
	    });
	promises.push(promise)
    }

    this.q.all(promises).then(function() {
	    this.updateGraphData();
	}.bind(this));

};

ScaleApp.prototype.slideWindow = function(data, newPoint) {
    if (data.length < limit) {
	data.push(newPoint);
	return data;
    }
    var newData = [];
    for (var i = 0; i < limit; i++) {
	newData[i] = data[i + 1];
    }
    newData[limit - 1] = newPoint;

    return newData;
}

ScaleApp.prototype.updateGraphData = function() {
    var qps = this.getQPS();
    var latency = this.getLatency();
    var success = this.getSuccess();

    this.qpsData[0] = this.slideWindow(this.qpsData[0], qps);
    this.latencyData[0] = this.slideWindow(this.latencyData[0], latency["mean"]);
    this.latencyData[1] = this.slideWindow(this.latencyData[1], latency["99th"]);
    this.availData[0] = this.slideWindow(this.availData[0], success);
    this.availData[1] = this.slideWindow(this.availData[1], 100 - success);
};

ScaleApp.prototype.getQPS = function() {
    if (!this.fullData) {
	return 0;
    }
    var qps = 0;
    angular.forEach(this.fullData, function(value) {
	    if (value && value.rate) {
		qps += value.rate;
	    }
	});
    return qps;
};

ScaleApp.prototype.getSuccess = function() {
    if (!this.fullData) {
	return 0;
    }
    var success = 0;
    var count = 0;
    angular.forEach(this.fullData, function(value) {
	    if (value && value.success) {
		success += value.success * 100;
		count++;
	    }
	});
    return success / count;
};

ScaleApp.prototype.getLatency = function() {
    if (!this.fullData) {
	return {};
    }
    var latency = {
	"mean": 0,
	"99th": 0
    };
    var count = 0;
    angular.forEach(this.fullData, function(datum) {
	    if (datum.latencies) {
		latency.mean += datum.latencies.mean / 1000000;
		latency["99th"] += datum.latencies["99th"] / 1000000;
		count++;
	    }
	});
    if (count == 0) {
	return {};
    }
    latency.mean = (latency.mean/count);
    latency["99th"] = (latency["99th"]/count);

    return latency;
};

ScaleApp.prototype.getNumServers = function() {
    return this.getNumPods(this.servers);
};

ScaleApp.prototype.getNumLoadbots = function() {
    return this.getNumPods(this.loadbots);
};

ScaleApp.prototype.getNumPods = function(pods) {
    if (pods) {
	return pods.items.length;
    }
    return 0;
};

app.controller('AppCtrl', ['$scope', '$http', '$interval', '$q', function($scope, $http, $interval, $q) {
    $scope.controller = new ScaleApp($http, $scope, $q);
    $scope.controller.refresh();

    $interval($scope.controller.refresh.bind($scope.controller), 1000)
    $interval($scope.controller.updateGraphData.bind($scope.controller), 1000)
}]);


text:
package com.facebook.buck.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import com.facebook.buck.test.result.type.ResultType;

import org.junit.Test;

/**
 * Unit test for {@link TestResultSummary}.
 */
public class TestResultSummaryTest {

  @Test
  public void testSuccessSummary() {
    TestResultSummary testResultSummary = new TestResultSummary(
        "com.facebook.buck.rules.TestResultSummaryTest",
        "testGetters",
        ResultType.SUCCESS,
        123L,
        null /* message */,
        null /* stacktrace */,
        null /* stdOut */,
        null /* stdErr */);
    assertEquals("testGetters", testResultSummary.getTestName());
    assertTrue(testResultSummary.isSuccess());
    assertEquals(123L, testResultSummary.getTime());
    assertNull(testResultSummary.getMessage());
    assertNull(testResultSummary.getStacktrace());
    assertNull(testResultSummary.getStdOut());
    assertNull(testResultSummary.getStdErr());
    assertEquals("PASS  123ms com.facebook.buck.rules.TestResultSummaryTest#testGetters()",
        testResultSummary.toString());
  }

  @Test
  public void testFailureSummary() {
    String assertionFailedMessage = "expected:<PASS  123ms te[]tGetters(com.faceboo...> " +
        "but was:<PASS  123ms te[s]tGetters(com.faceboo...>";
    String stacktrace = "at org.junit.Assert.assertEquals(Assert.java:123)";
    String stdOut = "STDOUT: getTime() returned 452L";
    String stdErr = "STDERR: getTime() returned 452L";
    TestResultSummary testResultSummary = new TestResultSummary(
        "com.facebook.buck.rules.TestResultSummaryTest",
        "testGetters",
        ResultType.FAILURE,
        456L,
        assertionFailedMessage,
        stacktrace,
        stdOut,
        stdErr);
    assertEquals("testGetters", testResultSummary.getTestName());
    assertFalse(testResultSummary.isSuccess());
    assertEquals(456L, testResultSummary.getTime());
    assertEquals(assertionFailedMessage, testResultSummary.getMessage());
    assertEquals(stacktrace, testResultSummary.getStacktrace());
    assertEquals(stdOut, testResultSummary.getStdOut());
    assertEquals(stdErr, testResultSummary.getStdErr());
    assertEquals("FAIL  456ms com.facebook.buck.rules.TestResultSummaryTest#testGetters()",
        testResultSummary.toString());
  }
}


text:
quickplots
==========

Allows quick plotting of json objects, programmatically or on command line.