text:
package org.jetbrains.plugins.scala.lang.parser.parsing.builder

import com.intellij.lang.PsiBuilder
import com.intellij.lang.impl.PsiBuilderAdapter
import com.intellij.openapi.util.text.StringUtil.isWhiteSpace
import com.intellij.psi.impl.source.resolve.FileContextUtil.CONTAINING_FILE_KEY
import org.jetbrains.plugins.scala.{ScalaVersion, isUnitTestMode}
import org.jetbrains.plugins.scala.lang.parser.IndentationWidth
import org.jetbrains.plugins.scala.project.ProjectPsiFileExt.enableFeaturesCheckInTests
import org.jetbrains.plugins.scala.project._

// TODO: now isScala3 is properly set only in org.jetbrains.plugins.scala.lang.parser.ScalaParser
//  update all ScalaPsiBuilderImpl instantiations passing proper isScala3 value
class ScalaPsiBuilderImpl(
  delegate:              PsiBuilder,
  override val isScala3: Boolean,
  presetFeatures:        Option[ScalaFeatures] = None
) extends PsiBuilderAdapter(delegate)
    with ScalaPsiBuilder {

  import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenType._
  import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes._

  private var newlinesEnabled = List.empty[Boolean]

  private var inBracedRegion: Int = 0

  private var inQuotedPattern: Int = 0

  private lazy val containingFile = Option {
    myDelegate.getUserData(CONTAINING_FILE_KEY)
  }

  override def skipExternalToken(): Boolean = false

  override final lazy val isMetaEnabled: Boolean = features.hasMetaEnabled

  override final lazy val isStrictMode: Boolean =
    containingFile.exists(_.isCompilerStrictMode)

  override final lazy val features: ScalaFeatures = presetFeatures.getOrElse {
    def featuresByVersion: ScalaFeatures = {
      val version = if (isScala3) ScalaVersion.Latest.Scala_3_0 else ScalaVersion.Latest.Scala_2_13
      ScalaFeatures.onlyByVersion(version)
    }

    containingFile match {
      case Some(file) =>
        file.module match {
          case Some(module) => module.features
          case None         => ScalaFeaturePusher.getFeatures(file).getOrElse(featuresByVersion)
        }
      case None => featuresByVersion
    }
  }

  override final lazy val underscoreWildcardsDisabled: Boolean = features.hasUnderscoreWildcardsDisabled

  final lazy val scalaLanguageLevel: Option[ScalaLanguageLevel] = Option(features.languageLevel)

  final private lazy val isAtLeast2_12: Boolean = scalaLanguageLevel.exists(_ >= ScalaLanguageLevel.Scala_2_12)

  override final def isTrailingComma: Boolean = getTokenType match {
    case `tCOMMA` => features.hasTrailingCommasEnabled ||
      (isUnitTestMode && !enableFeaturesCheckInTests)
    case _ => false
  }

  override final def isIdBinding: Boolean =
    this.invalidVarId || isAtLeast2_12

  override def newlineBeforeCurrentToken: Boolean =
    findPreviousNewLineSafe.isDefined

  override def twoNewlinesBeforeCurrentToken: Boolean =
    findPreviousNewLineSafe.exists { text =>
      s"start $text end".split('\n').exists { line =>
        line.forall(isWhiteSpace)
      }
    }

  override final def disableNewlines(): Unit =
    newlinesEnabled = false :: newlinesEnabled

  override final def enableNewlines(): Unit =
    newlinesEnabled = true :: newlinesEnabled

  override final def enterBracedRegion(): Unit =
    inBracedRegion += 1

  override final def exitBracedRegion(): Unit = {
    assert(isInsideBracedRegion)
    inBracedRegion -= 1
  }

  override final def isInsideBracedRegion: Boolean = inBracedRegion > 0

  override final def enterQuotedPattern(): Unit =
    inQuotedPattern += 1

  override final def exitQuotedPattern(): Unit = {
    assert(inQuotedPattern > 0)
    inQuotedPattern -= 1
  }

  override final def isInQuotedPattern: Boolean =
    inQuotedPattern > 0

  override final def restoreNewlinesState(): Unit = {
    assert(newlinesEnabled.nonEmpty)
    newlinesEnabled = newlinesEnabled.tail
  }

  protected final def isNewlinesEnabled: Boolean =
    newlinesEnabled.isEmpty || newlinesEnabled.head

  private def findPreviousNewLineSafe =
    if (isNewlinesEnabled && canStartStatement)
      this.findPreviousNewLine
    else
      None

  private def canStartStatement: Boolean = getTokenType match {
    case null => false
    case `kCATCH` |
         `kELSE` |
         `kEXTENDS` |
         `kFINALLY` |
         `kMATCH` |
         `kWITH` |
         `kYIELD` |
         `tCOMMA` |
         `tDOT` |
         `tSEMICOLON` |
         `tCOLON` |
         `tASSIGN` |
         `tFUNTYPE` |
         `ImplicitFunctionArrow` |
         `tCHOOSE` |
         `tUPPER_BOUND` |
         `tLOWER_BOUND` |
         `tVIEW` |
         `tINNER_CLASS` |
         `tLSQBRACKET` |
         `tRSQBRACKET` |
         `tRPARENTHESIS` |
         `tRBRACE` => false
    case `kCASE` =>
      this.predict { builder =>
        builder.getTokenType match {
          case ObjectKeyword |
               ClassKeyword |
               `tIDENTIFIER` => true
          case _ =>
            false
        }
      }
    case _ => true
  }

  private var indentationStack = List(IndentationWidth.initial)

  def isScala3IndentationBasedSyntaxEnabled: Boolean =
    features.indentationBasedSyntaxEnabled

  override def currentIndentationWidth: IndentationWidth =
    indentationStack.head

  override def pushIndentationWidth(width: IndentationWidth): Unit =
    indentationStack ::= width

  override def popIndentationWidth(): IndentationWidth = {
    val top :: rest = indentationStack
    indentationStack = rest
    top
  }
}


