text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Caching;

namespace Web.Common
{
    /// <summary>
    /// This library came from here: http://stackoverflow.com/questions/445050/how-can-i-cache-objects-in-asp-net-mvc
    /// </summary>
    public static class CacheExtensions
    {

        private static object sync = new object();
        public const int DefaultCacheExpiration = 20;

        /// <summary>
        /// Allows Caching of typed data
        /// </summary>
        /// <example><![CDATA[
        /// var user = HttpRuntime
        ///   .Cache
        ///   .GetOrStore<User>(
        ///      string.Format("User{0}", _userId),
        ///      () => Repository.GetUser(_userId));
        ///
        /// ]]></example>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache">calling object</param>
        /// <param name="key">Cache key</param>
        /// <param name="generator">Func that returns the object to store in cache</param>
        /// <returns></returns>
        /// <remarks>Uses a default cache expiration period as defined in <see cref="CacheExtensions.DefaultCacheExpiration"/></remarks>
        public static T GetOrStore<T>(this Cache cache, string key, Func<T> generator)
        {
            return cache.GetOrStore(key, (cache[key] == null && generator != null) ? generator() : default(T), DefaultCacheExpiration);
        }

        /// <summary>
        /// Allows Caching of typed data
        /// </summary>
        /// <example><![CDATA[
        /// var user = HttpRuntime
        ///   .Cache
        ///   .GetOrStore<User>(
        ///      string.Format("User{0}", _userId),
        ///      () => Repository.GetUser(_userId));
        ///
        /// ]]></example>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache">calling object</param>
        /// <param name="key">Cache key</param>
        /// <param name="generator">Func that returns the object to store in cache</param>
        /// <param name="expireInMinutes">Time to expire cache in minutes</param>
        /// <returns></returns>
        public static T GetOrStore<T>(this Cache cache, string key, Func<T> generator, double expireInMinutes)
        {
            return cache.GetOrStore(key, (cache[key] == null && generator != null) ? generator() : default(T), expireInMinutes);
        }

        /// <summary>
        /// Allows Caching of typed data
        /// </summary>
        /// <example><![CDATA[
        /// var user = HttpRuntime
        ///   .Cache
        ///   .GetOrStore<User>(
        ///      string.Format("User{0}", _userId),_userId));
        ///
        /// ]]></example>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache">calling object</param>
        /// <param name="key">Cache key</param>
        /// <param name="obj">Object to store in cache</param>
        /// <returns></returns>
        /// <remarks>Uses a default cache expiration period as defined in <see cref="CacheExtensions.DefaultCacheExpiration"/></remarks>
        public static T GetOrStore<T>(this Cache cache, string key, T obj)
        {
            return cache.GetOrStore(key, obj, DefaultCacheExpiration);
        }

        /// <summary>
        /// Allows Caching of typed data
        /// </summary>
        /// <example><![CDATA[
        /// var user = HttpRuntime
        ///   .Cache
        ///   .GetOrStore<User>(
        ///      string.Format("User{0}", _userId),
        ///      () => Repository.GetUser(_userId));
        ///
        /// ]]></example>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache">calling object</param>
        /// <param name="key">Cache key</param>
        /// <param name="obj">Object to store in cache</param>
        /// <param name="expireInMinutes">Time to expire cache in minutes</param>
        /// <returns></returns>
        public static T GetOrStore<T>(this Cache cache, string key, T obj, double expireInMinutes)
        {
            var result = cache[key];

            if (result == null)
            {

                lock (sync)
                {
                    if (result == null)
                    {
                        result = obj != null ? obj : default(T);
                        cache.Insert(key, result, null, DateTime.Now.AddMinutes(expireInMinutes), Cache.NoSlidingExpiration);
                    }
                }
            }

            return (T)result;

        }

    }
}


text:
package com.vesperin.cue.cmds;

import com.github.rvesse.airline.HelpOption;
import com.github.rvesse.airline.annotations.Command;
import com.github.rvesse.airline.annotations.Option;
import com.google.common.base.Strings;
import com.vesperin.base.Source;
import com.vesperin.cue.Cue;
import com.vesperin.cue.Introspector;
import com.vesperin.cue.IntrospectorWithCli;
import com.vesperin.cue.utils.IO;
import com.vesperin.cue.utils.Sources;

import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.vesperin.cue.IntrospectorWithCli.allNonNull;
import static com.vesperin.cue.IntrospectorWithCli.allNull;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;

/**
 * @author Huascar Sanchez
 */
@Command(name = "typical", description = "Finds the top k most typical implementation")
public class TypicalityAnalysisCommand implements IntrospectorWithCli.CliCommand {

  private static final String TYPICAL_SET_FILE_NAME = "typicalset.txt";

  @Inject HelpOption<TypicalityAnalysisCommand> help;

  @Option(name = { "-t", "--targets" }, arity = 100, description = "the names of multiple files to analyze (100 max).")
  private List<String> targets = null;

  @Option(name = {"-f", "--from"}, arity = 1, description = "analyze only the method entries in target file.")
  private String from = null;

  @Option(name = {"-d", "--directory"}, arity = 1, description = "directory containing files to analyze.")
  private String directory = null;

  @Option(name = {"-k", "--topK"}, description = "k most typical source code.")
  private int topK = 1;

  @SuppressWarnings("FieldCanBeLocal")
  @Option(name = {"-b", "--bandwidth"}, description = "bandwidth parameter.")
  private double bandwidth = 0.3;

  @SuppressWarnings("FieldCanBeLocal")
  @Option(name = {"-e", "--echo"}, description = "print results on screen.")
  private boolean onScreen = false;

  @Override public Integer call() throws Exception {
    if(!help.showHelpIfRequested()){
      if(allNull(3, directory, from, targets)) {
        System.err.println("Please use a valid option (see -help for information).");
        return -1;
      }

      if(topK < 1) {
        System.err.println("Please use a valid topK value (see -help for information).");
        return -1;
      }

      if(allNonNull(3, directory, from, targets)) {
        System.err.println("Please use only one option at a time (not all).");
        return -1;
      }

      final List<Source> corpus = new ArrayList<>();
      if(targets != null){

        final Set<String> relevant = Sources.populate(corpus, targets);
        performTypicalityQuery(corpus, relevant);

      } else {
        if(from != null){
          catchAndQuery(corpus);
        } else {
          if(directory == null) {
            System.err.println("missing -d or --directory option");
            return -1;
          } else {
            catchDirAndQuery(corpus, directory);
          }
        }
      }
    }

    return 0;
  }

  private void catchDirAndQuery(List<Source> corpus, String target) {
    final Path start = Paths.get(target);
    final List<File> allFiles = IO.collectFiles(start, "java", "test", "Test");
    for(File each : allFiles){
      final Source src = Sources.from(each);
      corpus.add(src);
    }

    performTypicalityQuery(corpus, new HashSet<>());
  }

  private void catchAndQuery(List<Source> corpus) {
    final Path start = Paths.get(from);
    final List<String> allLines = IO.readLines(start);

    final Set<String> relevant = Sources.populate(corpus, allLines);
    performTypicalityQuery(corpus, relevant);
  }

