text:
package org.springframework.orm.jpa.vendor;

import java.sql.Connection;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import org.apache.commons.logging.LogFactory;
import org.apache.openjpa.persistence.FetchPlan;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAPersistence;
import org.apache.openjpa.persistence.jdbc.IsolationLevel;
import org.apache.openjpa.persistence.jdbc.JDBCFetchPlan;

import org.springframework.jdbc.datasource.ConnectionHandle;
import org.springframework.jdbc.datasource.ConnectionHolder;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.orm.jpa.DefaultJpaDialect;
import org.springframework.transaction.SavepointManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;

/**
 * {@link org.springframework.orm.jpa.JpaDialect} implementation for Apache OpenJPA.
 * Developed and tested against OpenJPA 2.2.
 *
 * @author Juergen Hoeller
 * @author Costin Leau
 * @since 2.0
 */
@SuppressWarnings("serial")
public class OpenJpaDialect extends DefaultJpaDialect {

	@Override
	public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
			throws PersistenceException, SQLException, TransactionException {

		OpenJPAEntityManager openJpaEntityManager = getOpenJPAEntityManager(entityManager);

		if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
			// Pass custom isolation level on to OpenJPA's JDBCFetchPlan configuration
			FetchPlan fetchPlan = openJpaEntityManager.getFetchPlan();
			if (fetchPlan instanceof JDBCFetchPlan) {
				IsolationLevel isolation = IsolationLevel.fromConnectionConstant(definition.getIsolationLevel());
				((JDBCFetchPlan) fetchPlan).setIsolation(isolation);
			}
		}

		entityManager.getTransaction().begin();

		if (!definition.isReadOnly()) {
			// Like with EclipseLink, make sure to start the logic transaction early so that other
			// participants using the connection (such as JdbcTemplate) run in a transaction.
			openJpaEntityManager.beginStore();
		}

		// Custom implementation for OpenJPA savepoint handling
		return new OpenJpaTransactionData(openJpaEntityManager);
	}

	@Override
	public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly)
			throws PersistenceException, SQLException {

		return new OpenJpaConnectionHandle(getOpenJPAEntityManager(entityManager));
	}

	/**
	 * Return the OpenJPA-specific variant of {@code EntityManager}.
	 * @param em the generic {@code EntityManager} instance
	 * @return the OpenJPA-specific variant of {@code EntityManager}
	 */
	protected OpenJPAEntityManager getOpenJPAEntityManager(EntityManager em) {
		return OpenJPAPersistence.cast(em);
	}

	/**
	 * Transaction data Object exposed from {@code beginTransaction},
	 * implementing the {@link SavepointManager} interface.
	 */
	private static class OpenJpaTransactionData implements SavepointManager {

		private final OpenJPAEntityManager entityManager;

		private int savepointCounter = 0;

		public OpenJpaTransactionData(OpenJPAEntityManager entityManager) {
			this.entityManager = entityManager;
		}

		@Override
		public Object createSavepoint() throws TransactionException {
			this.savepointCounter++;
			String savepointName = ConnectionHolder.SAVEPOINT_NAME_PREFIX + this.savepointCounter;
			this.entityManager.setSavepoint(savepointName);
			return savepointName;
		}

		@Override
		public void rollbackToSavepoint(Object savepoint) throws TransactionException {
			this.entityManager.rollbackToSavepoint((String) savepoint);
		}

		@Override
		public void releaseSavepoint(Object savepoint) throws TransactionException {
			try {
				this.entityManager.releaseSavepoint((String) savepoint);
			}
			catch (Throwable ex) {
				LogFactory.getLog(OpenJpaTransactionData.class).debug(
						"Could not explicitly release OpenJPA savepoint", ex);
			}
		}
	}

	/**
	 * {@link ConnectionHandle} implementation that fetches a new OpenJPA-provided
	 * Connection for every {@code getConnection} call and closes the Connection on
	 * {@code releaseConnection}. This is necessary because OpenJPA requires the
	 * fetched Connection to be closed before continuing EntityManager work.
	 * @see org.apache.openjpa.persistence.OpenJPAEntityManager#getConnection()
	 */
	private static class OpenJpaConnectionHandle implements ConnectionHandle {

		private final OpenJPAEntityManager entityManager;

		public OpenJpaConnectionHandle(OpenJPAEntityManager entityManager) {
			this.entityManager = entityManager;
		}

		@Override
		public Connection getConnection() {
			return (Connection) this.entityManager.getConnection();
		}

		@Override
		public void releaseConnection(Connection con) {
			JdbcUtils.closeConnection(con);
		}
	}

}

redpajama_set_name: RedPajamaGithub


text: package ginkgo


text:
/*jslint node: true */
'use strict';

var textHelper = {
    failedResponse: 'I\'m sorry. There was a problem processing this request. The Alexa card may have more details. Goodbye.',
    onLaunchPrompt: 'Welcome to Code Camp Tweets. You can ask for recent tweets or who has tweeted.',
    help: 'You can ask for an update, a number of recent tweets, or who has tweeted recently.',
    helpAfterPause: 'You can ask for an update or ask who has tweeted.',
    goodbye: 'Thank you for interacting with me. Goodbye.',

    noMatchingTweets: 'There were no matching tweets.',
    noRecentTweets: 'There were no recent tweets.',

    lastTweets: function (n) {
        return `The last ${n} tweet` + (n === 1
            ? ' was: '
            : 's were: ');
    },

    /**
     * Recursively attempt to build an Alexa "sayable" string that represents the supplied exception object.
     * @param exc
     * @returns {string}
     */
    exceptionMsg: function (exc) {
        var thisForScopeIssueInJSLint = this;
        return exc.message || (Array.isArray(exc)
            ? exc.map(function (e) {
                return thisForScopeIssueInJSLint.exceptionMsg(e);
            }).join("\n")
            : exc);
    },

    /**
     * Combine list of users into Alexa "sayable" string.
     * @param users       List of twitter users
     * @returns {String}
     */
    recentTweetsFrom: function (users) {
        var msg;
        if (users.length === 0) {                 // could not find any tweets recently
            msg = this.noRecentTweets;
        } else {
            msg = 'Recent tweets were from: ';
            if (users.length === 1) {
                msg += users[0];
            } else {
                msg += users.slice(0, -1).join(', ') + ', and ' + users.slice(-1);
            }
            msg += '.';
        }
        return msg;
    }

};

module.change_code = 1;
module.exports = textHelper;


text:
'use strict';

angular.module('admin').config(['$stateProvider',function($stateProvider) {

  $stateProvider.
    state('allUsers', {
      url: '/admin/users',
      templateUrl: 'modules/admin/views/users.admin.client.view.html'
    });
}]);


text:
class PatternGenerator
  include PatternConstantsHelper
  include PatternViewHelper
  include MathConversionsHelper

  attr_reader :row_1, :per_1, :title, :user_id

  def initialize(user_input)
    @title = user_input[:name]
    @user_id = user_input[:user_id]
    @needle = Needle.find(user_input[:needle_id])
    @row_1 = user_input[:gauge_row_inch]
    @per_1 = user_input[:gauge_per_inch]
    @yarn_weight = YarnWeight.find(user_input[:yarn_weight_id])
    @hat_circumference = user_input[:hat_circumference]
  end

  def needle
    @needle.size
  end

  def smaller_needle
    if @needle.id-1 == 0
      @needle.size
    else
      Needle.find(@needle.id-1).size
    end
  end

  def estimated_yardage
    round_0(@yarn_weight.yardage_factor.to_f * @square_inches * 1.1)
  end

  def per_4
    round_2(@per_1 * 4)
  end

  def row_4
    round_2(@row_1 * 4)
  end

  def yarn_weight
    @yarn_weight.weight
  end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.maps.weather.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;

/** The QuarterDayForecast model. */
@Fluent
public final class QuarterDayForecast {
    /*
     * Date of the forecast as example, 2019-10-27T00:00:00
     */
    @JsonProperty(value = "date")
    private OffsetDateTime dateTime;

    /*
     * Date and time of the beginning of the forecast quarter displayed in ISO 8601 format, for example,
     * 2019-10-27T19:39:57-08:00.
     */
    @JsonProperty(value = "effectiveDate")
    private OffsetDateTime effectiveDate;

    /*
     * Quarter of the day.
     */
    @JsonProperty(value = "quarter")
    private DayQuarter quarter;

    /*
     * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather Service
     * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details.
     */
    @JsonProperty(value = "iconCode")
    private IconCode iconCode;

    /*
     * Phrase description of the icon. Displayed in specified language. For example, 'Sunny'.
     */
    @JsonProperty(value = "iconPhrase")
    private String iconPhrase;

    /*
     * Short summary phrase summary for quarter.
     */
    @JsonProperty(value = "phrase")
    private String phrase;

    /*
     * Temperature values for the quarter.
     */
    @JsonProperty(value = "temperature")
    private WeatherValueRange temperature;