text:
/**
* CellPhoneRecord.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs        :: http://sailsjs.org/#!documentation/models
*/

module.exports = {

  attributes: {
    phone : {
        model: 'CellPhone'
    },
    docid: {
        type: 'integer',
    },
    status : {
        type: 'string'
    },
    active : {
        type: 'boolean',
        defaultsTo: true
    }
  }
};

redpajama_set_name: RedPajamaGithub


text:
package com.kingleung.androidhodgepodge.basic.butterknife;

import com.kingleung.androidhodgepodge.BuildConfig;
import com.kingleung.androidhodgepodge.core.TestTheApplication;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;

/**
 * @author kingleung
 *         Created on 2017/9/5.
 */
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, application = TestTheApplication.class)
public class ButterKnifeActivityTest {

    @Test
    public void testButterKnife() throws Exception {
        ActivityController<ButterKnifeActivity> controller =
                Robolectric.buildActivity(ButterKnifeActivity.class).create().start().resume().visible();
        ButterKnifeActivity activity = controller.get();

        assertNotNull(activity);
        assertNotNull(activity.mTextView);
        assertNotNull(activity.mAppName);
        assertNotNull(activity.mButton);
        assertEquals("Butter Knife", activity.mTextView.getText().toString());
        assertEquals("AndroidHodgepodge", activity.mAppName);
        activity.mButton.performClick();
        assertEquals("AndroidHodgepodge", activity.mTextView.getText().toString());

        controller.stop();
        controller.destroy();
    }
}


text:
#include <iostream>
#include <future>
#include <vector>
#include <string>
#include <cassert>
#include <limits>
#include <cmath>
#include <utility>
#include <chrono>

#include "prime_factorization.h"
#include "prime_table.h"

using std::vector; using std::string;
using std::future; using std::async; using std::launch;
using std::cout;
using std::ceil; using std::sqrt;
using std::move;
using namespace std::chrono;

constexpr uint32_t kAMOUNT = 1000000;

static void factorize(PrimeFactorization* out, const vector<uint32_t>& data,
               uint32_t start_ele, uint32_t num_eles)
{
    for (uint32_t i = 0; i < num_eles; i++) {
        out[i] = PrimeFactorization(data[i + start_ele]);
    }
}

/* TODO Can be improved by using stride and offset, this is because nums may be
   sorted and larger numbers will take longer to factorize causing the jobs with
   larger numbers taking more time... good exercise I suppose, the main goal was
   to use futures correctly and show how they improve performance. That goal is
   accomlished */