  private void performTypicalityQuery(List<Source> corpus, Set<String> relevant) {

    final Introspector cue = Cue.newIntrospector();
    final Set<Source> corpusSet = corpus.stream().collect(Collectors.toSet());
    final List<Source> result = cue.typicalityQuery(topK, bandwidth, corpusSet, relevant);
    if(result.isEmpty()){
      System.out.println("No typical source code was found.");
    } else {

      try {
        final Path newFile = Paths.get(TYPICAL_SET_FILE_NAME);
        Files.deleteIfExists(newFile);

        for(Source each : result){

          final String snippet = Introspector.methodCode(each, relevant);
          if(!Strings.isNullOrEmpty(snippet)){

            if(!onScreen) {
              final List<String> lines = new ArrayList<>();
              lines.add(each.getName() + ":");
              lines.addAll(Sources.contentToLines(snippet));

              Files.write(
                newFile,
                lines,
                CREATE, APPEND
              );
            } else {
              Files.deleteIfExists(newFile);
              System.out.println(each.getName());
              System.out.println(snippet);
              System.out.println();
            }

          }

        }

        if(!onScreen){
          System.out.printf("%-32s\n", newFile.toFile().getAbsolutePath());
        }

      } catch (IOException e){
        throw new RuntimeException(e);
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Stratis.Bitcoin.Features.RPC.Tests.Models
{
    public class BaseRPCModelTest
    {
        protected static JObject ModelToJObject(object model)
        {
            string json = ModelToJson(model);
            JObject obj = JObject.Parse(json);
            return obj;
        }

        protected static string ModelToJson(object model)
        {
            var formatter = new RPCJsonOutputFormatter(new JsonSerializerSettings(), System.Buffers.ArrayPool<char>.Create());
            var sw = new StringWriter();
            formatter.WriteObject(sw, model);
            string json = sw.ToString();
            return json;
        }
    }
}


text:
using Mosa.Compiler.Framework;

namespace Mosa.Platform.ARMv6.Instructions
{
	/// <summary>
	/// Isb instruction: Instruction Synchronization Barrier
	/// </summary>
	public class Isb : ARMv6Instruction
	{
		#region Construction

		/// <summary>
		/// Initializes a new instance of <see cref="Isb"/>.
		/// </summary>
		public Isb() :
			base(1, 3)
		{
		}

		#endregion Construction

		#region Methods

		/// <summary>
		/// Emits the specified platform instruction.
		/// </summary>
		/// <param name="node">The node.</param>
		/// <param name="emitter">The emitter.</param>
		protected override void Emit(InstructionNode node, MachineCodeEmitter emitter)
		{
			// TODO
		}

		#endregion Methods
	}
}


text:
import { ChangeEvent, useState } from 'react';

export function useTextInputState(
  init: string,
): [string, (e: ChangeEvent<HTMLInputElement>) => void] {
  const [value, setValue] = useState(init);

  return [
    value,
    (e: ChangeEvent<HTMLInputElement>) => {
      setValue(e.currentTarget.value);
    },
  ];
}


text:
[![Stories in Ready](https://badge.waffle.io/damondouglas/uom.dart.png?label=ready&title=Ready)](https://waffle.io/damondouglas/uom.dart)
[![Build Status](https://drone.io/github.com/damondouglas/uom.dart/status.png)](https://drone.io/github.com/damondouglas/uom.dart/latest)
uom.dart
========

A Dart Library for Handling Unit of Measures in Medical Applications.

## Usage
```dart
import 'package:uom/uom.dart';
```

## Weight

```dart
kg patientWeightInKg = new kg(80); 						// 80 kg

lbs patientWeightInLbs = new lbs(176.37); 				// 176.37 lbs

kg newWeight = patientWeightInKg + new kg(1);			// 81 kg

lbs convertWeight = patientWeightInKg.convertTo(lbs);   // 176.37 lbs
```

## Height

```dart
cm patientHeightInCm = new cm(165.1);					// 165.1 cm

```

## Ratios

```dart
mgPerkg medicationDose = new mgPerkg(1);				// 1 mg/kg

kg patientWeight = new kg(80);							// 80 kg

mg doseValue = medicationDose * patientWeight;			// 80 mg

mgPermL concentration = new mgPermL(10);				// 10 mg / mL

mL doseVolume = doseValue / concentration;				// 8 mL
```


text:
module Tableficate
  class Base
    extend Tableficate::Finder

    def self.scope(model = nil)
      if block_given?
        @scope = yield
      else
        @scope = model.to_s.camelize.constantize
      end
    end

    def self.default_sort(name, dir = 'asc')
      @default_sort = [name, dir]
    end

    def self.column(name, options = {})
      @sort ||= {}

      @sort[name] = options[:sort] if options[:sort].present?
    end

    def self.filter(name, options = {}, &block)
      @filter ||= {}

      if block_given?
        @filter[name] = block
      else
        options.reverse_merge!(
          field: name
        )

        @filter[name] = options
      end
    end
  end
end


text:
"""
Test the interaction between trial and errors logged during test run.
"""

import time

from twisted.internet import defer
from twisted.python import failure, log
from twisted.trial import unittest, reporter, runner

def makeFailure():
    """
    Return a new, realistic failure.
    """
    try:
        1/0
    except ZeroDivisionError:
        f = failure.Failure()
    return f

def deferLater(n):
    """
    Return a L{defer.Deferred} that will fire in C{n} seconds.
    """
    from twisted.internet import reactor
    d = defer.Deferred()
    reactor.callLater(n, d.callback, None)
    return d

class Mask(object):
    """
    Hide C{MockTest}s from Trial's automatic test finder.
    """

    class MockTest(unittest.TestCase):
        def test_silent(self):
            """
            Don't log any errors.
            """

        def test_single(self):
            """
            Log a single error.
            """
            log.err(makeFailure())

        def test_double(self):
            """
            Log two errors.
            """
            log.err(makeFailure())
            log.err(makeFailure())

        def test_inCallback(self):
            """
            Log an error in an asynchronous callback.
            """
            d = deferLater(0)
            d.addCallback(lambda _: log.err(makeFailure()))
            return d

class TestObserver(unittest.TestCase):
    def setUp(self):
        self.result = reporter.TestResult()
        self.observer = unittest._LogObserver()

    def test_msg(self):
        """
        Test that a standard log message doesn't go anywhere near the result.
        """
        self.observer.gotEvent({'message': ('some message',),
                                'time': time.time(), 'isError': 0,
                                'system': '-'})
        self.assertEqual(self.observer.getErrors(), [])

    def test_error(self):
        """
        Test that an observed error gets added to the result
        """
        f = makeFailure()
        self.observer.gotEvent({'message': (),
                                'time': time.time(), 'isError': 1,
                                'system': '-', 'failure': f,
                                'why': None})
        self.assertEqual(self.observer.getErrors(), [f])

    def test_flush(self):
        """
        Check that flushing the observer with no args removes all errors.
        """
        self.test_error()
        flushed = self.observer.flushErrors()
        self.assertEqual(self.observer.getErrors(), [])
        self.assertEqual(len(flushed), 1)
        self.assertTrue(flushed[0].check(ZeroDivisionError))

    def _makeRuntimeFailure(self):
        return failure.Failure(RuntimeError('test error'))

    def test_flushByType(self):
        """
        Check that flushing the observer remove all failures of the given type.
        """
        self.test_error() # log a ZeroDivisionError to the observer
        f = self._makeRuntimeFailure()
        self.observer.gotEvent(dict(message=(), time=time.time(), isError=1,
                                    system='-', failure=f, why=None))
        flushed = self.observer.flushErrors(ZeroDivisionError)
        self.assertEqual(self.observer.getErrors(), [f])
        self.assertEqual(len(flushed), 1)
        self.assertTrue(flushed[0].check(ZeroDivisionError))

    def test_ignoreErrors(self):
        """
        Check that C{_ignoreErrors} actually causes errors to be ignored.
        """
        self.observer._ignoreErrors(ZeroDivisionError)
        f = makeFailure()
        self.observer.gotEvent({'message': (),
                                'time': time.time(), 'isError': 1,
                                'system': '-', 'failure': f,
                                'why': None})
        self.assertEqual(self.observer.getErrors(), [])

    def test_clearIgnores(self):
        """
        Check that C{_clearIgnores} ensures that previously ignored errors
        get captured.
        """
        self.observer._ignoreErrors(ZeroDivisionError)
        self.observer._clearIgnores()
        f = makeFailure()
        self.observer.gotEvent({'message': (),
                                'time': time.time(), 'isError': 1,
                                'system': '-', 'failure': f,
                                'why': None})
        self.assertEqual(self.observer.getErrors(), [f])

class LogErrors(unittest.TestCase):
    """
    High-level tests demonstrating the expected behaviour of logged errors
    during tests.
    """

    def setUp(self):
        self.result = reporter.TestResult()

    def tearDown(self):
        self.flushLoggedErrors(ZeroDivisionError)

    def test_singleError(self):
        """
        Test that a logged error gets reported as a test error.
        """
        test = Mask.MockTest('test_single')
        test(self.result)
        self.assertEqual(len(self.result.errors), 1)
        self.assertTrue(self.result.errors[0][1].check(ZeroDivisionError),
                        self.result.errors[0][1])

    def test_twoErrors(self):
        """
        Test that when two errors get logged, they both get reported as test
        errors.
        """
        test = Mask.MockTest('test_double')
        test(self.result)
        self.assertEqual(len(self.result.errors), 2)

    def test_inCallback(self):
        """
        Test that errors logged in callbacks get reported as test errors.
        """
        test = Mask.MockTest('test_inCallback')
        test(self.result)
        self.assertEqual(len(self.result.errors), 1)
        self.assertTrue(self.result.errors[0][1].check(ZeroDivisionError),
                        self.result.errors[0][1])

    def test_errorsIsolated(self):
        """
        Check that an error logged in one test doesn't fail the next test.
        """
        t1 = Mask.MockTest('test_single')
        t2 = Mask.MockTest('test_silent')
        t1(self.result)
        t2(self.result)
        self.assertEqual(len(self.result.errors), 1)
        self.assertEqual(self.result.errors[0][0], t1)


text:
<?php

namespace MoreSparetime\WordPress\PluginBuilder\Admin\Settings\Fields;

use AndreasGlaser\Helpers\Html\FormHelper;
use MoreSparetime\WordPress\PluginBuilder\Admin\Settings\Field;

/**
 * Class TextField
 *
 * @package MoreSparetime\WordPress\PluginBuilder\Admin\Settings\Fields
 * @author  Andreas Glaser
 */
class TextField extends Field
{
    /**
     * @author Andreas Glaser
     */
    public function render()
    {
        if (!$this->renderer) {
            print FormHelper::text($this->getOptionName(), get_option($this->getOptionName()), ['id' => $this->getOptionName()]);
        } else {
            print $this->renderer->render($this);
        }
    }

    /**
     * @param $input
     *
     * @return string
     * @author Andreas Glaser
     */
    public function sanitize($input)
    {
        return sanitize_text_field($input);
    }
}


text:
package org.apache.beam.sdk.extensions.euphoria.core.translate;

import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;

import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import org.apache.beam.sdk.extensions.euphoria.core.client.accumulators.AccumulatorProvider;
import org.apache.beam.sdk.extensions.euphoria.core.client.functional.ReduceFunctor;
import org.apache.beam.sdk.extensions.euphoria.core.client.functional.UnaryFunction;
import org.apache.beam.sdk.extensions.euphoria.core.client.operator.ReduceByKey;
import org.apache.beam.sdk.extensions.euphoria.core.client.type.TypeAwareness;
import org.apache.beam.sdk.extensions.euphoria.core.translate.collector.AdaptableCollector;
import org.apache.beam.sdk.extensions.euphoria.core.translate.collector.SingleValueCollector;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.GroupByKey;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.apache.beam.sdk.transforms.SimpleFunction;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionList;
import org.apache.beam.sdk.values.TypeDescriptors;

/** Translator for {@code ReduceByKey} operator. */
public class ReduceByKeyTranslator<InputT, KeyT, ValueT, OutputT>
    implements OperatorTranslator<
        InputT, KV<KeyT, OutputT>, ReduceByKey<InputT, KeyT, ValueT, OutputT>> {

  @Override
  public PCollection<KV<KeyT, OutputT>> translate(
      ReduceByKey<InputT, KeyT, ValueT, OutputT> operator, PCollectionList<InputT> inputs) {

    // todo Could we even do values sorting in Beam ? And do we want it?
    checkState(!operator.getValueComparator().isPresent(), "Values sorting is not supported.");

    final UnaryFunction<InputT, KeyT> keyExtractor = operator.getKeyExtractor();
    final UnaryFunction<InputT, ValueT> valueExtractor = operator.getValueExtractor();
    final ReduceFunctor<ValueT, OutputT> reducer = operator.getReducer();

    final PCollection<InputT> input =
        operator
            .getWindow()
            .map(window -> OperatorTranslators.getSingleInput(inputs).apply(window))
            .orElseGet(() -> OperatorTranslators.getSingleInput(inputs));

    // ~ create key & value extractor
    final MapElements<InputT, KV<KeyT, ValueT>> extractor =
        MapElements.via(new KeyValueExtractor<>(keyExtractor, valueExtractor));

    final PCollection<KV<KeyT, ValueT>> extracted =
        input
            .apply("extract-keys", extractor)
            .setTypeDescriptor(
                TypeDescriptors.kvs(
                    TypeAwareness.orObjects(operator.getKeyType()),
                    TypeAwareness.orObjects(operator.getValueType())));

    final AccumulatorProvider accumulators =
        new LazyAccumulatorProvider(AccumulatorProvider.of(inputs.getPipeline()));

    if (operator.isCombinable()) {
      // if operator is combinable we can process it in more efficient way
      final PCollection<KV<KeyT, ValueT>> combined =
          extracted.apply(
              "combine",
              Combine.perKey(asCombiner(reducer, accumulators, operator.getName().orElse(null))));
      @SuppressWarnings("unchecked")
      final PCollection<KV<KeyT, OutputT>> casted = (PCollection) combined;
      return casted.setTypeDescriptor(
          operator
              .getOutputType()
              .orElseThrow(
                  () -> new IllegalStateException("Unable to infer output type descriptor.")));
    }

    return extracted
        .apply("group", GroupByKey.create())
        .setTypeDescriptor(
            TypeDescriptors.kvs(
                TypeAwareness.orObjects(operator.getKeyType()),
                TypeDescriptors.iterables(TypeAwareness.orObjects(operator.getValueType()))))
        .apply(
            "reduce",
            ParDo.of(new ReduceDoFn<>(reducer, accumulators, operator.getName().orElse(null))))
        .setTypeDescriptor(
            operator
                .getOutputType()
                .orElseThrow(
                    () -> new IllegalStateException("Unable to infer output type descriptor.")));
  }

  @Override
  public boolean canTranslate(ReduceByKey operator) {
    // translation of sorted values is not supported yet
    return !operator.getValueComparator().isPresent();
  }

  private static <InputT, OutputT> SerializableFunction<Iterable<InputT>, InputT> asCombiner(
      ReduceFunctor<InputT, OutputT> reducer,
      AccumulatorProvider accumulatorProvider,
      @Nullable String operatorName) {

    @SuppressWarnings("unchecked")
    final ReduceFunctor<InputT, InputT> combiner = (ReduceFunctor<InputT, InputT>) reducer;

    return (Iterable<InputT> input) -> {
      SingleValueCollector<InputT> collector =
          new SingleValueCollector<>(accumulatorProvider, operatorName);
      combiner.apply(StreamSupport.stream(input.spliterator(), false), collector);
      return collector.get();
    };
  }

  /**
   * Extract key and values from input data set.
   *
   * @param <InputT> type of input
   * @param <KeyT> type of key
   * @param <ValueT> type of value
   */
  private static class KeyValueExtractor<InputT, KeyT, ValueT>
      extends SimpleFunction<InputT, KV<KeyT, ValueT>> {

    private final UnaryFunction<InputT, KeyT> keyExtractor;
    private final UnaryFunction<InputT, ValueT> valueExtractor;

    KeyValueExtractor(
        UnaryFunction<InputT, KeyT> keyExtractor, UnaryFunction<InputT, ValueT> valueExtractor) {
      this.keyExtractor = keyExtractor;
      this.valueExtractor = valueExtractor;
    }

    @Override
    public KV<KeyT, ValueT> apply(InputT in) {
      return KV.of(keyExtractor.apply(in), valueExtractor.apply(in));
    }
  }

  /**
   * Perform reduction of given elements.
   *
   * @param <KeyT> type of key
   * @param <ValueT> type of value
   * @param <OutputT> type of output
   */
  private static class ReduceDoFn<KeyT, ValueT, OutputT>
      extends DoFn<KV<KeyT, Iterable<ValueT>>, KV<KeyT, OutputT>> {

    private final ReduceFunctor<ValueT, OutputT> reducer;
    private final AdaptableCollector<KV<KeyT, Iterable<ValueT>>, KV<KeyT, OutputT>, OutputT>
        collector;

    ReduceDoFn(
        ReduceFunctor<ValueT, OutputT> reducer,
        AccumulatorProvider accumulators,
        @Nullable String operatorName) {
      this.reducer = reducer;
      this.collector =
          new AdaptableCollector<>(
              accumulators,
              operatorName,
              (DoFn<KV<KeyT, Iterable<ValueT>>, KV<KeyT, OutputT>>.ProcessContext ctx,
                  OutputT out) -> ctx.output(KV.of(ctx.element().getKey(), out)));
    }

    @ProcessElement
    @SuppressWarnings("unused")
    public void processElement(ProcessContext ctx) {
      collector.setProcessContext(ctx);
      reducer.apply(
          StreamSupport.stream(requireNonNull(ctx.element().getValue()).spliterator(), false),
          collector);
    }
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">

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

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Lista X

Navegar além

bla bla bla


text:
package monix.reactive.internal.operators

import monix.reactive.Observable
import scala.concurrent.duration._

object BufferSlidingOverlapSuite extends BaseOperatorSuite {
  val waitNext = Duration.Zero
  val waitFirst = Duration.Zero

  def createObservable(sourceCount: Int) = {
    require(sourceCount > 0, "count must be strictly positive")
    if (sourceCount > 1) Some {
      val divBy4 = sourceCount / 4 * 4
      val o = Observable
        .range(0L, divBy4.toLong)
        .map(_ % 4)
        .bufferSliding(8, 4)
        .flatMap(x => Observable.fromIterable(x))

      val count = 8 + (divBy4 - 8) * 2
      val sum = (count / 4) * 6
      Sample(o, count, sum.toLong, waitFirst, waitNext)
    }
    else
      Some {
        val o = Observable
          .now(1L)
          .bufferSliding(2, 1)
          .flatMap(x => Observable.fromIterable(x))
        Sample(o, 1, 1, waitFirst, waitNext)
      }
  }

  def brokenUserCodeObservable(sourceCount: Int, ex: Throwable) = None
  def observableInError(sourceCount: Int, ex: Throwable) = None

  override def cancelableObservables() = {
    val o = Observable
      .range(0, 1000)
      .delayOnNext(1.second)
      .bufferSliding(2, 1)
      .flatMap(x => Observable.fromIterable(x))
    Seq(Sample(o, 0, 0, 0.seconds, 0.seconds))
  }
}


text:
package org.springframework.cloud.cluster.lock;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Generic configuration properties for distributed locking.
 *
 * @author Janne Valkealahti
 *
 */
@ConfigurationProperties(value = "spring.cloud.cluster.lock")
public class DistributedLockProperties {

	/** if distributed locking is enabled globally. */
	private boolean enabled = true;

	/** distributed locking role. */
	private String role;

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

}


text:
layout: default
title: About Manoj M J
---
## About

Rails lover. Game Of Thrones fan. Will code for chocolate.

Tea > Coffee.

I write extensively on [Quora](https://quora.com/Manoj-Memana-Jayakumar-1/).

You can also follow me on [twitter](https://twitter.com/manoj_g33k)


text:
[Zillow Prize: Zillow's Home Value Prediction (Zestimate)](https://www.kaggle.com/c/zillow-prize-1)

[GPS converter](https://www.gps-coordinates.net/gps-coordinates-converter)

[zillow](https://www.zillow.com/)


text:
<?php

namespace backend\models;

use Yii;
use common\helpers\Mailer;

/**
 * This is the model class for table "review".
 *
 * @property integer $id
 * @property string $first_name
 * @property string $last_name
 * @property string $body
 * @property string $status
 */
class Review extends \yii\db\ActiveRecord
{
    use Mailer;

    const STATUS_NEW = 'новый';
    const STATUS_DONE = 'готово';
    const STATUS_FAIL = 'отклонен';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'review';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['first_name', 'last_name', 'body'], 'required'],
            [['body'], 'string'],
            [['first_name', 'last_name', 'status'], 'string', 'max' => 128],
            ['status', 'in', 'range' => [self::STATUS_NEW, self::STATUS_DONE, self::STATUS_FAIL]],
            ['status', 'default', 'value' => self::STATUS_NEW],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'first_name' => 'Имя',
            'last_name' => 'Фамилия',
            'body' => 'Отзыв',
            'status' => 'Статус',
        ];
    }

    public static function getReviewStatesGoodly($model)
    {
        $result;
        switch ($model->status) {
            case self::STATUS_NEW:
                $result = 'новый';
                break;
            case self::STATUS_DONE:
                $result = 'готово';
                break;
            case self::STATUS_FAIL:
                $result = 'отклонен';
                break;
        }
        return $result;
    }

    public static function getStatuses()
    {
        return [
            self::STATUS_NEW => self::STATUS_NEW,
            self::STATUS_DONE => self::STATUS_DONE,
            self::STATUS_FAIL => self::STATUS_FAIL,

        ];
    }
}


text:
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import logging
import xml.etree.ElementTree as ET
from datetime import datetime

from indra.statements import *
from indra.util import UnicodeXMLTreeBuilder as UTB

logger = logging.getLogger(__name__)

class CWMSError(Exception):
    pass

POLARITY_DICT = {'CC': {'ONT::CAUSE': 1,
                        'ONT::INFLUENCE': 1},
                 'EVENT': {'ONT::INCREASE': 1,
                           'ONT::MODULATE': None,
                           'ONT::DECREASE': -1,
                           'ONT::INHIBIT': -1,
                           'ONT::TRANSFORM': None,
                           'ONT::STIMULATE': 1},
                 'EPI': {'ONT::ASSOCIATE': None}}

class CWMSProcessor(object):
    """The CWMSProcessor currently extracts causal relationships between
    terms (nouns) in EKB. In the future, this processor can be extended to
    extract other types of relations, or to extract relations involving
    events.

    For more details on the TRIPS EKB XML format, see
    http://trips.ihmc.us/parser/cgi/drum

    Parameters
    ----------
    xml_string : str
        A TRIPS extraction knowledge base (EKB) in XML format as a string.

    Attributes
    ----------
    tree : xml.etree.ElementTree.Element
        An ElementTree object representation of the TRIPS EKB XML.
    doc_id: str
        Document ID
    statements : list[indra.statements.Statement]
        A list of INDRA Statements that were extracted from the EKB.
    sentences : dict[str: str]
        The list of all sentences in the EKB with their IDs
    paragraphs : dict[str: str]
        The list of all paragraphs in the EKB with their IDs
    par_to_sec : dict[str: str]
        A map from paragraph IDs to their associated section types
    """

    def __init__(self, xml_string):
        self.statements = []
        # Parse XML
        try:
            self.tree = ET.XML(xml_string, parser=UTB())
        except ET.ParseError:
            logger.error('Could not parse XML string')
            self.tree = None
            return

        # Get the document ID from the EKB tag.
        self.doc_id = self.tree.attrib.get('id')

        # Store all paragraphs and store all sentences in a data structure
        paragraph_tags = self.tree.findall('input/paragraphs/paragraph')
        sentence_tags = self.tree.findall('input/sentences/sentence')
        self.paragraphs = {p.attrib['id']: p.text for p in paragraph_tags}
        self.sentences = {s.attrib['id']: s.text for s in sentence_tags}
        self.par_to_sec = {p.attrib['id']: p.attrib.get('sec-type')
                           for p in paragraph_tags}

        # Keep a list of events that are part of relations and events
        # subsumed by other events
        self.relation_events = []
        self.subsumed_events = []

        # Keep a list of unhandled events for development purposes
        self._unhandled_events = []

        self._preprocess_events()

    def _preprocess_events(self):
        events = self.tree.findall("EVENT/[type]")
        for event in events:
            affected = event.find("*[@role=':AFFECTED']")
            if affected is not None:
                affected_id = affected.attrib.get('id')
                if affected_id:
                    self.subsumed_events.append(affected_id)

    def extract_causal_relations(self):
        """Extract Influence Statements from the EKB."""
        relations = self.tree.findall("CC/[type]")
        for relation in relations:
            st = self.influence_from_relation(relation)
            if st:
                self.statements.append(st)

        events = self.tree.findall("EVENT/[type]")
        for event in events:
            st = self.influence_from_event(event)
            if st:
                self.statements.append(st)
        # In some EKBs we get two redundant relations over the same arguments,
        # we eliminate these
        self._remove_multi_extraction_artifacts()

        # Print unhandled event types
        logger.debug('Unhandled event types: %s' %
                     (', '.join(sorted(list(set(self._unhandled_events))))))

    def extract_events(self):
        """Extract standalone Events from the EKB."""
        events = [(1, self.tree.findall("EVENT/[type='ONT::INCREASE']")),
                  (-1, self.tree.findall("EVENT/[type='ONT::DECREASE']"))]
        for polarity, event_list in events:
            for event_term in event_list:
                event_id = event_term.attrib.get('id')
                if event_id in self.subsumed_events or \
                        event_id in self.relation_events:
                    continue
                event = self.event_from_event(event_term)
                if event:
                    # Here we set the polarity based on the polarity implied by
                    # the increase/decrease here
                    event.delta['polarity'] = polarity
                    self.statements.append(event)

        self._remove_multi_extraction_artifacts()

    def extract_correlations(self):
        correlations = self.tree.findall("EPI/[type='ONT::ASSOCIATE']")
        for cor in correlations:
            st = self._association_from_element(cor, 'EPI', 'NEUTRAL1',
                                               'NEUTRAL2', False)
            if st:
                self.statements.append(st)

        # self._remove_multi_extraction_artifacts()

    def _influence_from_element(self, element, element_type, subj_arg,
                                obj_arg, is_arg):
        components = self._statement_components_from_element(
            element, element_type, subj_arg, obj_arg, is_arg)
        if components is None:
            return None
        subj, obj, evidence, rel_type = components
        # If the object polarity is not given explicitly, we set it
        # based on the one implied by the relation
        if obj.delta['polarity'] is None:
            obj.delta['polarity'] = POLARITY_DICT[element_type][rel_type]

        st = Influence(subj, obj, evidence=[evidence])
        return st

    def influence_from_relation(self, relation):
        """Return an Influence from a CC element in the EKB."""
        return self._influence_from_element(relation, 'CC', 'FACTOR',
                                            'OUTCOME', True)

    def influence_from_event(self, event):
        """Return an Influence from an EVENT element in the EKB."""
        return self._influence_from_element(event, 'EVENT', 'AGENT',
                                            'AFFECTED', False)

    def _statement_components_from_element(self, element, element_type,
                                           member1_arg, member2_arg, is_arg):
        element_id = element.attrib.get('id')
        rel_type = element.find('type').text
        if rel_type not in POLARITY_DICT[element_type]:
            self._unhandled_events.append(rel_type)
            return None
        member1_id, member1_term = self._get_term_by_role(
            element, member1_arg, is_arg)
        member2_id, member2_term = self._get_term_by_role(
            element, member2_arg, is_arg)
        if member1_term is None or member2_term is None:
            return None

        member1 = self._get_event(member1_term)
        member2 = self._get_event(member2_term)
        if member1 is None or member2 is None:
            return None

        self.relation_events += [member1_id, member2_id, element_id]

        evidence = self._get_evidence(element)

        return member1, member2, evidence, rel_type

    def _association_from_element(self, element, element_type, member1_arg,
                                  member2_arg, is_arg):
        components = self._statement_components_from_element(
            element, element_type, member1_arg, member2_arg, is_arg)
        if components is None:
            return None
        member1, member2, evidence, _ = components
        st = Association([member1, member2], evidence=[evidence])
        return st

    def event_from_event(self, event_term):
        """Return an Event from an EVENT element in the EKB."""
        arg_id, arg_term = self._get_term_by_role(event_term, 'AFFECTED',
                                                  False)
        if arg_term is None:
            return None

        # Make an Event statement if it is a standalone event
        evidence = self._get_evidence(event_term)
        event = self._get_event(arg_term, evidence=[evidence])
        if event is None:
            return None
        event.context = self.get_context(event_term)
        return event

    def _get_term_by_role(self, term, role, is_arg):
        """Return the ID and the element corresponding to a role in a term."""
        element = term.find("%s[@role=':%s']" % ('arg/' if is_arg else '*',
                                                 role))
        if element is None:
            return None, None
        element_id = element.attrib.get('id')
        if element_id is None:
            return None, None
        element_term = self.tree.find("*[@id='%s']" % element_id)
        if element_term is None:
            return None, None
        return element_id, element_term

    def _get_event(self, event_term, evidence=None):
        """Extract and Event from the given EKB element."""
        # Now see if there is a modifier like assoc-with connected
        # to the main concept
        assoc_with = self._get_assoc_with(event_term)

        # Get the element's text and use it to construct a Concept
        element_text_element = event_term.find('text')
        if element_text_element is None:
            return None
        element_text = element_text_element.text
        element_db_refs = {'TEXT': element_text}
        element_name = sanitize_name(element_text)

        element_type_element = event_term.find('type')
        if element_type_element is not None:
            element_db_refs['CWMS'] = element_type_element.text
            # If there's an assoc-with, we tack it on as extra grounding
            if assoc_with is not None:
                element_db_refs['CWMS'] += ('|%s' % assoc_with)

        concept = Concept(element_name, db_refs=element_db_refs)

        ev_type = event_term.find('type').text
        polarity = POLARITY_DICT['EVENT'].get(ev_type)
        delta = {'polarity': polarity, 'adjectives': []}
        context = self.get_context(event_term)
        event_obj = Event(concept, delta=delta, context=context,
                          evidence=evidence)
        return event_obj

    def get_context(self, element):
        time = self._extract_time(element)
        geoloc = self._extract_geoloc(element)

        if time or geoloc:
            context = WorldContext(time=time, geo_location=geoloc)
        else:
            context = None
        return context

    def _extract_time(self, term):
        time = term.find('time')
        if time is None:
            time = term.find('features/time')
            if time is None:
                return None
        time_id = time.attrib.get('id')
        time_term = self.tree.find("*[@id='%s']" % time_id)
        if time_term is None:
            return None
        text = sanitize_name(time_term.findtext('text'))
        timex = time_term.find('timex')
        if timex is not None:
            year = timex.findtext('year')
            try:
                year = int(year)
            except Exception:
                year = None
            month = timex.findtext('month')
            day = timex.findtext('day')
            if year and (month or day):
                try:
                    month = int(month)
                except Exception:
                    month = 1
                try:
                    day = int(day)
                except Exception:
                    day = 1
                start = datetime(year, month, day)
                time_context = TimeContext(text=text, start=start)
            else:
                time_context = TimeContext(text=text)
        else:
            time_context = TimeContext(text=text)
        return time_context

    def _extract_geoloc(self, term):
        """Get the location from a term (CC or TERM)"""
        loc = term.find('location')
        if loc is None:
            return None
        loc_id = loc.attrib.get('id')
        loc_term = self.tree.find("*[@id='%s']" % loc_id)
        if loc_term is None:
            return None
        text = loc_term.findtext('text')
        # name = loc_term.findtext('name')
        geoloc_context = RefContext(name=text)
        return geoloc_context

    def _get_assoc_with(self, element_term):
        # NOTE: there could be multiple assoc-withs here that we may
        # want to handle
        assoc_with = element_term.find('assoc-with')
        if assoc_with is not None:
            # We first identify the ID of the assoc-with argument
            assoc_with_id = assoc_with.attrib.get('id')
            # In some cases the assoc-with has no ID but has a type
            # defined in place that we can get
            if assoc_with_id is None:
                assoc_with_grounding = assoc_with.find('type').text
                return assoc_with_grounding
            # If the assoc-with has an ID then find the TERM
            # corresponding to it
            assoc_with_term = self.tree.find("*[@id='%s']" % assoc_with_id)
            if assoc_with_term is not None:
                # We then get the grounding for the term
                assoc_with_grounding = assoc_with_term.find('type').text
                return assoc_with_grounding
        return None

    def _get_evidence(self, event_tag):
        text = self._get_evidence_text(event_tag)
        sec = self._get_section(event_tag)
        epi = {'direct': False}
        if sec:
            epi['section_type'] = sec
        ev = Evidence(source_api='cwms', text=text, pmid=self.doc_id,
                      epistemics=epi)
        return ev

    def _get_evidence_text(self, event_tag):
        """Extract the evidence for an event.

        Pieces of text linked to an EVENT are fragments of a sentence. The
        EVENT refers to the paragraph ID and the "uttnum", which corresponds
        to a sentence ID. Here we find and return the full sentence from which
        the event was taken.
        """
        par_id = event_tag.attrib.get('paragraph')
        uttnum = event_tag.attrib.get('uttnum')
        event_text = event_tag.find('text')
        if self.sentences is not None and uttnum is not None:
            sentence = self.sentences[uttnum]
        elif event_text is not None:
            sentence = event_text.text
        else:
            sentence = None
        return sentence

    def _get_section(self, event_tag):
        par_id = event_tag.attrib.get('paragraph')
        sec = self.par_to_sec.get(par_id)
        return sec

    def _remove_multi_extraction_artifacts(self):
        # Build up a dict of evidence matches keys with statement UUIDs
        evmks = {}
        logger.debug('Starting with %d Statements.' % len(self.statements))
        for stmt in self.statements:
            if isinstance(stmt, Event):
                evmk = stmt.evidence[0].matches_key()
            elif isinstance(stmt, Influence):
                evmk = (stmt.evidence[0].matches_key() +
                        stmt.subj.matches_key() + stmt.obj.matches_key())
            elif isinstance(stmt, Association):
                evmk = (stmt.evidence[0].matches_key() +
                        stmt.members[0].matches_key() +
                        stmt.members[1].matches_key())
            if evmk not in evmks:
                evmks[evmk] = [stmt.uuid]
            else:
                evmks[evmk].append(stmt.uuid)
        # This is a list of groups of statement UUIDs that are redundant
        multi_evmks = [v for k, v in evmks.items() if len(v) > 1]
        # We now figure out if anything needs to be removed
        to_remove = []
        # Remove redundant statements
        for uuids in multi_evmks:
            # Influence statements to be removed
            infl_stmts = [s for s in self.statements if (
                            s.uuid in uuids and isinstance(s, Influence))]
            infl_stmts = sorted(infl_stmts, key=lambda x: x.polarity_count(),
                                reverse=True)
            to_remove += [s.uuid for s in infl_stmts[1:]]
            # Association statements to be removed
            assn_stmts = [s for s in self.statements if (
                            s.uuid in uuids and isinstance(s, Association))]
            assn_stmts = sorted(assn_stmts, key=lambda x: x.polarity_count(),
                                reverse=True)
            # Standalone events to be removed
            events = [s for s in self.statements if (
                        s.uuid in uuids and isinstance(s, Event))]
            events = sorted(events, key=lambda x: event_delta_score(x),
                            reverse=True)
            to_remove += [e.uuid for e in events[1:]]

        # Remove all redundant statements
        if to_remove:
            logger.debug('Found %d Statements to remove' % len(to_remove))
        self.statements = [s for s in self.statements
                           if s.uuid not in to_remove]

def sanitize_name(txt):
    name = txt.replace('\n', '')
    return name

def event_delta_score(stmt):
    pol_score = 1 if stmt.delta['polarity'] is not None else 0
    adj_score = len(stmt.delta['adjectives'])
    return (pol_score + adj_score)


text:
'use strict';

var assert = require('chai').assert,
    LIB = require('../api-validator.js'),
    AV = LIB.validate,
    AS = LIB.schema,
    nock = require('nock'),

    baseurl = 'http://fake.host',
    NoConnectURL = 'http://localhost:1/',

    PATHS = {
        NULL: '/getNull',
        ABC123: '/getJsonAbc123',
        ABCDEF: '/getJsonAbcDef'
    },

    setupFakeHTTP = function () {
        nock(baseurl)
        .get(PATHS.NULL).reply(200, '')
        .get(PATHS.ABC123).reply(200, {abc: 123})
        .get(PATHS.ABCDEF).reply(200, {abc: '123', def: 0});
    },

    cleanFakeHTTP = function () {
        nock.cleanAll();
    },

    testSchema1 = {
        '$schema': 'http://json-schema.org/draft-04/schema#',
        'type': 'object',
        required: ['abc', 'def'],
        properties: {
            abc: {
                type: 'string'
            },
            def: {},
            ghi: {
                default: 'DEFAULT'
            }
        }
    };

describe('Validator.one', function () {
    it('should be failed as internal error', function (done) {
        assert.deepEqual({"error":[{"type":"internal","message":"No input for AValidator.one"}]}, AV.one());
        done();
    });

    it('should be failed as input error', function (done) {
        assert.deepEqual({"error":[{"type":"input","message":"No schema in input for AValidator.one"}]}, AV.one({}));
        done();
    });

    it('should be passed by the schema', function (done) {
        assert.deepEqual(null, AV.one({
            data: {abc: 'dev', def: 1},
            schema: testSchema1
        }));
        done();
    });

    it('should be failed by the schema', function (done) {
        assert.deepEqual({"error":[{"type":"validation","target":"def","rule":{"required":true}},{"type":"validation","target":"abc","rule":{"type":"string"}}]}, AV.one({
            data: {abc: 1},
            schema: testSchema1
        }));
        done();
    });

    it('should validate by schema name', function (done) {
        assert.deepEqual(null, AV.one({
            data: {abc: 'dev', def: 1},
            schemas: {abcde123: testSchema1},
            schema: 'abcde123'
        }));
        done();
    });

    it('should validate by schema name with #path', function (done) {
        assert.deepEqual(null, AV.one({
            data: 1,
            schemas: AS.loadCoreSchemas(),
            schema: 'http://json-schema.org/draft-04/schema#/definitions/positiveInteger'
        }));
        done();
    });

    it('should set default value', function (done) {
        var O = {
            data: {abc: '1', def: 0},
            schema: testSchema1
        };
        assert.equal(undefined, AV.one(O, {useDefault: true}));
        assert.equal('DEFAULT', O.data.ghi);
        done();
    });
});

describe('Validator.selfVerify', function () {
    it('should passed all core schemas', function (done) {
        assert.deepEqual({}, AV.selfVerify(AS.loadCoreSchemas()));
        done();
    });

    it('should failed by a none title schema', function (done) {
        var C = AS.loadCoreSchemas(),
            FN = 'test/schemas/error.jschema',
            S = AS.load([FN]);

        C['test'] = S[FN];

        assert.deepProperty(AV.selfVerify(C), 'test.error');
        done();
    });

    it('should failed when $schema not founds in provided schemas', function (done) {
        var C = AS.loadCoreSchemas(),
            FN = 'test/schemas/schema_notfound.jschema',
            S = AS.load([FN]);

        C['test'] = S[FN];

        assert.deepEqual({test: {error: [{
            'type': 'schemas',
            message: 'can not find schema "never_be_found"'
        }]}}, AV.selfVerify(C));
        done();
    });
});


text:
SRC         = Parser

# We never run small.out since it's not feasible.
TARGETS			= qcGen.out smart.out

all : $(TARGETS)

include ../Config.mk


text:
Code to accompany Adventures in Arduino, Wiley (2015)

Visit the [book's companion site](http://www.adventuresinarduinobook.com/) for more information.


text:
package org.droolsfiddle.rest;

import org.drools.compiler.compiler.DroolsParserException;
import org.droolsfiddle.rest.model.Request;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

/**
 * Created by gurfm on 29/06/16.
 */
@Path("/drools")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface DrlParserService {

    @POST
    @Path("/drlParser")
    Request postDrlParser(Request iRequest) throws DroolsParserException;

}


text:
package gw.lang.parser;

public interface IGosuValidator
{
  /**
   * Provides additional semantic checks to a Gosu parser
   *
   * @param rootParsedElement - the root parsed element to validate from
   */
  void validate( IParsedElement rootParsedElement, String scriptSrc );
}


text:
    [EVENT_OBJECT_##capital_] = pretty_,
#define COMMAND_TO_STRING(capital_, pretty_, str_id_, parser)   \
    [EVENT_COMMAND_##capital_] = pretty_,

#define OBJECT_TO_MSTRING(id_, pretty_, display_, capital_, parser)     \
    [EVENT_OBJECT_##capital_] = (display_ ? pretty_ : #id_),
#define COMMAND_TO_MSTRING(capital_, pretty_, str_id_, parser)  \
    [EVENT_COMMAND_##capital_] = #str_id_,

#define LAYER_TO_STRING(id_, pretty_, capital_) \
    [EVENT_LAYER_##capital_] = pretty_,
#define LOOP_TO_STRING(id_, pretty_, capital_)  \
    [EVENT_##capital_] = pretty_,
#define ORIG_TO_STRING(id_, pretty_, capital_)  \
    [EVENT_ORIGIN_##capital_] = pretty_,

static char const *event_str[MAX_EVENT_TYPE] = {
    EVENT_OBJECTS(OBJECT_TO_STRING)
    EVENT_COMMANDS(COMMAND_TO_STRING)
};
static char const *event_map_str[MAX_EVENT_TYPE] = {
    EVENT_OBJECTS(OBJECT_TO_MSTRING)
    EVENT_COMMANDS(COMMAND_TO_MSTRING)
};

static char const *layer_str[MAX_LAYER] = {
    EVENT_LAYERS(LAYER_TO_STRING)
};
static char const *loop_str[MAX_LOOP] = {
    EVENT_LOOPS(LOOP_TO_STRING)
};
static char const *orig_str[MAX_ORIGIN] = {
    EVENT_ORIGINS(ORIG_TO_STRING)
};

char const *osux_event_type_get_name(int event_type)
{
    if (event_type < 0 || event_type >= MAX_EVENT_TYPE)
        return NULL;
    return event_str[event_type];
}

char const *osux_event_type_get_mname(int event_type)
{
    if (event_type < 0 || event_type >= MAX_EVENT_TYPE)
        return NULL;
    return event_map_str[event_type];
}

char const *osux_event_layer_get_name(int layer)
{
    if (layer < 0 || layer >= MAX_LAYER)
        return NULL;
    return layer_str[layer];
}

char const *osux_event_loop_get_name(int loop)
{
    if (loop < 0 || loop >= MAX_LOOP)
        return NULL;
    return loop_str[loop];
}

char const *osux_event_origin_get_name(int orig)
{
    if (orig < 0 || orig >= MAX_ORIGIN)
        return NULL;
    return orig_str[orig];
}


text:
package wvw.utils.android;

import java.io.File;
import java.io.IOException;

import android.content.Context;

public class AndroidIOUtils {

	// courtesy of
	// http://android-developers.blogspot.co.nz/2011/07/custom-class-loading-in-dalvik.html
	public static void copyFromAssets(String assetPath, File destFile, Context context) throws IOException {
		wvw.utils.IOUtils.writeToFile(context.getAssets().open(assetPath), destFile);
	}
}


text:
@interface UMComDiscoverViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UIButton *rightButton;

@property (nonatomic, strong) UIView *systemNotificationView;

@property (nonatomic, strong) UIView *userMessageView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UMComUserInfoBar *userInfoBar;

@end

@implementation UMComDiscoverViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setForumUIBackButton];
    [self setForumUITitle:UMComLocalizedString(@"um_com_find", @"我的")];

    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    [self.tableView registerNib:[UINib nibWithNibName:@"UMComFindTableViewCell" bundle:nil] forCellReuseIdentifier:@"FindTableViewCell"];
    self.tableView.rowHeight = 55.0f;
    if (UMCom_Current_System_Version >= 7.0 && UMCom_Current_System_Version < 8) {
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }else{
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    [self.view addSubview:self.tableView];

    UIButton *menuItemButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [menuItemButton addTarget:self action:@selector(tranToSetting) forControlEvents:UIControlEventTouchUpInside];
    [menuItemButton setImage:UMComImageWithImageName(@"um_setting_normal") forState:UIControlStateNormal];
    [menuItemButton setImage:UMComImageWithImageName(@"um_setting_highlighted") forState:UIControlStateHighlighted];
    menuItemButton.frame = CGRectMake(0.f, 0.f, 20.f, 20.f);

    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithCustomView:menuItemButton];

    [self.navigationItem setRightBarButtonItem:menuItem];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshNoticeItemViews) name:kUMComUnreadNotificationRefreshNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMessageData:) name:UIApplicationWillEnterForegroundNotification object:nil];
    [self refreshNoticeItemViews];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.rightButton removeFromSuperview];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)refreshMessageData:(id)sender
{
    if (![[UMComSession sharedInstance] isLogin]) {
        return;
    }
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [[UMComSession sharedInstance] refreshConfigDataWithCompletion:^(NSDictionary *configData, NSError *error) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
}
- (void)refreshNoticeItemViews
{
    [self.tableView reloadData];
}

- (UIView *)creatNoticeViewWithOriginX:(CGFloat)originX
{
    CGFloat noticeViewWidth = 7;
    UIView *itemNoticeView = [[UIView alloc]initWithFrame:CGRectMake(originX,0, noticeViewWidth, noticeViewWidth)];
    itemNoticeView.backgroundColor = [UIColor redColor];
    itemNoticeView.layer.cornerRadius = noticeViewWidth/2;
    itemNoticeView.clipsToBounds = YES;
    itemNoticeView.hidden = YES;
    return itemNoticeView;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    } else if (section == 1) {
        return 5;
    } else {
        return 5;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"FindTableViewCell";
    UMComFindTableViewCell *cell = (UMComFindTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.section == 0) {

    } else if (indexPath.section == 1) {
        switch (indexPath.row) {
            case 0: {
                cell.titleImageView.image = UMComImageWithImageName(@"um_notice_f");
                cell.titleNameLabel.text = UMComLocalizedString(@"um_news_notice", @"我的消息");

                UMComUnReadNoticeModel *unReadNotice = [UMComSession sharedInstance].unReadNoticeModel;
                if (unReadNotice.totalNotiCount == 0) {
                    self.userMessageView.hidden = YES;
                }else{
                    if (!self.userMessageView) {
                        CGFloat padding = 2;
                        CGFloat defaultNoticeViewOriginX = 115;
                        CGSize nameSize = [cell.titleNameLabel.text sizeWithFont:cell.titleNameLabel.font];
                        CGFloat noticeViewOriginX = cell.titleNameLabel.frame.origin.x + nameSize.width + padding;
                        if (noticeViewOriginX >= cell.contentView.bounds.size.width) {
                            //大于cell的宽度就减去padding
                            noticeViewOriginX = cell.contentView.bounds.size.width - padding;
                        }
                        else if (noticeViewOriginX <= 0)
                        {
                            //小于0就用默认
                            noticeViewOriginX = defaultNoticeViewOriginX;
                        }
                        else{}
                        self.userMessageView = [self creatNoticeViewWithOriginX:noticeViewOriginX];
                        self.userMessageView.center = CGPointMake(self.userMessageView.center.x, cell.titleNameLabel.frame.origin.y+11);
                        [cell.contentView addSubview:self.userMessageView];
                    } else {
                        if (self.userMessageView.superview != cell.contentView) {
                            [self.userMessageView removeFromSuperview];
                            [cell addSubview:self.userMessageView];
                        }
                    }
                    self.userMessageView.hidden = NO;
                }
            }
                break;
            case 1: {
                cell.titleImageView.image = UMComImageWithImageName(@"um_fav+");
                cell.titleNameLabel.text = UMComLocalizedString(@"um_com_user_collection", @"我的收藏");
            }
                break;
            case 2: {
                cell.titleImageView.image = UMComImageWithImageName(@"um_friend");
                cell.titleNameLabel.text = UMComLocalizedString(@"um_com_friend", @"好友圈");
            }
                break;
            case 3: {
                // 我关注的
                cell.titleImageView.image = UMComImageWithImageName(@"um_follow_topic");
                cell.titleNameLabel.text = UMComLocalizedString(@"um_follow_topic", @"我关注的话题");
            }
                break;
            case 4: {
                // 我的图册
                cell.titleImageView.image = UMComImageWithImageName(@"um_my_gallery");
                cell.titleNameLabel.text = UMComLocalizedString(@"um_my_gallery", @"我的图册");
            }
                break;
            default:
                break;
        }
    } else {
        switch (indexPath.row) {
            case 0: {
                cell.titleImageView.image = UMComImageWithImageName(@"um_near");
                cell.titleNameLabel.text = UMComLocalizedString(@"um_com_nearbyRecommend", @"附近内容");
            }
                break;
            case 1: {
                cell.titleImageView.image = UMComImageWithImageName(@"um_nearbyuser");
                cell.titleNameLabel.text = UMComLocalizedString(@"um_nearbyuser", @"附近用户");
            }
                break;
            case 2: {
                cell.titleImageView.image = UMComImageWithImageName(@"um_newcontent");
                cell.titleNameLabel.text = UMComLocalizedString(@"um_com_newcontent", @"实时内容");
            }
                break;
            case 3: {
                cell.titleImageView.image = UMComImageWithImageName(@"user_recommend");
                cell.titleNameLabel.text = UMComLocalizedString(@"um_com_user_recommend", @"用户推荐");
            }
                break;
            case 4: {
                cell.titleImageView.image = UMComImageWithImageName(@"topic_recommend");
                cell.titleNameLabel.text = UMComLocalizedString(@"topic_recommend", @"话题推荐");
            }
                break;
            default:
                break;
        }
    }
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIEdgeInsets edge = UIEdgeInsetsMake(tableView.rowHeight - 1, 15, 0, 0);
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:edge];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableView setLayoutMargins:edge];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 91.f;
    } else if (section == 1) {
        return 31.0f;
    }else {
        return 31.0f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        NSArray *xibs = [[NSBundle mainBundle] loadNibNamed:@"UMComUserInfoBar" owner:self options:nil];
        self.userInfoBar = xibs[0];

        [_userInfoBar refresh];
        [_userInfoBar addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(prepareToUserCenter)]];
        return _userInfoBar;
    } else if (section == 1) {
        return [self headViewWithTitle:UMComLocalizedString(@"um_com_find", @"我的") viewHeight:31];
    } else {
        return [self headViewWithTitle:UMComLocalizedString(@"um_com_recommend", @"推荐") viewHeight:31];
    }
}

- (UIView *)headViewWithTitle:(NSString *)title viewHeight:(CGFloat)viewHeight
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, viewHeight)];
    view.backgroundColor = UMComColorWithHexString(@"#F5F6FA");
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(13, 0, 50, 30)];
    CGPoint center = label.center;
    center.y = view.frame.size.height / 2.f;
    label.center = center;
    label.backgroundColor = [UIColor clearColor];
    label.text = title;
    label.textColor = UMComColorWithHexString(FontColorGray);
    label.font = UMComFontNotoSansLightWithSafeSize(13.f);
    [view addSubview:label];
    UIView *bottomLine = [[UIView alloc]initWithFrame:CGRectMake(0,viewHeight-0.5,view.frame.size.width,0.5)];
    bottomLine.backgroundColor = UMComTableViewSeparatorColor;
    [view addSubview:bottomLine];

    if ([[UIDevice currentDevice].systemVersion floatValue] < 8.0) {
        UIView *topLine = [[UIView alloc]initWithFrame:CGRectMake(0,0,view.frame.size.width,0.5)];
        topLine.backgroundColor = UMComTableViewSeparatorColor;
        [view addSubview:topLine];
    }
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {

    } else if (indexPath.section == 1) {
        [UMComLoginManager performLogin:self completion:^(id responseObject, NSError *error) {
            if (error) {
                return;
            }
            switch (indexPath.row) {
                case 0:
                {
                    self.userMessageView.hidden = YES;
                    [self tranToUsersNotice];
                }
                    break;
                case 1:
                    [self tranToUsersFavourites];
                    break;
                case 2:
                    [self tranToCircleFriends];
                    break;
                case 3:
                    [self tranToFollowedTopic];
                    break;
                case 4:
                    [self tranToAlbum];
                    break;

                default:
                    break;
            }
        }];
    }else if(indexPath.section == 2){
        switch (indexPath.row) {
            case 0:
            {
                [UMComLoginManager performLogin:self completion:^(id responseObject, NSError *error) {
                    if (!error) {
                       [self tranToNearby];
                    }

                }];
            }
                break;

            case 1:
            {
                [UMComLoginManager performLogin:self completion:^(id responseObject, NSError *error) {
                    if (!error) {
                       [self tranToNearbyUsers];
                    }

                }];
            }
                break;
            case 2:
                [self tranToRealTimeFeeds];
                break;
            case 3:
                [self tranToRecommendUsers];
                break;
            case 4:
                [self tranToRecommendTopics];
                break;

            default:
                break;
        }
    }
}

- (void)prepareToUserCenter
{
    if ([UMComLoginManager isLogin]) {
        [self tranToUserCenter];
    } else {
        __weak typeof(self) ws = self;
        [UMComLoginManager performLogin:self completion:^(id responseObject, NSError *error) {
            if (!error) {
                [ws.userInfoBar refresh];
            }
        }];

    }
}

- (void)tranToCircleFriends
{

}

- (void)tranToFollowedTopic
{

}

- (void)tranToAlbum
{

}

- (void)tranToNearby
{

}

- (void)tranToNearbyUsers
{

}

- (void)tranToRealTimeFeeds
{

}

- (void)tranToRecommendUsers
{

}

- (void)tranToRecommendTopics
{

}

- (void)tranToUsersFavourites
{

}

- (void)tranToUsersNotice
{

}

- (void)tranToSetting
{
    __weak typeof(self) ws = self;
    [UMComLoginManager performLogin:self completion:^(id responseObject, NSError *error) {
        if (!error) {
            UMComProfileSettingController *settingVc = [[UMComProfileSettingController alloc]initWithNibName:@"UMComProfileSettingController" bundle:nil];
            [ws.navigationController pushViewController:settingVc animated:YES];
        }
    }];
}

- (void)tranToUserCenter
{

}

@end


text:
function prompt_get_git_branch() {
  ref="$(git symbolic-ref HEAD 2> /dev/null)"
  if [[ "$ref" != "" ]]; then
    echo "${ref/refs\/heads\//}"
  else
    echo "(no branch)"
  fi
}

function prompt_get_git_progress() {
  # Detect in-progress actions (e.g. merge, rebase)
  # https://github.com/git/git/blob/v1.9-rc2/wt-status.c#L1199-L1241
  git_dir="$(git rev-parse --git-dir)"

  # git merge
  if [[ -f "$git_dir/MERGE_HEAD" ]]; then
    echo " [merge]"
  elif [[ -d "$git_dir/rebase-apply" ]]; then
    # git am
    if [[ -f "$git_dir/rebase-apply/applying" ]]; then
      echo " [am]"
    # git rebase
    else
      echo " [rebase]"
    fi
  elif [[ -d "$git_dir/rebase-merge" ]]; then
    # git rebase --interactive/--merge
    echo " [rebase]"
  elif [[ -f "$git_dir/CHERRY_PICK_HEAD" ]]; then
    # git cherry-pick
    echo " [cherry-pick]"
  fi
  if [[ -f "$git_dir/BISECT_LOG" ]]; then
    # git bisect
    echo " [bisect]"
  fi
  if [[ -f "$git_dir/REVERT_HEAD" ]]; then
    # git revert --no-commit
    echo " [revert]"
  fi
}

prompt_is_branch1_behind_branch2 () {
  # $ git log origin/master..master -1
  # commit 4a633f715caf26f6e9495198f89bba20f3402a32
  # Author: Todd Wolfson <todd@twolfson.com>
  # Date:   Sun Jul 7 22:12:17 2013 -0700
  #
  #     Unsynced commit

  # Find the first log (if any) that is in branch1 but not branch2
  first_log="$(git log $1..$2 -1 2> /dev/null)"

  # Exit with 0 if there is a first log, 1 if there is not
  [[ -n "$first_log" ]]
}

prompt_branch_exists () {
  # List remote branches           | # Find our branch and exit with 0 or 1 if found/not found
  git branch --remote 2> /dev/null | grep --quiet "$1"
}

prompt_parse_git_ahead () {
  # Grab the local and remote branch
  branch="$(prompt_get_git_branch)"
  remote="$(git config --get "branch.${branch}.remote" || echo -n "origin")"
  remote_branch="$remote/$branch"

  # $ git log origin/master..master
  # commit 4a633f715caf26f6e9495198f89bba20f3402a32
  # Author: Todd Wolfson <todd@twolfson.com>
  # Date:   Sun Jul 7 22:12:17 2013 -0700
  #
  #     Unsynced commit

  # If the remote branch is behind the local branch
  # or it has not been merged into origin (remote branch doesn't exist)
  if (prompt_is_branch1_behind_branch2 "$remote_branch" "$branch" ||
      ! prompt_branch_exists "$remote_branch"); then
    # echo our character
    echo 1
  fi
}

prompt_parse_git_behind () {
  # Grab the branch
  branch="$(prompt_get_git_branch)"
  remote="$(git config --get "branch.${branch}.remote" || echo -n "origin")"
  remote_branch="$remote/$branch"

  # $ git log master..origin/master
  # commit 4a633f715caf26f6e9495198f89bba20f3402a32
  # Author: Todd Wolfson <todd@twolfson.com>
  # Date:   Sun Jul 7 22:12:17 2013 -0700
  #
  #     Unsynced commit

  # If the local branch is behind the remote branch
  if prompt_is_branch1_behind_branch2 "$branch" "$remote_branch"; then
    # echo our character
    echo 1
  fi
}

function prompt_parse_git_dirty() {
  # If the git status has *any* changes (e.g. dirty), echo our character
  if [[ -n "$(git status --porcelain 2> /dev/null)" ]]; then
    echo 1
  fi
}

# Set up symbols
prompt_synced_symbol=""
prompt_dirty_synced_symbol="*"
prompt_unpushed_symbol="△"
prompt_dirty_unpushed_symbol="▲"
prompt_unpulled_symbol="▽"
prompt_dirty_unpulled_symbol="▼"
prompt_unpushed_unpulled_symbol="⬡"
prompt_dirty_unpushed_unpulled_symbol="⬢"

function prompt_get_git_status() {
  # Grab the git dirty and git behind
  dirty_branch="$(prompt_parse_git_dirty)"
  branch_ahead="$(prompt_parse_git_ahead)"
  branch_behind="$(prompt_parse_git_behind)"

  # Iterate through all the cases and if it matches, then echo
  if [[ "$dirty_branch" == 1 && "$branch_ahead" == 1 && "$branch_behind" == 1 ]]; then
    echo "$prompt_dirty_unpushed_unpulled_symbol"
  elif [[ "$branch_ahead" == 1 && "$branch_behind" == 1 ]]; then
    echo "$prompt_unpushed_unpulled_symbol"
  elif [[ "$dirty_branch" == 1 && "$branch_ahead" == 1 ]]; then
    echo "$prompt_dirty_unpushed_symbol"
  elif [[ "$branch_ahead" == 1 ]]; then
    echo "$prompt_unpushed_symbol"
  elif [[ "$dirty_branch" == 1 && "$branch_behind" == 1 ]]; then
    echo "$prompt_dirty_unpulled_symbol"
  elif [[ "$branch_behind" == 1 ]]; then
    echo "$prompt_unpulled_symbol"
  elif [[ "$dirty_branch" == 1 ]]; then
    echo "$prompt_dirty_synced_symbol"
  else # clean
    echo "$prompt_synced_symbol"
  fi
}

prompt_git () {
  if git rev-parse 2> /dev/null; then
    echo "#$(tput setaf 3)$(prompt_get_git_branch)$(prompt_get_git_status)$(tput setaf 1)$(prompt_get_git_progress)$(tput sgr0)"
  fi
}

prompt_machine () {
  if [[ -v SSH_CONNECTION ]]
  then
    echo "$(tput setaf 4)%n$(tput sgr0)@$(tput setaf 6)%m$(tput sgr0)"
  fi
}

prompt_k8_context() {
  echo $(kubectl config current-context 2> /dev/null)
}

setopt prompt_subst

prompt='$(prompt_machine):$(tput setaf 2)$(tput bold)%~$(tput sgr0)$(prompt_git)
$(echo -n $DOCKER_MACHINE_NAME $DOCKER_HOST $(prompt_k8_context) )%{%(?..$(tput setaf 1))%} %% %{$(tput sgr0)%}'


text:
define(["dojo/_base/declare","./_Indicator"],
  function(declare, Indicator) {

return declare("dojox.gauges.TextIndicator", [Indicator], {
	// summary:
	//		A gauge indicator the simply draws its value as text.

	// x: Number
	//		The x coordinate of the indicator
	x: 0,

	// y: Number
	//		The y coordinate of the indicator
	y: 0,

	// align: String
	//		The horizontal alignment of the text, the value can be 'middle' (the default), 'left' or 'right'
	align: 'middle',

	// fixedPrecision: Boolean
	//		Indicates that the number is displayed in fixed precision or not (precision is defined by the 'precision' property (default is true).
	fixedPrecision: true,

	// precision: Number
	//		The number of tailing digits to display the value of the indicator when the 'fixedPrecision' property is set to true (default is 0).
	precision: 0,

	draw: function(group, /*Boolean?*/ dontAnimate){
		// summary:
		//		Override of dojox.gauges._Indicator.draw
		var v = this.value;

		if (v < this._gauge.min) {
			v = this._gauge.min;
		}
		if (v > this._gauge.max) {
			v = this._gauge.max;
		}
		var txt;
		var NumberUtils = this._gauge ? this._gauge._getNumberModule() : null;
		if (NumberUtils) {
			txt = this.fixedPrecision ? NumberUtils.format(v, {
				places: this.precision
			}) : NumberUtils.format(v);
		} else {
			txt = this.fixedPrecision ? v.toFixed(this.precision) : v.toString();
		}

		var x = this.x ? this.x : 0;
		var y = this.y ? this.y : 0;
		var align = this.align ? this.align : "middle";
		if(!this.shape){
			this.shape = group.createText({
				x: x,
				y: y,
				text: txt,
				align: align
			});
		}else{
			this.shape.setShape({
				x: x,
				y: y,
				text: txt,
				align: align
			});
		}
		this.shape.setFill(this.color);
		if (this.font) this.shape.setFont(this.font);

	}

});
});


text:
#include <Modules/Legacy/Fields/ConvertQuadSurfToTriSurf.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Testing/ModuleTestBase/ModuleTestBase.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/DenseMatrix.h>

using namespace SCIRun;
using namespace SCIRun::Testing;
using namespace SCIRun::Modules::Fields;
using namespace SCIRun::Core;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Dataflow::Networks;
using ::testing::_;
using ::testing::NiceMock;
using ::testing::DefaultValue;
using ::testing::Return;

class ConvertHexVolToTetVolModuleTests : public ModuleTest
{
 protected:

  FieldHandle CreateEmptyLatVol(size_type sizex = 3, size_type sizey = 4, size_type sizez = 5, data_info_type type=data_info_type::DOUBLE_E)
  {
    FieldInformation lfi(mesh_info_type::LATVOLMESH_E, databasis_info_type::LINEARDATA_E, type);
    Point minb(-1.0, -1.0, -1.0);
    Point maxb(1.0, 1.0, 1.0);
    MeshHandle mesh = CreateMesh(lfi, sizex, sizey, sizez, minb, maxb);
    FieldHandle ofh = CreateField(lfi,mesh);
    return ofh;
  }

 DenseMatrixHandle CreateDenseMatrix()
 {
  DenseMatrixHandle m(makeShared<DenseMatrix>(3,3));
  (*m)(0,0) = 1;
  (*m)(1,0) = 2;
  (*m)(2,0) = 3;
  return m;
 }
};

TEST_F(ConvertHexVolToTetVolModuleTests, ThrowsForNullInput)
{
  auto csdf = makeModule("ConvertHexVolToTetVol");
  FieldHandle nullField;
  stubPortNWithThisData(csdf, 0, nullField);

  EXPECT_THROW(csdf->execute(), NullHandleOnPortException);
}

TEST_F(ConvertHexVolToTetVolModuleTests, WrongDataType)
{
  auto csdf = makeModule("ConvertHexVolToTetVol");
  stubPortNWithThisData(csdf, 0, CreateDenseMatrix());
  EXPECT_THROW(csdf->execute(), DataPortException);
}

TEST_F(ConvertHexVolToTetVolModuleTests, CorrectInput)
{
  auto csdf = makeModule("ConvertHexVolToTetVol");
  auto size=6;
  stubPortNWithThisData(csdf, 0, CreateEmptyLatVol(size, size, size, data_info_type::INT_E));
  EXPECT_NO_THROW(csdf->execute());
}


text:
/*
 * Name: Application.java
 * Project: SensorAct-VPDS
 * Version: 1.0
 * Date: 2012-04-14
 * Authors: Pandarasamy Arjunan, Haksoo Choi
 */
package controllers;

import java.util.HashMap;
import java.util.Map;

import play.mvc.Before;
import play.mvc.Controller;
import edu.pc3.sensoract.vpds.api.SensorActAPI;
import edu.pc3.sensoract.vpds.api.request.TaskletAddFormat;

/**
 * Application class, entry point for all APIs.
 *
 * @author Pandarasamy Arjunan, Haksoo Choi and Manaswi Saha
 * @version 1.1
 */

public class Application extends Controller {

	@Before
	static void handleHeaders() {
		// System.out.println("key is : " +
		// request.headers.get("x-key").value());
	}

	//@Before(unless = {"/"})
	static void sslOrRedirect() {

		// skip https for localhost
		if(request.getBase().toString().contains("localhost"))
			return;

		// force to use https on other domains e.g. google app engine
		if (!request.secure) {
			redirect("https://" + request.host + request.url);
		}
	}

	public static void index() {
		renderText("Welcome to SensorAct!");
	}

	// Repo information
	public static void repoInfo() {
		SensorActAPI.repoInfo.doProcess();
	}

	// User profile management
	public static void userLogin() {
		SensorActAPI.userLogin.doProcess(request.params.get("body"));
	}

	public static void userRegister() {
		SensorActAPI.userRegister.doProcess(request.params.get("body"));
	}

	public static void userList() {
		SensorActAPI.userList.doProcess(request.params.get("body"));
	}

	// User key management
	public static void keyGenerate() {
		SensorActAPI.keyGenerate.doProcess(request.params.get("body"));
	}

	public static void keyDelete() {
		SensorActAPI.keyDelete.doProcess(request.params.get("body"));
	}

	public static void keyList() {
		SensorActAPI.keyList.doProcess(request.params.get("body"));
	}

	public static void keyEnable() {
		SensorActAPI.keyEnable.doProcess(request.params.get("body"));
	}

	public static void keyDisable() {
		SensorActAPI.keyDisable.doProcess(request.params.get("body"));
	}

	// Device profile management
	public static void deviceAdd() {
		SensorActAPI.deviceAdd.doProcess(request.params.get("body"));
	}

	public static void deviceDelete() {
		SensorActAPI.deviceDelete.doProcess(request.params.get("body"));
	}

	public static void deviceGet() {
		SensorActAPI.deviceGet.doProcess(request.params.get("body"));
	}

	public static void deviceList() {
		SensorActAPI.deviceList.doProcess(request.params.get("body"));
	}

	public static void deviceShare() {
		SensorActAPI.deviceShare.doProcess(request.params.get("body"));
	}

	public static void deviceSearch() {
		SensorActAPI.deviceSearch.doProcess(request.params.get("body"));
	}

	// Device template management
	public static void deviceTemplateAdd() {
		SensorActAPI.deviceTemplateAdd.doProcess(request.params.get("body"));
	}

	public static void deviceTemplateDelete() {
		SensorActAPI.deviceTemplateDelete.doProcess(request.params.get("body"));
	}

	public static void deviceTemplateGet() {
		SensorActAPI.deviceTemplateGet.doProcess(request.params.get("body"));
	}

	public static void deviceTemplateList() {
		SensorActAPI.deviceTemplateList.doProcess(request.params.get("body"));
	}

	public static void deviceTemplateGlobalList() {
		SensorActAPI.deviceTemplateGlobalList.doProcess(request.params
				.get("body"));
	}

	// Guard rule management
	public static void guardRuleAdd() {
		SensorActAPI.guardRuleAdd.doProcess(request.params.get("body"));
	}

	public static void guardRuleDelete() {
		SensorActAPI.guardRuleDelete.doProcess(request.params.get("body"));
	}

	public static void guardRuleGet() {
		SensorActAPI.guardRuleGet.doProcess(request.params.get("body"));
	}

	public static void guardRuleList() {
		SensorActAPI.guardRuleList.doProcess(request.params.get("body"));
	}

	public static void guardRuleAssociationAdd() {
		SensorActAPI.guardRuleAssociationAdd.doProcess(request.params
				.get("body"));
	}

	public static void guardRuleAssociationDelete() {
		SensorActAPI.guardRuleAssociationDelete.doProcess(request.params
				.get("body"));
	}

	public static void guardRuleAssociationGet() {
		SensorActAPI.guardRuleAssociationGet.doProcess(request.params
				.get("body"));
	}

	public static void guardRuleAssociationList() {
		SensorActAPI.guardRuleAssociationList.doProcess(request.params
				.get("body"));
	}

	// Task management
	public static void taskletAdd() {
		System.out.println(request.params.get("body"));
		SensorActAPI.taskletAdd.doProcess(request.params.get("body"));
	}

	public static void taskletDelete() {
		SensorActAPI.taskleteDelete.doProcess(request.params.get("body"));
	}

	public static void taskletGet() {
		SensorActAPI.taskletGet.doProcess(request.params.get("body"));
	}

	public static void taskletList() {
		SensorActAPI.taskletList.doProcess(request.params.get("body"));
	}

	public static void taskletExecute() {
		SensorActAPI.taskletExecute.doProcess(request.params.get("body"));
	}

	public static void taskletStatus() {
		SensorActAPI.taskletStatus.doProcess(request.params.get("body"));
	}

	public static void taskletCancel() {
		SensorActAPI.taskletCancel.doProcess(request.params.get("body"));
	}

	// Data management
	public static void dataQuery() {
		SensorActAPI.dataQuery.doProcess(request.params.get("body"));
	}

	public static void dataQueryV2(String device, String sensor, String channel,
			long start, long end, String timeformat) {

		final String XAPIKEY = "x-apikey";

		for(String k : request.headers.keySet()) {
		//	System.out.println(request.headers.get(k).name);
		}

		String secretkey = null;
		if(request.headers.containsKey(XAPIKEY)) {
			secretkey =  request.headers.get(XAPIKEY).value();
		} else {
			renderText("Unregistered secretkey");
		}

		//System.out.println("secretkey " + secretkey + " " + start + " " + end);
		SensorActAPI.dataQueryv2.doProcess(secretkey, device, sensor, channel, start, end, timeformat);
	}

	public static void dataUploadWaveSegment() {
		SensorActAPI.dataUpload.doProcess(request.params.get("body"));
	}

	public static void putDeviceData(String device) {
		renderText("Device " + device);
		// SensorActAPI.putData.doProcess(request.params.get("body"));
	}

	public static void putDeviceSensorData(String device, String sensor) {
		renderText("Device " + device + " Sensor " + sensor);
		// SensorActAPI.putData.doProcess(request.params.get("body"));
	}

	// TODO: refer play framework cookbook about router head
	public static void putDeviceSensorChannelData(String device, String sensor,
			String channel, String time, String value) {

		// SensorActAPI.putData.doProcess(request.params.get("body"));

		final String XAPIKEY = "x-apikey";
		//for(String k : request.headers.keySet()) {
			//System.out.println(request.headers.get(k).name);
		//}

		String secretkey = null;
		if(request.headers.containsKey(XAPIKEY)) {
			secretkey =  request.headers.get(XAPIKEY).value();
		} else {
			renderText("Invalid apikey");
		}

		SensorActAPI.dataUpload.doProcess(secretkey, device, sensor, channel, time, value);

		renderText("Device " + device + " Sensor " + sensor + " Channel "
				+ channel + " time " + time + " value " + value);
	}

	// TODO: refer play framework cookbook about router head
	public static void getDeviceSensorChannelData(String device, String sensor,
			String channel, String from, String to) {

		String interval = request.params.get("interval");
		String function = request.params.get("function");

		SensorActAPI.getDeviceSensorChannelData.doProcess(device, sensor,
				channel, from, to, interval, function);

		renderText("Device " + device + " Sensor " + sensor + " Channel "
				+ channel + " from " + from + " to " + to + "  interval "
				+ interval + "  function " + function);

	}

	public static void deviceActuate() {
		System.out.println(request.params.get("body"));
		SensorActAPI.deviceActuate.doProcess(request.params.get("body"));
	}

	// For Listing Actuation Requests
	public static void deviceListActuationRequest() {
		SensorActAPI.deviceListActuationRequest.doProcess(request.params
				.get("body"));
	}

	// For Canceling Actuation Requests
	public static void deviceCancelActuationRequest() {
		SensorActAPI.deviceCancelActuationRequest.doProcess(request.params
				.get("body"));
	}

	// For development test purpose.
	public static void test() throws Exception {

		new temp().loadComputedSensors();

		//new temp().ifxTest();
		//new temp().ifxDownload();

		renderText("done!");
	}

	public static void computedSensor1() {
		TaskletAddFormat t1 = new TaskletAddFormat();

		t1.taskletname = "computed1";
		t1.desc = "desc";

		Map<String,String> param = new HashMap<String,String>();
		param.put("c1", "nesl_owner:Test_Device1:Temperature:channel1");

		Map<String,String> input = new HashMap<String,String>();
		param.put("t1", "[0/5 * 0-23 * *]");

		String script = "print( 'reading ', d1); \n"
						+ "dd = VPDS:read(d1) \n"
						+ "print('its value ', dd )";

		t1.param = param;
		t1.input = input;

		t1.when = "t1";
		t1.execute = "script";

	}
}


text:
module.exports = function (data, process) {

    function checkForFailures(err) {
        if (err) {
            process.fail('Could not send POST request: ' + err);
        }
    }

    var branchToProtect = data.parameters.branch || 'master',
        preventInfiniteLoop = 'githook-super-protected-branches protected you!';

    if ( data.payload.ref !== ('refs/heads/' + branchToProtect) ) {
        process.succeed('the commit was to ' + data.payload.ref + ' and thus was not a problem');
    }
    else if (data.payload.head_commit.message === preventInfiniteLoop ) {
        process.succeed('This was an automated commit made by super-protected-branches, so processing was skipped');
    }
    else if (data.payload.head_commit.message.match(/Merge pull request #([0-9]+) from (.+)/)) {
        process.succeed('This commit came from merging another branch and thus was not a problem');
    }
    else {
        // STEP 1 - create a new branch off branchToProtect - this will be used to open the Pull Request later
        var newBranchName = branchToProtect + "--super-protected--" + Date.now(),
            options = {
                url: data.payload.repository.git_refs_url.replace('{/sha}', ''),
                headers: {
                    'Content-Type':  'application/json',
                    'User-Agent':    'super-protected-branches',
                    'Authorization': 'token ' + data.access_token
                },
                json: {
                    "ref": "refs/heads/" + newBranchName,
                    "sha": data.payload.after
                }
            };

        request.post(options, function newBranchCreated(err, httpResponse, body) {
            checkForFailures(err);

            // STEP 2 - create new temporary branch off branchToProtect - we will do our commit manipulation here
            // and eventually replace branchToProtect with this temporary branch.
            var tmpBranch = branchToProtect + "--tmp--" + Date.now();

            options.url = data.payload.repository.git_refs_url.replace('{/sha}', ''),
            options.json = {
                "ref": "refs/heads/" + tmpBranch,
                "sha": data.payload.before
            }
            request.post(options, function newBranchCreated(err, httpResponse, body) {
                checkForFailures(err);

                // STEP 3 - revert the directly pushed commit on our temporary branch
                // The reason we cannot do this directly on branchToProtect is that it would cause an
                // infinite loop in our GitHook!
                options.url = data.payload.repository.git_refs_url.replace('{/sha}', '/heads/' + tmpBranch),
                options.json = {
                    "force": true,
                    "sha": data.payload.before
                };
                request.patch(options, function forceRollback(err, httpResponse, body) {
                    checkForFailures(err);

                    // STEP 4 - add a new commit message `preventInfiniteLoop` to the `tmpBranch`.
                    // We have to apply the preventInfiniteLoop commit message to prevent an infinite
                    // loop (otherwise thie GitHook would be called again and would run all the revert
                    // code again).
                    // Adding a new commit message must be tackled in several steps.

                    // STEP 4.1 - get tree structure of the tmpBranch
                    options.url = data.payload.repository.trees_url.replace('{/sha}', '/' + data.payload.before);
                    options.json = {};
                    request.get(options, function getTreeStructure(err, httpResponse, body) {
                        checkForFailures(err);

                        // STEP 4.2 - post a new tree object, getting a tree SHA back
                        options.url = data.payload.repository.trees_url.replace('{/sha}', '');
                        options.json = {
                            "base_tree": data.payload.before,
                            "tree":      body.tree
                        };
                        request.post(options, function newTreeCreated(err, httpResponse, body) {
                            checkForFailures(err);

                            var treeSHA = body.sha;

                            // STEP 4.3 - create a new commit object with the current commit SHA as the parent and the new tree SHA, getting a commit SHA back
                            options.url = data.payload.repository.git_commits_url.replace('{/sha}', '');
                            options.json = {
                                "tree":    treeSHA,
                                "message": preventInfiniteLoop,
                                "parents": [data.payload.before]
                            };
                            request.post(options, function treeAssociatedWithCommit(err, httpResponse, body) {
                                checkForFailures(err);

                                var commitSHA = body.sha;

                                // STEP 5 - point the `branchToProtect` head to the latest commit to `body.sha`
                                // (which contains the 'githook-super-protected-branches saved you!' commit message)
                                options.url = data.payload.repository.git_refs_url.replace('{/sha}', '/heads/' + branchToProtect);
                                options.json = {
                                    "sha": commitSHA,
                                    "force": true
                                };
                                request.patch(options, function protectedBranchReverted(err, httpResponse, body) {
                                    checkForFailures(err);

                                    // STEP 6 - open a PR with `newBranchName`
                                    options.url = data.payload.repository.pulls_url.replace('{/number}', '');
                                    options.json = {
                                        title: data.payload.head_commit.message,
                                        body:  'This pull request was automatically generated by the [Super Protected Branches GitHook](http://githooks.io/githooks/GitHooksIO/githook-super-protected-branches) when ' + data.payload.head_commit.author.username + ' tried to push directly to ' + branchToProtect + '.',
                                        head:  newBranchName,
                                        base:  branchToProtect
                                    };
                                    request.post(options, function pullRequestOpened(err, httpResponse, body) {
                                        checkForFailures(err);

                                        process.succeed('Result*** body: ' + JSON.stringify(body) + ' \n options: ' + JSON.stringify(options.json));
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    }
}


text:
<?php

namespace JimmyOak\DataType;

abstract class SimpleValueObject
{
    /**
     * @var mixed
     */
    private $value;

    /**
     * SimpleValueObject constructor.
     *
     * @param mixed $value
     */
    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * @return int|null|string
     */
    public function value()
    {
        return $this->value;
    }

    public function __toString()
    {
        return (string) $this->value();
    }

    public function equals(SimpleValueObject $object)
    {
        return $this->value() === $object->value();
    }

    protected function duplicateWith($newValue)
    {
        return new static($newValue);
    }
}


text:
class Elastic {
public:

	static float EaseIn( float t, float b, float c, float d );
	static float EaseOut( float t, float b, float c, float d );
	static float EaseInOut( float t, float b, float c, float d );
};