    /*
     * RealFeel™ Temperature values for the quarter.
     */
    @JsonProperty(value = "realFeelTemperature")
    private WeatherValueRange realFeelTemperature;

    /*
     * The dewpoint temperature in specified unit. The dewpoint temperature is the temperature that the air must be
     * cooled to in order to reach saturation.
     */
    @JsonProperty(value = "dewPoint")
    private WeatherUnitDetails dewPoint;

    /*
     * Relative humidity is the amount of water vapor present in air expressed as a percentage of the amount needed for
     * saturation at the same temperature.
     */
    @JsonProperty(value = "relativeHumidity")
    private Integer relativeHumidity;

    /*
     * Wind details being returned including speed and direction.
     */
    @JsonProperty(value = "wind")
    private WindDetails wind;

    /*
     * Wind gust. Wind gust is a sudden, brief increase in speed of the wind.
     */
    @JsonProperty(value = "windGust")
    private WindDetails windGust;

    /*
     * Visibility in specified unit. A measure of the distance at which an object or light can be clearly discerned.
     */
    @JsonProperty(value = "visibility")
    private WeatherUnitDetails visibility;

    /*
     * Percent representing cloud cover.
     */
    @JsonProperty(value = "cloudCover")
    private Integer cloudCover;

    /*
     * Indicates the presence or absence of precipitation. True indicates the presence of precipitation, false
     * indicates the absence of precipitation.
     */
    @JsonProperty(value = "hasPrecipitation")
    private Boolean hasPrecipitation;

    /*
     * Specifies the type of precipitation ("Rain" "Snow" "Ice" or "Mix"). If dbz is zero, precipitationType is not
     * present in the response.
     */
    @JsonProperty(value = "precipitationType")
    private PrecipitationType precipitationType;

    /*
     * Description of the intensity.
     */
    @JsonProperty(value = "precipitationIntensity")
    private String precipitationIntensity;

    /*
     * Percent representing the probability of precipitation. For example, '20'.
     */
    @JsonProperty(value = "precipitationProbability")
    private Integer precipitationProbability;

    /*
     * Percent representing the probability of a thunderstorm. For example, '10'.
     */
    @JsonProperty(value = "thunderstormProbability")
    private Integer thunderstormProbability;

    /*
     * Total liquid equivalent of precipitation during the forecast period.
     */
    @JsonProperty(value = "totalLiquid")
    private WeatherUnitDetails totalLiquid;

    /*
     * Rain
     */
    @JsonProperty(value = "rain")
    private WeatherUnitDetails rain;

    /*
     * Snow
     */
    @JsonProperty(value = "snow")
    private WeatherUnitDetails snow;

    /*
     * Ice
     */
    @JsonProperty(value = "ice")
    private WeatherUnitDetails ice;

    /** Set default QuarterDayForecast constructor to private */
    private QuarterDayForecast() {}

    /**
     * Get the dateTime property: Date of the forecast as example, 2019-10-27T00:00:00.
     *
     * @return the dateTime value.
     */
    public OffsetDateTime getDateTime() {
        return this.dateTime;
    }

    /**
     * Get the effectiveDate property: Date and time of the beginning of the forecast quarter displayed in ISO 8601
     * format, for example, 2019-10-27T19:39:57-08:00.
     *
     * @return the effectiveDate value.
     */
    public OffsetDateTime getEffectiveDate() {
        return this.effectiveDate;
    }

    /**
     * Get the quarter property: Quarter of the day.
     *
     * @return the quarter value.
     */
    public DayQuarter getQuarter() {
        return this.quarter;
    }

    /**
     * Get the iconCode property: Numeric value representing an image that displays the `iconPhrase`. Please refer to
     * [Weather Service Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details.
     *
     * @return the iconCode value.
     */
    public IconCode getIconCode() {
        return this.iconCode;
    }

    /**
     * Get the iconPhrase property: Phrase description of the icon. Displayed in specified language. For example,
     * 'Sunny'.
     *
     * @return the iconPhrase value.
     */
    public String getIconPhrase() {
        return this.iconPhrase;
    }

    /**
     * Get the phrase property: Short summary phrase summary for quarter.
     *
     * @return the phrase value.
     */
    public String getPhrase() {
        return this.phrase;
    }

    /**
     * Get the temperature property: Temperature values for the quarter.
     *
     * @return the temperature value.
     */
    public WeatherValueRange getTemperature() {
        return this.temperature;
    }

    /**
     * Get the realFeelTemperature property: RealFeel™ Temperature values for the quarter.
     *
     * @return the realFeelTemperature value.
     */
    public WeatherValueRange getRealFeelTemperature() {
        return this.realFeelTemperature;
    }

    /**
     * Get the dewPoint property: The dewpoint temperature in specified unit. The dewpoint temperature is the
     * temperature that the air must be cooled to in order to reach saturation.
     *
     * @return the dewPoint value.
     */
    public WeatherUnitDetails getDewPoint() {
        return this.dewPoint;
    }

    /**
     * Get the relativeHumidity property: Relative humidity is the amount of water vapor present in air expressed as a
     * percentage of the amount needed for saturation at the same temperature.
     *
     * @return the relativeHumidity value.
     */
    public Integer getRelativeHumidity() {
        return this.relativeHumidity;
    }

    /**
     * Get the wind property: Wind details being returned including speed and direction.
     *
     * @return the wind value.
     */
    public WindDetails getWind() {
        return this.wind;
    }

    /**
     * Get the windGust property: Wind gust. Wind gust is a sudden, brief increase in speed of the wind.
     *
     * @return the windGust value.
     */
    public WindDetails getWindGust() {
        return this.windGust;
    }

    /**
     * Get the visibility property: Visibility in specified unit. A measure of the distance at which an object or light
     * can be clearly discerned.
     *
     * @return the visibility value.
     */
    public WeatherUnitDetails getVisibility() {
        return this.visibility;
    }

    /**
     * Get the cloudCover property: Percent representing cloud cover.
     *
     * @return the cloudCover value.
     */
    public Integer getCloudCover() {
        return this.cloudCover;
    }

    /**
     * Get the hasPrecipitation property: Indicates the presence or absence of precipitation. True indicates the
     * presence of precipitation, false indicates the absence of precipitation.
     *
     * @return the hasPrecipitation value.
     */
    public Boolean isHasPrecipitation() {
        return this.hasPrecipitation;
    }

    /**
     * Get the precipitationType property: Specifies the type of precipitation ("Rain" "Snow" "Ice" or "Mix"). If dbz is
     * zero, precipitationType is not present in the response.
     *
     * @return the precipitationType value.
     */
    public PrecipitationType getPrecipitationType() {
        return this.precipitationType;
    }

    /**
     * Get the precipitationIntensity property: Description of the intensity.
     *
     * @return the precipitationIntensity value.
     */
    public String getPrecipitationIntensity() {
        return this.precipitationIntensity;
    }

    /**
     * Get the precipitationProbability property: Percent representing the probability of precipitation. For example,
     * '20'.
     *
     * @return the precipitationProbability value.
     */
    public Integer getPrecipitationProbability() {
        return this.precipitationProbability;
    }

    /**
     * Get the thunderstormProbability property: Percent representing the probability of a thunderstorm. For example,
     * '10'.
     *
     * @return the thunderstormProbability value.
     */
    public Integer getThunderstormProbability() {
        return this.thunderstormProbability;
    }

    /**
     * Get the totalLiquid property: Total liquid equivalent of precipitation during the forecast period.
     *
     * @return the totalLiquid value.
     */
    public WeatherUnitDetails getTotalLiquid() {
        return this.totalLiquid;
    }

    /**
     * Get the rain property: Rain.
     *
     * @return the rain value.
     */
    public WeatherUnitDetails getRain() {
        return this.rain;
    }

    /**
     * Get the snow property: Snow.
     *
     * @return the snow value.
     */
    public WeatherUnitDetails getSnow() {
        return this.snow;
    }

    /**
     * Get the ice property: Ice.
     *
     * @return the ice value.
     */
    public WeatherUnitDetails getIce() {
        return this.ice;
    }
}


text:
package org.ensime

package object pcplod {

  def withPcPlod[T](pluginJar: String)(f: PcPlod => T): T = {
    f(PcPlod(Some(pluginJar)))
  }

  def withPcPlod[T](f: PcPlod => T): T = {
    f(PcPlod())
  }

  def withMrPlod[T](res: String)(f: MrPlod => T): T = {
    f(MrPlod(res))
  }

  implicit def posToPoint(pos: Int): Point = PositionPoint(pos)
  implicit def lineColToPoint(lc: (Int, Int)): Point = LineColumnPoint(lc._1, lc._2)
  implicit def noddyPoint(name: Symbol): Point = NoddyPoint(name)

}


text:
package org.apache.parquet.column.values;

import java.io.IOException;
import java.util.Random;

import org.apache.parquet.io.api.Binary;

/**
 * Test Utility class
 *
 * @author Aniket Mokashi
 *
 */
public class Utils {
  private static Random randomLen = new Random();
  private static RandomStr randomStr = new RandomStr(randomLen);