void parallel_factorize(vector<PrimeFactorization> &pf,
                        const vector<uint32_t>& nums,
                        const uint32_t jobs = 4)
{
    assert(jobs < pf.size() && jobs != 0); // Would want different solution for this case

    // set the amount of work for each job and account for division rounding
    const uint32_t nums_per_job = nums.size() / jobs;
    const uint32_t nums_last_job = nums.size() - nums_per_job * (jobs - 1);

    vector<future<void>> futures(jobs);

    // launch jobs asynchronously
    for (uint32_t i = 0; i < jobs - 1; i++) {
        const uint32_t start_idx = i * nums_per_job;
        futures[i] = async(launch::async, factorize,
            pf.data() + start_idx, nums, start_idx, nums_per_job);
    }

    // special case for last job to account for division rounding
    const uint32_t start_idx = nums.size() - nums_last_job;
    futures[jobs - 1] = async(launch::async, factorize,
        pf.data() + start_idx, nums, start_idx, nums_last_job);

    // wait for all jobs to finish
    for (auto& f : futures) {
        f.get();
    }
}

int main(int argc, char* argv[]) {
    PrimeTable::init(static_cast<string>(kPRIMETABLEBLOBNAME));
    vector<PrimeFactorization> pf_vec0(kAMOUNT);
    vector<PrimeFactorization> pf_vec1(kAMOUNT);

    vector<uint32_t> nums;
    nums.reserve(kAMOUNT);

    for (uint32_t i = 0; i < kAMOUNT; i++) {
        nums.push_back(i);
    }

    auto t0 = high_resolution_clock::now();
    parallel_factorize(pf_vec0, nums, 8);
    auto t1 = high_resolution_clock::now();
    auto span0 = duration_cast<duration<double>>(t1 - t0);

    auto t2 = high_resolution_clock::now();
    parallel_factorize(pf_vec1, nums, 1);
    auto t3 = high_resolution_clock::now();
    auto span1 = duration_cast<duration<double>>(t3 - t2);

    //cout << *PrimeTable::instance() << '\n';
    for (uint32_t i = (kAMOUNT - 10 < kAMOUNT) ? kAMOUNT - 10 : 0; i < kAMOUNT; i++) {
        cout << pf_vec0[i] << pf_vec1[i];
    }

    cout << "8 jobs time: " << span0.count() << '\n';
    cout << "1 job time: " << span1.count() << '\n';

    return 0;
}


text:
package com.dremio.exec.planner.acceleration.substitution;

import com.dremio.common.config.SabotConfig;
import com.dremio.exec.planner.sql.OperatorTable;
import com.dremio.options.OptionResolver;

/**
 * A Factory interface to create {@code org.apache.calcite.plan.SubstitutionProvider} based on context
 *
 */
public interface SubstitutionProviderFactory {
  SubstitutionProvider getSubstitutionProvider(SabotConfig config,
      MaterializationProvider materializationProvider, OptionResolver options, OperatorTable operatorTable);
}


text:
{-
ghci c:\Users\Thomas\Documents\GitHub\practice\pe\nonvisualstudio\haskell\Spec\Problem0027.Spec.hs
 c:\Users\Thomas\Documents\GitHub\practice\pe\nonvisualstudio\haskell\Implementation\Problem0027.hs
 c:\Users\Thomas\Documents\GitHub\practice\utilities\nonvisualstudio\haskell\Implementation\Primes.hs
 c:\Users\Thomas\Documents\GitHub\practice\utilities\nonvisualstudio\haskell\Implementation\Math.hs
 c:\Users\Thomas\Documents\GitHub\practice\utilities\nonvisualstudio\haskell\Implementation\Seq.hs
-}
-- :r :q :set +s for times