  public static String[] getRandomStringSamples(int numSamples, int maxLength) {
    String[] samples = new String[numSamples];

    for (int i=0; i < numSamples; i++) {
      int len = randomLen.nextInt(maxLength);
      samples[i] = randomStr.get(len);
    }

    return samples;
  }

  public static void writeInts(ValuesWriter writer, int[] ints)
      throws IOException {
    for(int i=0; i < ints.length; i++) {
      writer.writeInteger(ints[i]);
    }
  }

  public static void writeData(ValuesWriter writer, String[] strings)
      throws IOException {
    for(int i=0; i < strings.length; i++) {
      writer.writeBytes(Binary.fromString(strings[i]));
    }
  }

  public static Binary[] readData(ValuesReader reader, byte[] data, int offset, int length)
      throws IOException {
    Binary[] bins = new Binary[length];
    reader.initFromPage(length, data, 0);
    for(int i=0; i < length; i++) {
      bins[i] = reader.readBytes();
    }
    return bins;
  }

  public static Binary[] readData(ValuesReader reader, byte[] data, int length)
      throws IOException {
    return readData(reader, data, 0, length);
  }

  public static int[] readInts(ValuesReader reader, byte[] data, int offset, int length)
      throws IOException {
    int[] ints = new int[length];
    reader.initFromPage(length, data, offset);
    for(int i=0; i < length; i++) {
      ints[i] = reader.readInteger();
    }
    return ints;
  }

  public static int[] readInts(ValuesReader reader, byte[] data, int length)
      throws IOException {
    return readInts(reader, data, 0, length);
  }
}


text:
body {
    background-color: aliceblue;
}

.item {
    border: 1px solid green;
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE cmdline
  PUBLIC "-//THECOMPANY//DTD DISCOVER 7.3.x//EN"
  "cmdline.dtd">
<cmdline nameintro="-" unrecognized="no_message">
<compilername>HP C/ANSI C</compilername>
reconfigure hpansic                                <!-- default to ANSI C -->
<translate>
  <option   name="Ac" noarg="1">hpcc</option>      <!-- specify Classic C -->
  <option   name="Aa" noarg="1">hpansic</option>   <!-- specify ANSI C -->
  <option   name="Ae" noarg="1">hpansic</option>   <!-- specify ANSI C -->
</translate>
</cmdline>


text:
// Copyright 2006 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Unit tests for the {@link MakeVariableExpander}, which expands variable references of the form
 * "$x" and "$(foo)" into their corresponding values.
 */
@RunWith(JUnit4.class)
public class MakeVariableExpanderTest {

  private MakeVariableExpander.Context context;

  private Map<String, String> vars = new HashMap<>();

  @Before
  public final void createContext() throws Exception  {
    context = new MakeVariableExpander.Context() {
        @Override
        public String lookupMakeVariable(String name)
            throws MakeVariableExpander.ExpansionException {
          // Not a Make variable. Let the shell handle the expansion.
          if (name.startsWith("$")) {
            return name;
          }
          if (!vars.containsKey(name)) {
            throw new MakeVariableExpander.ExpansionException("$(" + name + ") not defined");
          }
          return vars.get(name);
        }
      };

    vars.put("SRCS", "src1 src2");
  }

  private void assertExpansionEquals(String expected, String cmd)
      throws MakeVariableExpander.ExpansionException {
    assertThat(MakeVariableExpander.expand(cmd, context)).isEqualTo(expected);
  }

  private void assertExpansionFails(String expectedErrorSuffix, String cmd) {
    try {
      MakeVariableExpander.expand(cmd, context);
      fail("Expansion of " + cmd + " didn't fail as expected");
    } catch (Exception e) {
      assertThat(e).hasMessage(expectedErrorSuffix);
    }
  }

  @Test
  public void testExpansion() throws Exception {
    vars.put("<", "src1");
    vars.put("OUTS", "out1 out2");
    vars.put("@", "out1");
    vars.put("^", "src1 src2 dep1 dep2");
    vars.put("@D", "outdir");
    vars.put("BINDIR", "bindir");

    assertExpansionEquals("src1 src2", "$(SRCS)");
    assertExpansionEquals("src1", "$<");
    assertExpansionEquals("out1 out2", "$(OUTS)");
    assertExpansionEquals("out1", "$(@)");
    assertExpansionEquals("out1", "$@");
    assertExpansionEquals("out1,", "$@,");

    assertExpansionEquals("src1 src2 out1 out2", "$(SRCS) $(OUTS)");

    assertExpansionEquals("cmd", "cmd");
    assertExpansionEquals("cmd src1 src2,", "cmd $(SRCS),");
    assertExpansionEquals("label1 src1 src2,", "label1 $(SRCS),");
    assertExpansionEquals(":label1 src1 src2,", ":label1 $(SRCS),");

    // Note: $(location x) is considered an undefined variable;
    assertExpansionFails("$(location label1) not defined",
                         "$(location label1), $(SRCS),");
  }

  @Test
  public void testRecursiveExpansion() throws Exception {
    // Expansion is recursive: $(recursive) -> $(SRCS) -> "src1 src2"
    vars.put("recursive", "$(SRCS)");
    assertExpansionEquals("src1 src2", "$(recursive)");

    // Recursion does not span expansion boundaries:
    // $(recur2a)$(recur2b) --> "$" + "(SRCS)"  --/--> "src1 src2"
    vars.put("recur2a", "$$");
    vars.put("recur2b", "(SRCS)");
    assertExpansionEquals("$(SRCS)", "$(recur2a)$(recur2b)");
  }

  @Test
  public void testInfiniteRecursionFailsGracefully() throws Exception {
    vars.put("infinite", "$(infinite)");
    assertExpansionFails("potentially unbounded recursion during expansion "
                         + "of '$(infinite)'",
                         "$(infinite)");

    vars.put("black", "$(white)");
    vars.put("white", "$(black)");
    assertExpansionFails("potentially unbounded recursion during expansion "
                         + "of '$(black)'",
                         "$(white) is the new $(black)");
  }

  @Test
  public void testErrors() throws Exception {
    assertExpansionFails("unterminated variable reference", "$(SRCS");
    assertExpansionFails("unterminated $", "$");

    String suffix = "instead for \"Make\" variables, or escape the '$' as '$$' if you intended "
        + "this for the shell";
    assertExpansionFails("'$file' syntax is not supported; use '$(file)' " + suffix,
                         "for file in a b c;do echo $file;done");
    assertExpansionFails("'${file%:.*8}' syntax is not supported; use '$(file%:.*8)' " + suffix,
                         "${file%:.*8}");
  }

  @Test
  public void testShellVariables() throws Exception {
    assertExpansionEquals("for file in a b c;do echo $file;done",
        "for file in a b c;do echo $$file;done");
    assertExpansionEquals("${file%:.*8}", "$${file%:.*8}");
    assertExpansionFails("$(basename file) not defined", "$(basename file)");
    assertExpansionEquals("$(basename file)", "$$(basename file)");
  }
}


text:
#ifndef __TIMER_H__
#define __TIMER_H__

namespace openxc {
namespace util {
namespace time {

typedef unsigned long (*TimeFunction)();

/* Public: A frequency counting clock.
 *
 * frequency - the clock freuquency in Hz.
 * lastTime - the last time (in milliseconds since startup) that the clock
 *      ticked.
 */
typedef struct {
    float frequency;
    unsigned long lastTick;
    TimeFunction timeFunction;
} FrequencyClock;

/* Public: Initialize a FrequencyClock structure back to a fresh start - never
 * ticked, default time function, no set frequency.
 *
 * clock - The clock to initialize.
 */
void initializeClock(FrequencyClock* clock);

/* Public: Determine if the clock should tick, according to its frequency and
 * last tick time, and tick it if it needs it!
 *
 * If the frequency is 0 or the clock is NULL, will return true. The first call
 * to this function always returns true if staggered start is disabled.
 *
 * stagger - If true, adds a random offset to the starting time (between 0 and 1
 *      full period), which is useful if you are initializing multiple clocks
 *      and you want to stagger their ticks. This only applies to the first tick
 *      of the clock.
 *
 * Return true if the clock should tick.
 */
bool conditionalTick(FrequencyClock* clock, bool stagger);

/* Public:  The same as conditionalTick(FrequencyClock, bool), but staggered start is
 *      off.
 */
bool conditionalTick(FrequencyClock* clock);

/* Public: Determine if the clock's tick timer has elapsed and it should tick.
 * Does *not* actually tick the clock.
 *
 * stagger - If true, will set the clock back a random amount if it hasn't
 *      started, so it doesn't start right away with the first call to
 *      conditionalTick(...). Still, it doesn't actually tick it.
 */
bool elapsed(FrequencyClock* clock, bool stagger);

/* Public: Force the clock to tick, regardless of it its time has actually
 * elapsed.
 */
void tick(FrequencyClock* clock);

/* Public: Delay execution by the given number of milliseconds.
 */
void delayMs(unsigned long delayInMs);

/* Public: Return the current system time in milliseconds.
 */
unsigned long systemTimeMs();

/* Public: Perform any one-time initialization required to use system times,
 * including those for system time and the delayMs function.
 */
void initialize();

/* Public: Return the system time in milliseconds when the code started to run.
 */
unsigned long startupTimeMs();

/* Public: Return the uptime of the code in milliseconds. */
unsigned long uptimeMs();

} // namespace time
} // namespace util
} // namespace openxc

#endif // __TIMER__H__


text:
from mercurio import engine

if __name__ == "__main__":
    engine.listen()
    print "Done..."


text:
define([
    'jquery',
	'underscore',
 	'backbone',
    'collections/users',
 	'text!templates/user-list-template.html'
], function ($, _, Backbone, Users, UserListTemplate) {
    var UserList = Backbone.View.extend({
        el: '.page',
        render: function () {
            var users = new Users();
            var that = this;
            users.fetch({
                success: function (users) {
                    console.log(users);
                    var compile = _.template(UserListTemplate, { users: users.models });
                    that.$el.html(compile);
                }
            });
        }
    });

    return UserList;
});


text:
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;

namespace MJennings.Extensions
{
    public static class ReflectionExtensions
    {
        public static bool IsNullableType(this Type source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            return source.IsGenericType && source.GetGenericTypeDefinition() == typeof(Nullable<>);
        }

        public static SqlDbType ToSqlDbType(this Type source)
        {
            if (source.IsNullableType())
            {
                var underlyingType = Nullable.GetUnderlyingType(source);
                return underlyingType.ToSqlDbType();
            }

            // Bit
            if (source.Equals(typeof(bool)))
            {
                return SqlDbType.Bit;
            }

            // TinyInt
            else if (source.Equals(typeof(byte)))
            {
                return SqlDbType.TinyInt;
            }

            // SmallInt
            else if (source.Equals(typeof(short)))
            {
                return SqlDbType.SmallInt;
            }

            // Int
            else if (source.Equals(typeof(int)))
            {
                return SqlDbType.Int;
            }

            // BigInt
            else if (source.Equals(typeof(long)))
            {
                return SqlDbType.BigInt;
            }

            // Binary
            // VarBinary
            // Image
            else if (source.Equals(typeof(byte[])))
            {
                return SqlDbType.VarBinary;
            }

            // Char
            else if (source.Equals(typeof(char)))
            {
                return SqlDbType.Char;
            }

            // Date
            // DateTime
            // DateTime2
            // SmallDateTime
            else if (source.Equals(typeof(DateTime)))
            {
                return SqlDbType.DateTime;
            }

            // DateTimeOffset
            else if (source.Equals(typeof(DateTimeOffset)))
            {
                return SqlDbType.DateTimeOffset;
            }

            // Time
            else if (source.Equals(typeof(TimeSpan)))
            {
                return SqlDbType.Time;
            }

            // Decimal
            // SmallMoney
            // Money
            else if (source.Equals(typeof(decimal)))
            {
                return SqlDbType.Decimal;
            }

            // Real
            else if (source.Equals(typeof(float)))
            {
                return SqlDbType.Real;
            }

            // Float
            else if (source.Equals(typeof(double)))
            {
                return SqlDbType.Float;
            }

            // NChar
            // NText
            // NVarChar
            // Text
            // VarChar
            // Xml
            else if (source.Equals(typeof(string)))
            {
                return SqlDbType.NVarChar;
            }

            // UniqueIdentifier
            else if (source.Equals(typeof(Guid)))
            {
                return SqlDbType.UniqueIdentifier;
            }

            // Structured
            else if (source.IsIn(typeof(DataTable), typeof(DbDataReader), typeof(IEnumerable<SqlDataRecord>)))
            {
                return SqlDbType.Structured;
            }

            // Variant
            else
            {
                return SqlDbType.Variant;
            }

            // Udt
            // Timestamp
        }
    }
}


text:
require 'spec_helper'

module Ab
  describe NullTest do
    subject { NullTest.new }

    its(:variant) { should be_nil }
    its(:start_at) { should_not be_nil }
    its(:end_at) { should_not be_nil }

    context 'with method ending in question mark' do
      before { Ab.config.logger.should_not_receive(:debug) }

      specify 'does not raise' do
        -> { subject.bla? }.should_not raise_error
      end
    end

    specify 'raises for method not ending in question mark' do
      -> { subject.bla }.should raise_error
    end
  end
end


text:
package io.netty.handler.codec;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;

import java.util.List;

public class MessageToMessageEncoderTest {

    /**
     * Test-case for https://github.com/netty/netty/issues/1656
     */
    @Test(expected = EncoderException.class)
    public void testException() {
        EmbeddedChannel channel = new EmbeddedChannel(new MessageToMessageEncoder<Object>() {
            @Override
            protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
                throw new Exception();
            }
        });
        channel.writeOutbound(new Object());
    }
}


text:
package com.google.zxing.oned;

import com.google.zxing.MultiFormatReader;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.AbstractBlackBoxTestCase;

import java.io.File;

/**
 * @author dswitkin@google.com (Daniel Switkin)
 */
public final class UPCABlackBox4TestCase extends AbstractBlackBoxTestCase {

  public UPCABlackBox4TestCase() {
    super(new File("test/data/blackbox/upca-4"), new MultiFormatReader(), BarcodeFormat.UPC_A);
    addTest(8, 13, 0.0f);
    addTest(8, 12, 180.0f);
  }

}


text:
layout: post
title: "Writefull Thesaurus"
posturl: https://chrome.google.com/webstore/detail/writefull-thesaurus/gjaljmejoplhicfhppcfcgjojehddfcc?hl=en
tags:
- Product
- Assistant
---

{% include post_info_header.md %}

This is how I imagine a great product built with AI tech: it just makes me overall more awesome. This one helps me to write better - and not being arrogantly pushy while doing it.

<!--more-->
{% include post_info_footer.md %}


text:
.. _examples:

========
Examples
========

All theory is grey. In this section, we present various practical examples that
demonstrate how to uses SimPy's features.

Here's a list of examples grouped by features they demonstrate.

Condition events
================

- :doc:`bank_renege`
- :doc:`movie_renege`

Interrupts
==========

- :doc:`machine_shop`

Monitoring
==========

Resources: Container
====================

- :doc:`gas_station_refuel`

Resources: Preemptive Resource
==============================

- :doc:`machine_shop`

Resources: Resource
===================

- :doc:`bank_renege`
- :doc:`carwash`
- :doc:`gas_station_refuel`
- :doc:`movie_renege`

Resources: Store
================

- :doc:`latency`
- :doc:`process_communication`

Shared events
=============

- :doc:`movie_renege`

Waiting for other processes
===========================

- :doc:`carwash`
- :doc:`gas_station_refuel`

All examples
============

.. toctree::

   bank_renege
   carwash
   machine_shop
   movie_renege
   gas_station_refuel
   process_communication
   latency

You have ideas for better examples? Please send them to our `mainling list
<https://lists.sourceforge.net/lists/listinfo/simpy-users>`_ or make a pull
request on `bitbucket <https://bitbucket.org/simpy/simpy>`_.


text:
package com.zuitangxuan.database.T003mybusinesspartner;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface HandleTypeT003 {
	public static final String O301 = "O301"; //增加资金账户
	public static final String O302 = "O302"; //删除资金账户
	public static final String O303 = "O303"; //修改资金账户
	public static final String O304 = "O304"; //查询资金账户
	public static final String O305 = "O305"; //创建数据表
	public static final String O306 = "O306"; //删除数据表

	/**增加资金账户*/
	public void orderO301(HttpServletRequest request, HttpServletResponse response) throws Exception;
	/**删除资金账户*/
	public void orderO302(HttpServletRequest request, HttpServletResponse response) throws Exception;
	/**修改资金账户*/
	public void orderO303(HttpServletRequest request, HttpServletResponse response) throws Exception;
	/**查询资金账户*/
	public void orderO304(HttpServletRequest request, HttpServletResponse response) throws Exception;
	/**创建数据表*/
	public void orderO305(HttpServletRequest request, HttpServletResponse response) throws Exception;
	/**删除数据表*/
	public void orderO306(HttpServletRequest request, HttpServletResponse response) throws Exception;

}


text:
a simple TagView for Swift, support single select and multiple select.