module Problem0027Tests where

  import Test.HUnit
  import System.IO

  import Problem0027

  testCases = TestList
    [
      TestCase $ assertEqual "generatesAPrime (39, (1,41)) should return True." True (generatesAPrime (39, (1, 41))),
      TestCase $ assertEqual "generatesAPrime (0, (-76,1601)) should return True." True (generatesAPrime (0, ((-76), 1601))),
      TestCase $ assertEqual "generatesAPrime (80, (-76, 1601)) should return False." False (generatesAPrime (80, ((-76), 1601))),
      TestCase $ assertEqual "generatesAPrime (40, (1, 41))) should return False." False (generatesAPrime (40, (1, 41))),

      TestCase $ assertEqual "numberOfConsecutivePrimesProducedByQuadraticFormula (-79, 1601) should return (80, ((-79), 1601))." (80, ((-79), 1601)) (numberOfConsecutivePrimesProducedByQuadraticFormula ((-79), 1601)),
      TestCase $ assertEqual "numberOfConsecutivePrimesProducedByQuadraticFormula (1, 41) should return (40, (1, 41))." (40, (1, 41)) (numberOfConsecutivePrimesProducedByQuadraticFormula (1, 41)),
      TestCase $ assertEqual "numberOfConsecutivePrimesProducedByQuadraticFormula (-3, -3) should return (4, ((-3), (-3))." (4, ((-3), (-3))) (numberOfConsecutivePrimesProducedByQuadraticFormula ((-3), (-3))),
      TestCase $ assertEqual "numberOfConsecutivePrimesProducedByQuadraticFormula (1, 40) should return (0, (1, 40))." (0, (1, 40)) (numberOfConsecutivePrimesProducedByQuadraticFormula (1, 40)),

      TestCase $ assertEqual "generateListOfBs 15 should return [(-13), (-11), (-7), (-5), (-3), (-2), 2, 3, 5, 7, 11, 13]." [(-13), (-11), (-7), (-5), (-3), (-2), 2, 3, 5, 7, 11, 13] (generateListOfBs 15),
      TestCase $ assertEqual "generateListOfBs 5 should return [(-3), (-2), 2, 3]." [(-3), (-2), 2, 3] (generateListOfBs 5),

      TestCase $ assertEqual "maxConPrimesGeneratedGivenB -3 4 should return (4, ((-3), (-3)))." (4, ((-3), (-3))) (maxConPrimesGeneratedGivenB (-3) 4),
      TestCase $ assertEqual "maxConPrimesGeneratedGivenB -2 3 should return (3, ((-2), (-2)))." (3, ((-2), (-2))) (maxConPrimesGeneratedGivenB (-2) 3),

      TestCase $ assertEqual "quadraticFormulaThatProducesTheMostPrimes 6 should return (5, (5, 5))." (5, (5, 5)) (quadraticFormulaThatProducesTheMostPrimes 6),
      TestCase $ assertEqual "quadraticFormulaThatProducesTheMostPrimes 10 should return (8, ((-7), (-7)))." (8, ((-7), (-7))) (quadraticFormulaThatProducesTheMostPrimes 10),

      TestCase $ assertEqual "productOfQuadraticFormulaThatProducesTheMostPrimes 10 should return 49." 49 (productOfQuadraticFormulaThatProducesTheMostPrimes 10),
      TestCase $ assertEqual "productOfQuadraticFormulaThatProducesTheMostPrimes 6 should return 25." 25 (productOfQuadraticFormulaThatProducesTheMostPrimes 6),

      TestCase $ assertEqual "quadraticFormulaThatProducesTheMostPrimesConcurrent 6 should return (5, (5, 5))." (5, (5, 5)) (quadraticFormulaThatProducesTheMostPrimesConcurrent 6),
      TestCase $ assertEqual "quadraticFormulaThatProducesTheMostPrimesConcurrent 10 should return (8, ((-7), (-7)))." (8, ((-7), (-7))) (quadraticFormulaThatProducesTheMostPrimesConcurrent 10)
    ]

  tests = runTestTT testCases


text:
class CompilationException(Exception):
    """Signals an error during compilation"""
    def __init__(self, isBug, format, *message):
        # isBug: indicates that this is a compiler bug
        super(CompilationException, self).__init__()

        assert isinstance(format, str)
        assert isinstance(isBug, bool)
        self.message = message
        self.format = format
        self.isBug = isBug

    def show(self):
        # TODO: format this message nicely
        return self.format.format(*self.message)

class NotSupportedException(Exception):
    archError = " not supported by EBPF"

    def __init__(self, format, *message):
        super(NotSupportedException, self).__init__()

        assert isinstance(format, str)
        self.message = message
        self.format = format

    def show(self):
        # TODO: format this message nicely
        return (self.format + NotSupportedException.archError).format(
            *self.message)


text: Quantpedia - Trading WTI/BRENT Spread