![Platform](http://img.shields.io/badge/platform-iOS-blue.svg?style=flat
)
![Language](http://img.shields.io/badge/language-swift-brightred.svg?style=flat
)
[![License](http://img.shields.io/badge/license-MIT-lightgrey.svg?style=flat
)](http://mit-license.org)

### Single Select (單選) & Border Type

### Multiple Select (多選) & Fill Type

## Usage
### 1.Drag the 'SMTagView.swift' to your project.
### 2.Create a UIView on storyboard or xib.
### 3.Setting the class of UIView for 'SMTagView'

### 4.Setting TagView:
#### Single Select
you will get the callback when user selected.

```swift
self.m_tagViewSingle.layer.cornerRadius = 15.0
self.m_tagViewSingle.tagMainColor = UIColor.orange
self.m_tagViewSingle.setTagForSingle(title: "你要選哪個呢 ? (單選)", tagType: .border, tags: tags)  { (index) in
    print(index)
}
```

#### Multiple Select
you can setting maximum select and minimum select,or just put the "nil" if you don't want set any condition,and you will get the callback when user click the "Done" button.

```swift
self.m_tagViewMultiple.layer.cornerRadius = 15.0
self.m_tagViewMultiple.tagMainColor = UIColor.orange
self.m_tagViewMultiple.setTagForMultiple(title: "選幾個喜歡的吧!(多選)", tagType: .fill, tags: tags, maximumSelect: 3, minimumSelect: 2) { (indexes) in
            print("done:\(indexes)")
}
```

## Custom Setting
you can get the other style from these setting.

```swift
var titleColor : UIColor = UIColor.darkGray
var titleFont : UIFont = UIFont.systemFont(ofSize: 20.0)

var tagTextColor : UIColor = UIColor.lightGray
var tagCornerRadius : CGFloat = 20.0
var tagMainColor : UIColor = UIColor.orange

var doneButtonTitleColor : UIColor = UIColor.white
var doneButtonBackgroundColor : UIColor = UIColor.orange
var doneButtonTitle : String = "Done"
var doneButtonCornerRadius : CGFloat = 8.0
```


text:
package org.apache.cassandra.metrics;

import java.io.IOException;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.datastax.driver.core.BatchStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Session;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.schema.Schema;
import org.apache.cassandra.service.EmbeddedCassandraService;

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

public class TableMetricsTest extends SchemaLoader
{
    private static Session session;

    private static final String KEYSPACE = "junit";
    private static final String TABLE = "tablemetricstest";
    private static final String COUNTER_TABLE = "tablemetricscountertest";

    @BeforeClass
    public static void setup() throws ConfigurationException, IOException
    {
        Schema.instance.clear();

        EmbeddedCassandraService cassandra = new EmbeddedCassandraService();
        cassandra.start();

        Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(DatabaseDescriptor.getNativeTransportPort()).build();
        session = cluster.connect();

        session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };", KEYSPACE));
        session.execute(String.format("CREATE TABLE IF NOT EXISTS %s.%s (id_c counter, id int, val text, PRIMARY KEY(id, val));", KEYSPACE, COUNTER_TABLE));
    }

    private ColumnFamilyStore recreateTable()
    {
        return recreateTable(TABLE);
    }

    private ColumnFamilyStore recreateTable(String table)
    {
        session.execute(String.format("DROP TABLE IF EXISTS %s.%s", KEYSPACE, table));
        session.execute(String.format("CREATE TABLE IF NOT EXISTS %s.%s (id int, val1 text, val2 text, PRIMARY KEY(id, val1));", KEYSPACE, table));
        return ColumnFamilyStore.getIfExists(KEYSPACE, table);
    }

    private void executeBatch(boolean isLogged, int distinctPartitions, int statementsPerPartition, String... tables)
    {
        if (tables == null || tables.length == 0)
        {
            tables = new String[] { TABLE };
        }
        BatchStatement.Type batchType;

        if (isLogged)
        {
            batchType = BatchStatement.Type.LOGGED;
        }
        else
        {
            batchType = BatchStatement.Type.UNLOGGED;
        }

        BatchStatement batch = new BatchStatement(batchType);

        for (String table : tables)
            populateBatch(batch, table, distinctPartitions, statementsPerPartition);

        session.execute(batch);
    }

    private static void populateBatch(BatchStatement batch, String table, int distinctPartitions, int statementsPerPartition)
    {
        PreparedStatement ps = session.prepare(String.format("INSERT INTO %s.%s (id, val1, val2) VALUES (?, ?, ?);", KEYSPACE, table));

        for (int i=0; i<distinctPartitions; i++)
        {
            for (int j=0; j<statementsPerPartition; j++)
            {
                batch.add(ps.bind(i, j + "a", "b"));
            }
        }
    }

    @Test
    public void testRegularStatementsExecuted()
    {
        ColumnFamilyStore cfs = recreateTable();
        assertEquals(0, cfs.metric.coordinatorWriteLatency.getCount());
        assertEquals(0.0, cfs.metric.coordinatorWriteLatency.getMeanRate(), 0.0);

        for (int i = 0; i < 10; i++)
        {
            session.execute(String.format("INSERT INTO %s.%s (id, val1, val2) VALUES (%d, '%s', '%s')", KEYSPACE, TABLE, i, "val" + i, "val" + i));
        }

        assertEquals(10, cfs.metric.coordinatorWriteLatency.getCount());
        assertGreaterThan(cfs.metric.coordinatorWriteLatency.getMeanRate(), 0);
    }

    @Test
    public void testPreparedStatementsExecuted()
    {
        ColumnFamilyStore cfs = recreateTable();
        PreparedStatement metricsStatement = session.prepare(String.format("INSERT INTO %s.%s (id, val1, val2) VALUES (?, ?, ?)", KEYSPACE, TABLE));

        assertEquals(0, cfs.metric.coordinatorWriteLatency.getCount());
        assertEquals(0.0, cfs.metric.coordinatorWriteLatency.getMeanRate(), 0.0);

        for (int i = 0; i < 10; i++)
        {
            session.execute(metricsStatement.bind(i, "val" + i, "val" + i));
        }

        assertEquals(10, cfs.metric.coordinatorWriteLatency.getCount());
        assertGreaterThan(cfs.metric.coordinatorWriteLatency.getMeanRate(), 0);
    }

    @Test
    public void testLoggedPartitionsPerBatch()
    {
        ColumnFamilyStore cfs = recreateTable();
        assertEquals(0, cfs.metric.coordinatorWriteLatency.getCount());
        assertEquals(0.0, cfs.metric.coordinatorWriteLatency.getMeanRate(), 0.0);

        executeBatch(true, 10, 2);
        assertEquals(1, cfs.metric.coordinatorWriteLatency.getCount());

        executeBatch(true, 20, 2);
        assertEquals(2, cfs.metric.coordinatorWriteLatency.getCount()); // 2 for previous batch and this batch
        assertGreaterThan(cfs.metric.coordinatorWriteLatency.getMeanRate(), 0);
    }

    @Test
    public void testLoggedPartitionsPerBatchMultiTable()
    {
        ColumnFamilyStore first = recreateTable();
        assertEquals(0, first.metric.coordinatorWriteLatency.getCount());
        assertEquals(0.0, first.metric.coordinatorWriteLatency.getMeanRate(), 0.0);

        ColumnFamilyStore second = recreateTable(TABLE + "_second");
        assertEquals(0, second.metric.coordinatorWriteLatency.getCount());
        assertEquals(0.0, second.metric.coordinatorWriteLatency.getMeanRate(), 0.0);

        executeBatch(true, 10, 2, TABLE, TABLE + "_second");
        assertEquals(1, first.metric.coordinatorWriteLatency.getCount());
        assertEquals(1, second.metric.coordinatorWriteLatency.getCount());

        executeBatch(true, 20, 2, TABLE, TABLE + "_second");
        assertEquals(2, first.metric.coordinatorWriteLatency.getCount()); // 2 for previous batch and this batch
        assertEquals(2, second.metric.coordinatorWriteLatency.getCount()); // 2 for previous batch and this batch
        assertGreaterThan(first.metric.coordinatorWriteLatency.getMeanRate(), 0);
        assertGreaterThan(second.metric.coordinatorWriteLatency.getMeanRate(), 0);
    }

    @Test
    public void testUnloggedPartitionsPerBatch()
    {
        ColumnFamilyStore cfs = recreateTable();
        assertEquals(0, cfs.metric.coordinatorWriteLatency.getCount());
        assertEquals(0.0, cfs.metric.coordinatorWriteLatency.getMeanRate(), 0.0);

        executeBatch(false, 5, 3);
        assertEquals(1, cfs.metric.coordinatorWriteLatency.getCount());

        executeBatch(false, 25, 2);
        assertEquals(2, cfs.metric.coordinatorWriteLatency.getCount()); // 2 for previous batch and this batch
        assertGreaterThan(cfs.metric.coordinatorWriteLatency.getMeanRate(), 0);
    }

    @Test
    public void testUnloggedPartitionsPerBatchMultiTable()
    {
        ColumnFamilyStore first = recreateTable();
        assertEquals(0, first.metric.coordinatorWriteLatency.getCount());
        assertEquals(0.0, first.metric.coordinatorWriteLatency.getMeanRate(), 0.0);

        ColumnFamilyStore second = recreateTable(TABLE + "_second");
        assertEquals(0, second.metric.coordinatorWriteLatency.getCount());
        assertEquals(0.0, second.metric.coordinatorWriteLatency.getMeanRate(), 0.0);

        executeBatch(false, 5, 3, TABLE, TABLE + "_second");
        assertEquals(1, first.metric.coordinatorWriteLatency.getCount());

        executeBatch(false, 25, 2, TABLE, TABLE + "_second");
        assertEquals(2, first.metric.coordinatorWriteLatency.getCount()); // 2 for previous batch and this batch
        assertEquals(2, second.metric.coordinatorWriteLatency.getCount()); // 2 for previous batch and this batch
        assertGreaterThan(first.metric.coordinatorWriteLatency.getMeanRate(), 0);
        assertGreaterThan(second.metric.coordinatorWriteLatency.getMeanRate(), 0);
    }

    @Test
    public void testCounterStatement()
    {
        ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(KEYSPACE, COUNTER_TABLE);
        assertEquals(0, cfs.metric.coordinatorWriteLatency.getCount());
        assertEquals(0.0, cfs.metric.coordinatorWriteLatency.getMeanRate(), 0.0);
        session.execute(String.format("UPDATE %s.%s SET id_c = id_c + 1 WHERE id = 1 AND val = 'val1'", KEYSPACE, COUNTER_TABLE));
        assertEquals(1, cfs.metric.coordinatorWriteLatency.getCount());
        assertGreaterThan(cfs.metric.coordinatorWriteLatency.getMeanRate(), 0);
    }

    private static void assertGreaterThan(double actual, double expectedLessThan) {
        assertTrue("Expected " + actual + " > " + expectedLessThan, actual > expectedLessThan);
    }

    @Test
    public void testMetricsCleanupOnDrop()
    {
        String tableName = TABLE + "_metrics_cleanup";
        CassandraMetricsRegistry registry = CassandraMetricsRegistry.Metrics;
        Supplier<Stream<String>> metrics = () -> registry.getNames().stream().filter(m -> m.contains(tableName));

        // no metrics before creating
        assertEquals(0, metrics.get().count());

        recreateTable(tableName);
        // some metrics
        assertTrue(metrics.get().count() > 0);

        session.execute(String.format("DROP TABLE IF EXISTS %s.%s", KEYSPACE, tableName));
        // no metrics after drop
        assertEquals(metrics.get().collect(Collectors.joining(",")), 0, metrics.get().count());
    }

    @Test
    public void testViewMetricsCleanupOnDrop()
    {
        String tableName = TABLE + "_2_metrics_cleanup";
        String viewName = TABLE + "_materialized_view_cleanup";
        CassandraMetricsRegistry registry = CassandraMetricsRegistry.Metrics;
        Supplier<Stream<String>> metrics = () -> registry.getNames().stream().filter(m -> m.contains(viewName));

        // no metrics before creating
        assertEquals(0, metrics.get().count());

        recreateTable(tableName);
        session.execute(String.format("CREATE MATERIALIZED VIEW %s.%s AS SELECT id,val1 FROM %s.%s WHERE id IS NOT NULL AND val1 IS NOT NULL PRIMARY KEY (id,val1);", KEYSPACE, viewName, KEYSPACE, tableName));
        // some metrics
        assertTrue(metrics.get().count() > 0);

        session.execute(String.format("DROP MATERIALIZED VIEW IF EXISTS %s.%s;", KEYSPACE, viewName));
        // no metrics after drop
        assertEquals(metrics.get().collect(Collectors.joining(",")), 0, metrics.get().count());
    }

    @AfterClass
    public static void teardown()
    {
        session.close();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.alfresco.maven</groupId>
    <artifactId>alfresco-sdk-aggregator</artifactId>
    <version>2.1.1-SNAPSHOT</version>
    <name>Alfresco SDK</name>
    <description>This aggregator Project builds all modules required for the Alfresco SDK</description>
    <packaging>pom</packaging>

    <url>${maven.site.url}</url>

    <prerequisites>
        <maven>3.0.3</maven>
    </prerequisites>

    <licenses>
        <license>
            <name>GNU Lesser General Public License v3.0 or later</name>
            <url>http://www.gnu.org/licenses/lgpl-3.0-standalone.html</url>
        </license>
    </licenses>

    <issueManagement>
        <system>GitHub</system>
        <url>https://github.com/Alfresco/alfresco-sdk/issues</url>
    </issueManagement>

    <scm>
        <connection>scm:git:${scm.url.base}.git</connection>
        <developerConnection>scm:git:${scm.url.base}</developerConnection>
        <url>${scm.url.base}</url>
      <tag>alfresco-sdk-aggregator-2.1.0-beta-1</tag>
  </scm>

    <developers>
        <developer>
            <id>mindthegab</id>
            <name>Gabriele Columbro</name>
            <email>gabriele.columbro@alfresco.com</email>
            <url>http://mindthegab.com</url>
            <organization>Alfresco Software</organization>
            <organizationUrl>http://www.alfresco.com</organizationUrl>
            <timezone>-5</timezone>
            <roles>
                <role>Founder</role>
                <role>Architect</role>
                <role>Developer</role>
            </roles>
        </developer>
        <developer>
            <id>maoo</id>
            <name>Maurizio Pillitu</name>
            <email>maurizio.pillitu@alfresco.com</email>
            <url>http://session.it</url>
            <organization>Alfresco Software</organization>
            <organizationUrl>http://www.alfresco.com</organizationUrl>
            <timezone>+1</timezone>
            <roles>
                <role>Architect</role>
                <role>Developer</role>
            </roles>
        </developer>
        <developer>
            <id>ohej</id>
            <name>Ole Hejlskov</name>
            <email>ole@magenta-aps.dk</email>
            <url>http://ohej.dk/</url>
            <organization>Magenta</organization>
            <organizationUrl>http://magenta.dk</organizationUrl>
            <timezone>+1</timezone>
            <roles>
                <role>Developer</role>
            </roles>
        </developer>
        <developer>
            <id>gravitonian</id>
            <name>Martin Bergljung</name>
            <email>martin.bergljung@alfresco.com</email>
            <url>http://www.marversolutions.com</url>
            <organization>Alfresco Software</organization>
            <organizationUrl>http://www.alfresco.com</organizationUrl>
            <timezone>+0</timezone>
            <roles>
                <role>Architect</role>
                <role>Developer</role>
            </roles>
        </developer>
    </developers>

    <contributors>
        <contributor>
            <name>Carlo Sciolla</name>
            <email>carlo@backbase.com</email>
            <organization>Backbase</organization>
            <organizationUrl>http://www.backbase.com</organizationUrl>
            <timezone>+1</timezone>
            <url>http://skuro.tk</url>
        </contributor>
        <contributor>
            <name>Samuel Langlois</name>
            <email>samuel.langlois@alfresco.com</email>
            <organization>Alfresco Software</organization>
            <organizationUrl>http://www.alfresco.com</organizationUrl>
            <timezone>+0</timezone>
            <url>https://twitter.com/samuel_langlois</url>
        </contributor>
        <contributor>
            <name>Ray Gauss II</name>
            <email>ray.gauss@alfresco.com</email>
            <organization>Alfresco Software</organization>
            <organizationUrl>http://www.alfresco.com</organizationUrl>
            <timezone>-5</timezone>
            <url>http://rgauss.com/</url>
        </contributor>
    </contributors>

    <!-- All the modules of the Alfresco SDK -->
    <modules>
        <!-- Modules -->
        <module>modules/alfresco-rad</module>
        <!-- Plugins -->
        <module>plugins/alfresco-maven-plugin</module>
        <!-- POM files -->
        <module>poms/alfresco-sdk-parent</module>
        <!-- Archetypes -->
        <module>archetypes/alfresco-amp-archetype</module>
        <module>archetypes/share-amp-archetype</module>
        <module>archetypes/alfresco-allinone-archetype</module>
  </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.archetype.version>2.2</maven.archetype.version>
        <alfresco.sdk.parent.version>${project.version}</alfresco.sdk.parent.version>
        <alfresco.community.default.version>5.0.d</alfresco.community.default.version>
        <alfresco.enterprise.default.version>5.0.1</alfresco.enterprise.default.version>
        <alfresco.rm.version>2.3</alfresco.rm.version>
        <springloaded.version>1.2.3.RELEASE</springloaded.version>
        <scm.url.base>https://github.com/Alfresco/alfresco-sdk</scm.url.base>
    </properties>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-archetype-plugin</artifactId>
                    <version>${maven.archetype.version}</version>
                    <configuration>
                        <skip>${skipTests}</skip>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <extensions>
            <extension>
                <groupId>org.apache.maven.archetype</groupId>
                <artifactId>archetype-packaging</artifactId>
                <version>${maven.archetype.version}</version>
            </extension>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-webdav-jackrabbit</artifactId>
                <version>2.2</version>
            </extension>
        </extensions>
    </build>

    <repositories>
        <repository>
            <id>alfresco-public</id>
            <url>https://artifacts.alfresco.com/nexus/content/groups/public
            </url>
        </repository>
        <repository>
            <id>alfresco-public-snapshots</id>
            <url>https://artifacts.alfresco.com/nexus/content/groups/public-snapshots
            </url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <profiles>
        <profile>
            <id>sdk-release</id>
            <properties>
                <maven.site.url>https://artifacts.alfresco.com/nexus/content/repositories/alfresco-docs/alfresco-sdk-aggregator/latest</maven.site.url>
                <maven.release.version>2.5.1</maven.release.version>
                <maven.release.goals>deploy site-deploy</maven.release.goals>
                <maven.site.version>3.4</maven.site.version>
                <maven.changes.version>2.10</maven.changes.version>
            </properties>
            <build>
                <plugins>
                     <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <version>2.4</version>
                        <executions>
                            <execution>
                                <id>attach-sources</id>
                                <goals>
                                    <goal>jar-no-fork</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <version>2.10.1</version>
                        <executions>
                            <execution>
                                <id>attach-javadocs</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                                <configuration>
	                                <additionalparam>-Xdoclint:none</additionalparam>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.5</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-release-plugin</artifactId>
                        <version>${maven.release.version}</version>
                        <configuration>
                            <preparationGoals>clean install</preparationGoals>
                            <goals>${maven.release.goals}</goals>
                            <autoVersionSubmodules>true</autoVersionSubmodules>
                            <releaseProfiles>sdk-release</releaseProfiles>
                        </configuration>
                    </plugin>
                </plugins>
                <pluginManagement>
                    <plugins>
                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-site-plugin</artifactId>
                            <version>${maven.site.version}</version>
                        </plugin>
                    </plugins>
                </pluginManagement>
            </build>
            <reporting>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-changes-plugin</artifactId>
                        <version>${maven.changes.version}</version>
                        <reportSets>
                            <reportSet>
                                <reports>
                                    <report>github-report</report>
                                </reports>
                            </reportSet>
                        </reportSets>
                        <configuration>
                            <onlyCurrentVersion>true</onlyCurrentVersion>
                        </configuration>
                    </plugin>
                </plugins>
            </reporting>
            <distributionManagement>
                <repository>
                    <id>central-releases-staging</id>
                    <url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url>
                </repository>
                <snapshotRepository>
                    <id>central-snapshots</id>
                    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
                </snapshotRepository>
                <site>
                    <id>alfresco-docs</id>
                    <url>dav:${maven.site.url}</url>
                </site>
            </distributionManagement>
        </profile>
        <!-- Attempt (failed) to retain run.sh permissions. Zip files are bad at this, full stop.
        <profile>
            <id>set-executables-permissions</id>
            <activation>
                <file>
                    <exists>src/main/resources/archetype-resources/run.sh</exists>
                </file>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.6</version>
                        <executions>
                            <execution>
                                <id>set-executable-resources</id>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                                <phase>process-resources</phase>
                                <configuration>
                                    <target>
                                        <chmod file="${project.build.outputDirectory}/archetype-resources/run.sh" perm="755" />
                                    </target>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
         -->
    </profiles>

</project>


text:
Install Cloudera CDH4 with puppet
=================================

Puppet modules to install hadoop, hbase, java, hive, impala, zookeeper in a production cluster.
Inital code from robbkidd's fork of my cdh3 module [here][robbkidd]
[robbkidd]: https://github.com/robbkidd/cloudera-cdh4-puppet

Prerequisites
=============

You must use [OAB][oab] to produce Java packages for install. Run OAB
according to its instructions and then place the generate files found in OAB's `deb/` directory into this
project's `modules/java/files/root/java` directory before running `vagrant up`.

[oab]: https://github.com/flexiondotorg/oab-java6

Copyright
=========

Copyright (c) 2012 Tom Hall.

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

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

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


text:
require 'test_helper'

class ImagesControllerTest < ActionController::TestCase
  setup do
    @image = images(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:images)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create image" do
    assert_difference('Image.count') do
      post :create, :image => @image.attributes
    end

    assert_redirected_to image_path(assigns(:image))
  end

  test "should show image" do
    get :show, :id => @image.to_param
    assert_response :success
  end

  test "should get edit" do
    get :edit, :id => @image.to_param
    assert_response :success
  end

  test "should update image" do
    put :update, :id => @image.to_param, :image => @image.attributes
    assert_redirected_to image_path(assigns(:image))
  end

  test "should destroy image" do
    assert_difference('Image.count', -1) do
      delete :destroy, :id => @image.to_param
    end

    assert_redirected_to images_path
  end
end


text:
<component name="InspectionProjectProfileManager">
  <profile version="1.0">
    <option name="myName" value="Project Default" />
    <inspection_tool class="AndroidLintLongLogTag" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AndroidLintSuspiciousIndentation" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="Anonymous2MethodRef" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CanBeFinal" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="REPORT_CLASSES" value="false" />
      <option name="REPORT_METHODS" value="false" />
      <option name="REPORT_FIELDS" value="true" />
    </inspection_tool>
    <inspection_tool class="CatchMayIgnoreExceptionMerged" />
    <inspection_tool class="CaughtExceptionImmediatelyRethrown" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CodeBlock2Expr" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ConstantConditionalExpression" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ConstantConditions" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="SUGGEST_NULLABLE_ANNOTATIONS" value="false" />
      <option name="DONT_REPORT_TRUE_ASSERT_STATEMENTS" value="false" />
    </inspection_tool>
    <inspection_tool class="ConstantIfStatement" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ContinueOrBreakFromFinallyBlock" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="Convert2Diamond" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="Convert2Lambda" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="Convert2MethodRef" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="Convert2streamapi" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="DialogTitleCapitalization" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="EmptyCatchBlock" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="m_includeComments" value="true" />
      <option name="m_ignoreTestCases" value="true" />
      <option name="m_ignoreIgnoreParameter" value="true" />
    </inspection_tool>
    <inspection_tool class="EmptyFinallyBlock" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="EmptyMethod" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="EmptyTryBlock" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="FinalPrivateMethod" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="FinalStaticMethod" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="FinallyBlockCannotCompleteNormally" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ForCanBeForeach" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="REPORT_INDEXED_LOOP" value="false" />
      <option name="ignoreUntypedCollections" value="false" />
    </inspection_tool>
    <inspection_tool class="IfCanBeSwitch" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="minimumBranches" value="3" />
      <option name="suggestIntSwitches" value="false" />
      <option name="suggestEnumSwitches" value="false" />
    </inspection_tool>
    <inspection_tool class="InfiniteLoopStatement" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JavaDoc" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="TOP_LEVEL_CLASS_OPTIONS">
        <value>
          <option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
          <option name="REQUIRED_TAGS" value="" />
        </value>
      </option>
      <option name="INNER_CLASS_OPTIONS">
        <value>
          <option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
          <option name="REQUIRED_TAGS" value="" />
        </value>
      </option>
      <option name="METHOD_OPTIONS">
        <value>
          <option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
          <option name="REQUIRED_TAGS" value="@return@param@throws or @exception" />
        </value>
      </option>
      <option name="FIELD_OPTIONS">
        <value>
          <option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
          <option name="REQUIRED_TAGS" value="" />
        </value>
      </option>
      <option name="IGNORE_DEPRECATED" value="false" />
      <option name="IGNORE_JAVADOC_PERIOD" value="true" />
      <option name="IGNORE_DUPLICATED_THROWS" value="false" />
      <option name="IGNORE_POINT_TO_ITSELF" value="false" />
      <option name="myAdditionalJavadocTags" value="" />
    </inspection_tool>
    <inspection_tool class="JniMissingFunction" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="LoopStatementsThatDontLoop" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ReturnFromFinallyBlock" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SafeVarargsDetector" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ThrowFromFinallyBlock" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="TryFinallyCanBeTryWithResources" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="TryWithIdenticalCatches" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnnecessaryEnumModifier" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnnecessaryInterfaceModifier" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnnecessaryLabelOnBreakStatement" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnnecessaryLabelOnContinueStatement" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnnecessaryLocalVariable" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="m_ignoreImmediatelyReturnedVariables" value="false" />
      <option name="m_ignoreAnnotatedVariables" value="false" />
    </inspection_tool>
    <inspection_tool class="UnnecessaryModuleDependencyInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnusedLabel" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnusedParameters" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnusedReturnValue" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="WhileCanBeForeach" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="unused" enabled="false" level="WARNING" enabled_by_default="false" checkParameterExcludingHierarchy="false">
      <option name="LOCAL_VARIABLE" value="true" />
      <option name="FIELD" value="true" />
      <option name="METHOD" value="true" />
      <option name="CLASS" value="true" />
      <option name="PARAMETER" value="true" />
      <option name="REPORT_PARAMETER_FOR_PUBLIC_METHODS" value="true" />
      <option name="ADD_MAINS_TO_ENTRIES" value="true" />
      <option name="ADD_APPLET_TO_ENTRIES" value="true" />
      <option name="ADD_SERVLET_TO_ENTRIES" value="true" />
      <option name="ADD_NONJAVA_TO_ENTRIES" value="true" />
    </inspection_tool>
  </profile>
</component>


text:
package org.apache.webbeans.portable;

import java.util.Map;

import javax.enterprise.context.spi.Contextual;
import javax.enterprise.inject.spi.Interceptor;

import org.apache.webbeans.context.creational.CreationalContextImpl;

public class BeanMetadataProducer<T> extends AbstractProducer<Contextual<T>>
{

    @Override
    protected Contextual<T> produce(Map<Interceptor<?>, ?> interceptors, CreationalContextImpl<Contextual<T>> creationalContext)
    {
        CreationalContextImpl<T> contextImpl = (CreationalContextImpl<T>)creationalContext;
        return contextImpl.getBean();
    }
}


text:
import * as React from 'react'
import {
  FilterOptionParsed, QueryDescription, QueryToken, SubTokensOptions,
  isList, isFilterGroupOptionParsed, isCheckBox
} from '../FindOptions'
import { ValueLine, FormGroup } from '../Lines'
import { Binding, IsByAll, tryGetTypeInfos, toLuxonFormat } from '../Reflection'
import { TypeContext } from '../TypeContext'
import "./FilterBuilder.css"
import { createFilterValueControl, MultiValue } from './FilterBuilder';
import { SearchMessage } from '../Signum.Entities';
import { classes } from '../Globals';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'

interface PinnedFilterBuilderProps {
  filterOptions: FilterOptionParsed[];
  onFiltersChanged?: (filters: FilterOptionParsed[]) => void;
  pinnedFilterVisible?: (fo: FilterOptionParsed) => boolean
  onSearch?: () => void;
  showSearchButton?: boolean;
  extraSmall?: boolean;
}
export default function PinnedFilterBuilder(p: PinnedFilterBuilderProps) {

  const timeoutWriteText = React.useRef<number | null>(null);

  var allPinned = getAllPinned(p.filterOptions).filter(fop => p.pinnedFilterVisible == null || p.pinnedFilterVisible(fop));

  if (allPinned.length == 0)
    return null;

  return (

        {
          allPinned
            .groupBy(fo => (fo.pinned!.column ?? 0).toString())
            .orderBy(gr => parseInt(gr.key))
            .map(gr =>

              {gr.elements.orderBy(a => a.pinned!.row).map((f, i) =>
{renderValue(f)}
)}

)
        }

      {p.showSearchButton &&
        <button className={classes("sf-query-button sf-search btn btn-primary")} onClick={() => p.onSearch && p.onSearch()} title="Enter">
          <FontAwesomeIcon icon={"magnifying-glass"} /> {SearchMessage.Search.niceToString()}
        </button>}

  );

  function renderValue(filter: FilterOptionParsed) {

    const f = filter;
    const readOnly = f.frozen;
    var label = f.pinned!.label || f.token?.niceName;

    if (f.pinned && (isCheckBox(f.pinned.active))) {
      return (

            <input type="checkbox" className="form-check-input me-1" checked={f.pinned.active == "Checkbox_StartChecked" || f.pinned.active == "NotCheckbox_StartChecked"} readOnly={readOnly} onChange={() => {
              f.pinned!.active =
                f.pinned!.active == "Checkbox_StartChecked" ? "Checkbox_StartUnchecked" :
                  f.pinned!.active == "Checkbox_StartUnchecked" ? "Checkbox_StartChecked" :
                    f.pinned!.active == "NotCheckbox_StartChecked" ? "NotCheckbox_StartUnchecked" :
                      f.pinned!.active == "NotCheckbox_StartUnchecked" ? "NotCheckbox_StartChecked" : undefined!;
            p.onFiltersChanged && p.onFiltersChanged(p.filterOptions);
          }} />{label}

      );
    }

    const ctx = new TypeContext<any>(undefined, { formGroupStyle: "Basic", readOnly: readOnly, formSize: p.extraSmall ? "xs" : "sm" }, undefined as any, Binding.create(f, a => a.value));

    if (isFilterGroupOptionParsed(f)) {
      return <ValueLine ctx={ctx} type={{ name: "string" }} onChange={() => handleValueChange(f)} label={label || SearchMessage.Search.niceToString()} />
    }

    if (isList(f.operation!))
      return (
        <FormGroup ctx={ctx} label={label}>
          <MultiValue values={f.value} readOnly={readOnly} onChange={() => handleValueChange(f)}
            onRenderItem={ctx => createFilterValueControl(ctx, f.token!, () => handleValueChange(f))} />
        </FormGroup>
      );

    return createFilterValueControl(ctx, f.token!, () => handleValueChange(f), label, f.pinned!.active == "WhenHasValue");
  }

  function handleValueChange(f: FilterOptionParsed) {

    if (isFilterGroupOptionParsed(f) || f.token && f.token.filterType == "String") {

      if (timeoutWriteText.current)
        clearTimeout(timeoutWriteText.current);

      timeoutWriteText.current = setTimeout(() => {
        p.onFiltersChanged && p.onFiltersChanged(p.filterOptions);
        timeoutWriteText.current = null;
      }, 200);

    } else {
      p.onFiltersChanged && p.onFiltersChanged(p.filterOptions);
    }
  }

  function handleFiltersKeyUp(e: React.KeyboardEvent<HTMLDivElement>) {
    if (p.onSearch && e.keyCode == 13) {
      setTimeout(() => {
        p.onSearch!();
      }, 200);
    }
  }

}

function getAllPinned(filterOptions: FilterOptionParsed[]): FilterOptionParsed[] {
  var direct = filterOptions.filter(a => a.pinned != null);

  var recursive = filterOptions
    .flatMap(f => f.pinned == null && isFilterGroupOptionParsed(f) ? getAllPinned(f.filters) : []);

  return direct.concat(recursive);
}


text:
package org.springframework.boot.test.mock.mockito;

import java.util.List;

import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextCustomizer;
import org.springframework.test.context.ContextCustomizerFactory;
import org.springframework.test.context.TestContextAnnotationUtils;

/**
 * A {@link ContextCustomizerFactory} to add Mockito support.
 *
 * @author Phillip Webb
 */
class MockitoContextCustomizerFactory implements ContextCustomizerFactory {

	@Override
	public ContextCustomizer createContextCustomizer(Class<?> testClass,
			List<ContextConfigurationAttributes> configAttributes) {
		// We gather the explicit mock definitions here since they form part of the
		// MergedContextConfiguration key. Different mocks need to have a different key.
		DefinitionsParser parser = new DefinitionsParser();
		parseDefinitions(testClass, parser);
		return new MockitoContextCustomizer(parser.getDefinitions());
	}

	private void parseDefinitions(Class<?> testClass, DefinitionsParser parser) {
		parser.parse(testClass);
		if (TestContextAnnotationUtils.searchEnclosingClass(testClass)) {
			parseDefinitions(testClass.getEnclosingClass(), parser);
		}
	}

}


text:
/*
  HCSR04 - Library for arduino, for HC-SR04 ultrasonic distance sensor.
  Created by Martin Sosic, June 11, 2016.
*/

#include "Arduino.h"
#include "HCSR04.h"

UltraSonicDistanceSensor::UltraSonicDistanceSensor(
        byte triggerPin, byte echoPin, unsigned short maxDistanceCm, unsigned long maxTimeoutMicroSec) {
    this->triggerPin = triggerPin;
    this->echoPin = echoPin;
    this->maxDistanceCm = maxDistanceCm;
    this->maxTimeoutMicroSec = maxTimeoutMicroSec;
    pinMode(triggerPin, OUTPUT);
    pinMode(echoPin, INPUT);
}

float UltraSonicDistanceSensor::measureDistanceCm() {
    //Using the approximate formula 19.307°C results in roughly 343m/s which is the commonly used value for air.
    return measureDistanceCm(19.307);
}

float UltraSonicDistanceSensor::measureDistanceCm(float temperature) {
    unsigned long maxDistanceDurationMicroSec;

    // Make sure that trigger pin is LOW.
    digitalWrite(triggerPin, LOW);
    delayMicroseconds(2);
    // Hold trigger for 10 microseconds, which is signal for sensor to measure distance.
    digitalWrite(triggerPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(triggerPin, LOW);
    float speedOfSoundInCmPerMicroSec = 0.03313 + 0.0000606 * temperature; // Cair ≈ (331.3 + 0.606 ⋅ ϑ) m/s

    // Compute max delay based on max distance with 25% margin in microseconds
    maxDistanceDurationMicroSec = 2.5 * maxDistanceCm / speedOfSoundInCmPerMicroSec;
    if (maxTimeoutMicroSec > 0) {
    	maxDistanceDurationMicroSec = min(maxDistanceDurationMicroSec, maxTimeoutMicroSec);
    }

    // Measure the length of echo signal, which is equal to the time needed for sound to go there and back.
    unsigned long durationMicroSec = pulseIn(echoPin, HIGH, maxDistanceDurationMicroSec); // can't measure beyond max distance

    float distanceCm = durationMicroSec / 2.0 * speedOfSoundInCmPerMicroSec;
    if (distanceCm == 0 || distanceCm > maxDistanceCm) {
        return -1.0 ;
    } else {
        return distanceCm;
    }
}