text:
require 'motion-support/inflector/methods'
require 'motion-support/inflector/inflections'
require 'motion-support/array'
require 'motion-support/string'
require 'motion-support/default_inflections'

module SchemaTools
  class SchemaBuilder

    def self.build_schema(app)
      schema_filename = File.join(app.project_dir, 'schemas/schema.rb')
      dsl = new
      dsl.instance_eval(File.read(schema_filename))
      return dsl.schema_hash, dsl.version
    end

    attr_accessor :schema_hash, :version

    def schema(opts={}, &block)
      check_opts(opts)
      @version = opts[:version]
      raise 'schema version must be an integer greater than 0' unless version_ok?
      @schema_hash = {}
      block.call
    end

    def check_opts(opts)
      raise 'schema must supply a hash before the block' unless opts.is_a? Hash
      raise 'schema must specify a version' unless opts[:version]
    end

    def version_ok?
      version.is_a?(Integer) && version > 0
    end

    def entity(class_name, opts={}, &block)
      # set default opts and merge passed in opts
      @opts = { id: true }.merge opts
      init_table(class_name)
      block.call
      ensure_primary_key
    end

    def init_table(class_name)
      @current_table = class_name.tableize
      @schema_hash[@current_table] = {}
    end

    def ensure_primary_key
      # Check that the schema has one and only one primary key somewhere
      table_schema = @schema_hash[@current_table]
      valid_table = false
      if @opts[:id]
        table_schema['id'] = 'INTEGER PRIMARY KEY AUTOINCREMENT' unless table_schema.has_key? 'id'
      else
        primary_keys = table_schema.values.select{ |val| val.include? 'PRIMARY KEY' }
        raise_primary_keys_error(table_schema.keys) unless primary_keys.length == 1
      end
    end

    def add_column(name, type)
      if @opts[:id] && name == 'id'
        raise_id_error unless type == 'INTEGER'
        type << ' PRIMARY KEY AUTOINCREMENT'
      end
      @schema_hash[@current_table][name] = type
    end

    %w(boolean float double integer datetime).each do |type|
      define_method(type) do |*args|
        column_name = args.first
        column_opts =  args[1].is_a?(Hash) ? args[1] : {}
        type = type.upcase
        type = add_primary(type, column_name) if column_opts[:primary_key]
        add_column column_name.to_s, type
      end
    end

    def string(column_name, column_opts={})
      type = 'VARCHAR'
      type = add_primary(type, column_name) if column_opts[:primary_key]
      add_column column_name.to_s, type
    end

    def integer32(column_name, column_opts={})
      type = 'INTEGER'
      type = add_primary(type, column_name) if column_opts[:primary_key]
      add_column column_name.to_s, type
    end

    def raise_id_error
      error_message = %Q(
  Your schema defines a non integer `id` column for #{@current_table}.
  If you do not wish to use the default id column, then you should
  specify the `id: false` option.
  )
      raise error_message
    end

    def raise_primary_keys_error(primary_keys)
      error_message = %Q(

  Your schema specified `id: false` for #{@current_table} and therefore must
  specify one primary key for this table. Instead you specified #{primary_keys.length}.

  )
      error_message += "These are the keys you gave: #{primary_keys}\n" if primary_keys.length > 1
      raise error_message
    end

    def add_primary(type, name)
      if @opts[:id]
        puts "SWISS DB WARNING: ignoring primary_key: #{name} because `id` is the default primary key"
      else
        type << ' PRIMARY KEY'
        type << ' AUTOINCREMENT' if type == 'INTEGER PRIMARY KEY'
      end
      type
    end
  end
end


text:
package zutil.osal.app.ffmpeg;

import org.junit.Test;
import zutil.osal.app.ffmpeg.FFmpegConstants.*;

import static org.junit.Assert.*;

public class FFmpegTest {

    @Test
    public void noArgs() {
        FFmpeg ffmpeg = new FFmpeg();
        ffmpeg.addInput(new FFmpegInput("iTest.mp4"));
        ffmpeg.addOutput(new FFmpegOutput("oTest.mp4"));

        assertEquals("ffmpeg -i iTest.mp4 oTest.mp4", ffmpeg.buildCommand());
    }

    @Test
    public void setLogLevel() {
        FFmpeg ffmpeg = new FFmpeg();
        ffmpeg.setLogLevel(FFmpegLogLevel.ERROR);
        ffmpeg.addInput(new FFmpegInput("iTest.mp4"));
        ffmpeg.addOutput(new FFmpegOutput("oTest.mp4"));

        assertEquals("ffmpeg -loglevel error -i iTest.mp4 oTest.mp4", ffmpeg.buildCommand());
    }

    @Test
    public void enableOutputOverwrite() {
        FFmpeg ffmpeg = new FFmpeg();
        ffmpeg.enableOutputOverwrite(true);
        ffmpeg.addInput(new FFmpegInput("iTest.mp4"));
        ffmpeg.addOutput(new FFmpegOutput("oTest.mp4"));

        assertEquals("ffmpeg -y -i iTest.mp4 oTest.mp4", ffmpeg.buildCommand());
    }
}

redpajama_set_name: RedPajamaGithub


text:
use crate::{Response, MiddlewareResult};
use hyper::header;
use crate::status::StatusCode;

pub trait Redirect: Sized {
    type Result;

    /// Redirect the response to a given target
    ///
    /// # Examples
    /// ```{rust}
    /// extern crate nickel;
    ///
    /// use nickel::{Nickel, HttpRouter, Request, Response, MiddlewareResult};
    /// use nickel::extensions::Redirect;
    ///
    /// fn redirect(_: &mut Request, res: Response) -> MiddlewareResult {
    ///     return res.redirect("http://nickel.rs")
    /// }
    ///
    /// fn main() {
    ///     let mut server = Nickel::new();
    ///     server.get("/a", redirect);
    /// }
    /// ```
    fn redirect<T>(self, target: T) -> Self::Result
    where T: Into<String> {
        self.redirect_with(target, StatusCode::FOUND)
    }

    fn redirect_permanently<T>(self, target: T) -> Self::Result
    where T: Into<String> {
        self.redirect_with(target, StatusCode::MOVED_PERMANENTLY)
    }

    fn redirect_with<T>(self, target: T, status: StatusCode) -> Self::Result
    where T: Into<String>;
}

// TODO: rework this to return a Responder so it will work with the
// middleware macro
impl<D: Send + 'static + Sync> Redirect for Response<D> {
    type Result = MiddlewareResult<D>;

    fn redirect_with<T>(mut self, target: T, status: StatusCode) -> Self::Result
    where T: Into<String> {
        let header_value: header::HeaderValue = match target.into().parse() {
            Ok(v) => v,
            Err(e) => {
                return self.error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string());
            }
        };
        self.headers_mut().insert(header::LOCATION, header_value);

        let code = status.as_u16();
        if code < 300 || code >= 400 {
            self.error(StatusCode::INTERNAL_SERVER_ERROR, "redirect_with called with non-3xx status code")
        } else {
            self.send(status)
        }
    }
}


text:
package io.grpc.internal;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.grpc.internal.Channelz.TransportStats;
import java.util.concurrent.TimeUnit;

/**
 * A class for gathering statistics about a transport. This is an experimental feature.
 * Can only be called from the transport thread unless otherwise noted.
 */
public final class TransportTracer {
  private static final TimeProvider SYSTEM_TIME_PROVIDER = new TimeProvider() {
    @Override
    public long currentTimeMillis() {
      return System.currentTimeMillis();
    }
  };
  private static final Factory DEFAULT_FACTORY = new Factory(SYSTEM_TIME_PROVIDER);

  private final TimeProvider timeProvider;
  private long streamsStarted;
  private long lastStreamCreatedTimeNanos;
  private long streamsSucceeded;
  private long streamsFailed;
  private long keepAlivesSent;
  private FlowControlReader flowControlWindowReader;

  private long messagesSent;
  private long lastMessageSentTimeNanos;
  // deframing happens on the application thread, and there's no easy way to avoid synchronization
  private final LongCounter messagesReceived = LongCounterFactory.create();
  private volatile long lastMessageReceivedTimeNanos;

  public TransportTracer() {
    this.timeProvider = SYSTEM_TIME_PROVIDER;
  }

  private TransportTracer(TimeProvider timeProvider) {
    this.timeProvider = timeProvider;
  }

  /**
   * Returns a read only set of current stats.
   */
  public TransportStats getStats() {
    long localFlowControlWindow =
        flowControlWindowReader == null ? -1 : flowControlWindowReader.read().localBytes;
    long remoteFlowControlWindow =
        flowControlWindowReader == null ? -1 : flowControlWindowReader.read().remoteBytes;
    return new TransportStats(
        streamsStarted,
        lastStreamCreatedTimeNanos,
        streamsSucceeded,
        streamsFailed,
        messagesSent,
        messagesReceived.value(),
        keepAlivesSent,
        lastMessageSentTimeNanos,
        lastMessageReceivedTimeNanos,
        localFlowControlWindow,
        remoteFlowControlWindow);
  }

  /**
   * Called by the transport to report a stream has started. For clients, this happens when a header
   * is sent. For servers, this happens when a header is received.
   */
  public void reportStreamStarted() {
    streamsStarted++;
    lastStreamCreatedTimeNanos = currentTimeNanos();
  }

  /**
   * Reports that a stream closed with the specified Status.
   */
  public void reportStreamClosed(boolean success) {
    if (success) {
      streamsSucceeded++;
    } else {
      streamsFailed++;
    }
  }

  /**
   * Reports that some messages were successfully sent. {@code numMessages} must be at least 0.
   */
  public void reportMessageSent(int numMessages) {
    if (numMessages == 0) {
      return;
    }
    messagesSent += numMessages;
    lastMessageSentTimeNanos = currentTimeNanos();
  }

  /**
   * Reports that a message was successfully received. This method is thread safe.
   */
  public void reportMessageReceived() {
    messagesReceived.add(1);
    lastMessageReceivedTimeNanos = currentTimeNanos();
  }

  /**
   * Reports that a keep alive message was sent.
   */
  public void reportKeepAliveSent() {
    keepAlivesSent++;
  }

  /**
   * Registers a {@link FlowControlReader} that can be used to read the local and remote flow
   * control window sizes.
   */
  public void setFlowControlWindowReader(FlowControlReader flowControlWindowReader) {
    this.flowControlWindowReader = Preconditions.checkNotNull(flowControlWindowReader);
  }

  /**
   * A container that holds the local and remote flow control window sizes.
   */
  public static final class FlowControlWindows {
    public final long remoteBytes;
    public final long localBytes;

    public FlowControlWindows(long localBytes, long remoteBytes) {
      this.localBytes = localBytes;
      this.remoteBytes = remoteBytes;
    }
  }

  /**
   * An interface for reading the local and remote flow control windows of the transport.
   */
  public interface FlowControlReader {
    FlowControlWindows read();
  }

  private long currentTimeNanos() {
    return TimeUnit.MILLISECONDS.toNanos(timeProvider.currentTimeMillis());
  }

  /**
   * Time source representing the current system time in millis. Used to inject a fake clock
   * into unit tests.
   */
  @VisibleForTesting
  public interface TimeProvider {
    /** Returns the current milli time. */
    long currentTimeMillis();
  }

  public static final class Factory {
    private TimeProvider timeProvider;

    @VisibleForTesting
    public Factory(TimeProvider timeProvider) {
      this.timeProvider = timeProvider;
    }

    public TransportTracer create() {
      return new TransportTracer(timeProvider);
    }
  }

  public static Factory getDefaultFactory() {
    return DEFAULT_FACTORY;
  }
}


text:
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Supported operating systems property.
    /// </summary>
    public partial class SupportedOSProperty
    {
        /// <summary>
        /// Initializes a new instance of the SupportedOSProperty class.
        /// </summary>
        public SupportedOSProperty()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the SupportedOSProperty class.
        /// </summary>
        /// <param name="instanceType">The replication provider type.</param>
        /// <param name="supportedOs">The list of supported operating
        /// systems.</param>
        public SupportedOSProperty(string instanceType = default(string), IList<SupportedOSDetails> supportedOs = default(IList<SupportedOSDetails>))
        {
            InstanceType = instanceType;
            SupportedOs = supportedOs;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the replication provider type.
        /// </summary>
        [JsonProperty(PropertyName = "instanceType")]
        public string InstanceType { get; set; }

        /// <summary>
        /// Gets or sets the list of supported operating systems.
        /// </summary>
        [JsonProperty(PropertyName = "supportedOs")]
        public IList<SupportedOSDetails> SupportedOs { get; set; }

    }
}


text:
package com.michaelrnovak.objectcursor.widget;

import android.database.Cursor;
import android.widget.Filter;

import com.michaelrnovak.objectcursor.ObjectCursor;

class ObjectCursorFilter<T> extends Filter {
    ObjectCursorFilterClient<T> mFilterClient;

    interface ObjectCursorFilterClient<T> {
        CharSequence convertToString(Cursor cursor);
        ObjectCursor<T> runQueryOnBackgroundThread(CharSequence constraint);
        ObjectCursor<T> getObjectCursor();

        void changeObjectCursor(ObjectCursor<T> cursor);
    }

    ObjectCursorFilter(ObjectCursorFilterClient<T> client) {
        mFilterClient = client;
    }

    @Override
    public CharSequence convertResultToString(Object resultValue) {
        return mFilterClient.convertToString((Cursor) resultValue);
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        Cursor cursor = mFilterClient.runQueryOnBackgroundThread(constraint);
        FilterResults results = new FilterResults();

        if (cursor != null) {
            results.count = cursor.getCount();
            results.values = cursor;
        } else {
            results.count = 0;
            results.values = null;
        }

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        ObjectCursor<T> oldCursor = mFilterClient.getObjectCursor();

        if (results.values != null && results.values != oldCursor) {
            mFilterClient.changeObjectCursor((ObjectCursor<T>) results.values);
        }
    }
}


text:
package com.lucidworks.spark.rdd;

import com.lucidworks.spark.util.JavaApiHelper;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.SolrDocument;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaRDD;

public class SolrJavaRDD extends JavaRDD<SolrDocument> {

  private final SelectSolrRDD solrRDD;

  public SolrJavaRDD(SelectSolrRDD solrRDD) {
    super(solrRDD, solrRDD.elementClassTag());
    this.solrRDD = solrRDD;
  }

  protected SolrJavaRDD wrap(SelectSolrRDD rdd) {
    return new SolrJavaRDD(rdd);
  }

  public JavaRDD<SolrDocument> query(String query) {
    return wrap(rdd().query(query));
  }

  public JavaRDD<SolrDocument> queryShards(String query) {
    return wrap(rdd().query(query));
  }

  public JavaRDD<SolrDocument> queryShards(SolrQuery solrQuery) {
    return wrap(rdd().query(solrQuery));
  }

  public JavaRDD<SolrDocument> queryShards(SolrQuery solrQuery, String splitFieldName, int splitsPerShard) {
    return wrap(rdd().query(solrQuery).splitField(splitFieldName).splitsPerShard(splitsPerShard));
  }

  public JavaRDD<SolrDocument> queryNoSplits(String query) {
    return wrap(rdd().query(query).splitsPerShard(1));
  }

  @Override
  public SelectSolrRDD rdd() {
    return solrRDD;
  }

  public static SolrJavaRDD get(String zkHost, String collection, SparkContext sc) {
    SelectSolrRDD solrRDD = SelectSolrRDD$.MODULE$.apply(zkHost, collection, sc);
    return new SolrJavaRDD(solrRDD);
  }

}


text:
package org.springframework.security.test.web.reactive.server;

import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.web.reactive.result.method.annotation.CurrentSecurityContextArgumentResolver;
import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter;
import org.springframework.test.web.reactive.server.WebTestClient;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockJwt;
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity;

/**
 * @author Jérôme Wacongne <ch4mp@c4-soft.com>
 * @author Josh Cummings
 * @since 5.2
 */
@RunWith(MockitoJUnitRunner.class)
public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerConfigurersTests {
	@Mock
	GrantedAuthority authority1;

	@Mock
	GrantedAuthority authority2;

	WebTestClient client = WebTestClient
			.bindToController(securityContextController)
			.webFilter(new SecurityContextServerWebExchangeWebFilter())
			.argumentResolvers(resolvers -> resolvers.addCustomResolver(
					new CurrentSecurityContextArgumentResolver(new ReactiveAdapterRegistry())))
			.apply(springSecurity())
			.configureClient()
			.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
			.build();

	@Test
	public void mockJwtWhenUsingDefaultsTheCreatesJwtAuthentication() {
		client
				.mutateWith(mockJwt())
				.get()
				.exchange()
				.expectStatus().isOk();

		SecurityContext context = securityContextController.removeSecurityContext();
		assertThat(context.getAuthentication()).isInstanceOf(
				JwtAuthenticationToken.class);
		JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication();
		assertThat(token.getAuthorities()).isNotEmpty();
		assertThat(token.getToken()).isNotNull();
		assertThat(token.getToken().getSubject()).isEqualTo("user");
		assertThat(token.getToken().getHeaders().get("alg")).isEqualTo("none");
	}

	@Test
	public void mockJwtWhenProvidingBuilderConsumerThenProducesJwtAuthentication() {
		String name = new String("user");
		client
				.mutateWith(mockJwt(jwt -> jwt.subject(name)))
				.get()
				.exchange()
				.expectStatus().isOk();

		SecurityContext context = securityContextController.removeSecurityContext();
		assertThat(context.getAuthentication()).isInstanceOf(
				JwtAuthenticationToken.class);
		JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication();
		assertThat(token.getToken().getSubject()).isSameAs(name);
	}

	@Test
	public void mockJwtWhenProvidingCustomAuthoritiesThenProducesJwtAuthentication() {
		client
				.mutateWith(mockJwt(jwt -> jwt.claim("scope", "ignored authorities"))
						.authorities(this.authority1, this.authority2))
				.get()
				.exchange()
				.expectStatus().isOk();

		SecurityContext context = securityContextController.removeSecurityContext();
		assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities())
				.containsOnly(this.authority1, this.authority2);
	}

	@Test
	public void mockJwtWhenProvidingScopedAuthoritiesThenProducesJwtAuthentication() {
		client
				.mutateWith(mockJwt(jwt -> jwt.claim("scope", "scoped authorities")))
				.get()
				.exchange()
				.expectStatus().isOk();

		SecurityContext context = securityContextController.removeSecurityContext();
		assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities())
				.containsOnly(new SimpleGrantedAuthority("SCOPE_scoped"),
						new SimpleGrantedAuthority("SCOPE_authorities"));
	}

	@Test
	public void mockJwtWhenProvidingGrantedAuthoritiesThenProducesJwtAuthentication() {
		client
				.mutateWith(mockJwt(jwt -> jwt.claim("scope", "ignored authorities"))
						.authorities(jwt -> Arrays.asList(this.authority1)))
						.get()
						.exchange()
						.expectStatus().isOk();

		SecurityContext context = securityContextController.removeSecurityContext();
		assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities())
				.containsOnly(this.authority1);
	}

	@Test
	public void mockJwtWhenProvidingPreparedJwtThenProducesJwtAuthentication() {
		Map<String, Object> claims = new HashMap<>();
		claims.put(IdTokenClaimNames.SUB, "some_user");
		Jwt originalToken = new Jwt("token123", Instant.now(), Instant.now().plusSeconds(3600),
				Collections.singletonMap("header1", "value1"), claims);
		client
				.mutateWith(mockJwt(originalToken))
				.get()
				.exchange()
				.expectStatus().isOk();

		SecurityContext context = securityContextController.removeSecurityContext();
		assertThat(context.getAuthentication()).isInstanceOf(
				JwtAuthenticationToken.class);
		JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication();
		assertThat(retrievedToken.getToken().getSubject()).isEqualTo("some_user");
		assertThat(retrievedToken.getToken().getTokenValue()).isEqualTo("token123");
		assertThat(retrievedToken.getToken().getHeaders().get("header1")).isEqualTo("value1");
	}
}


text:
/////////////////////////////////////////////////////////////////////////////////
//
//  Levenberg - Marquardt non-linear minimization algorithm
//  Copyright (C) 2004-05  Manolis Lourakis (lourakis at ics forth gr)
//  Institute of Computer Science, Foundation for Research & Technology - Hellas
//  Heraklion, Crete, Greece.
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
/////////////////////////////////////////////////////////////////////////////////

/********************************************************************************
 * Box-constrained Levenberg-Marquardt nonlinear minimization. The same core code
 * is used with appropriate #defines to derive single and double precision versions,
 * see also lmbc_core.c
 ********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>

#include "levmar.h"
#include "compiler.h"
#include "misc.h"

#define EPSILON       1E-12
#define ONE_THIRD     0.3333333334 /* 1.0/3.0 */

#if !defined(LM_DBL_PREC) && !defined(LM_SNGL_PREC)
#error At least one of LM_DBL_PREC, LM_SNGL_PREC should be defined!
#endif

#ifdef LM_SNGL_PREC
/* single precision (float) definitions */
#define LM_REAL float
#define LM_PREFIX s

#define LM_REAL_MAX FLT_MAX
#define LM_REAL_MIN -FLT_MAX

#define LM_REAL_EPSILON FLT_EPSILON
#define __SUBCNST(x) x##F
#define LM_CNST(x) __SUBCNST(x) // force substitution

#include "lmbc_core.c" // read in core code

#undef LM_REAL
#undef LM_PREFIX
#undef LM_REAL_MAX
#undef LM_REAL_MIN
#undef LM_REAL_EPSILON
#undef __SUBCNST
#undef LM_CNST
#endif /* LM_SNGL_PREC */

#ifdef LM_DBL_PREC
/* double precision definitions */
#define LM_REAL double
#define LM_PREFIX d

#define LM_REAL_MAX DBL_MAX
#define LM_REAL_MIN -DBL_MAX

#define LM_REAL_EPSILON DBL_EPSILON
#define LM_CNST(x) (x)

#include "lmbc_core.c" // read in core code

#undef LM_REAL
#undef LM_PREFIX
#undef LM_REAL_MAX
#undef LM_REAL_MIN
#undef LM_REAL_EPSILON
#undef LM_CNST
#endif /* LM_DBL_PREC */


text:
#ifndef SkEmbossMask_DEFINED
#define SkEmbossMask_DEFINED

#include "SkEmbossMaskFilter.h"

class SkEmbossMask {
public:
    static void Emboss(SkMask* mask, const SkEmbossMaskFilter::Light&);
};

#endif


text:
exports.L = { bit: 1 }
exports.M = { bit: 0 }
exports.Q = { bit: 3 }
exports.H = { bit: 2 }

function fromString (string) {
  if (typeof string !== 'string') {
    throw new Error('Param is not a string')
  }

  const lcStr = string.toLowerCase()

  switch (lcStr) {
    case 'l':
    case 'low':
      return exports.L

    case 'm':
    case 'medium':
      return exports.M

    case 'q':
    case 'quartile':
      return exports.Q

    case 'h':
    case 'high':
      return exports.H

    default:
      throw new Error('Unknown EC Level: ' + string)
  }
}

exports.isValid = function isValid (level) {
  return level && typeof level.bit !== 'undefined' &&
    level.bit >= 0 && level.bit < 4
}

exports.from = function from (value, defaultValue) {
  if (exports.isValid(value)) {
    return value
  }

  try {
    return fromString(value)
  } catch (e) {
    return defaultValue
  }
}


text:
require 'helper'

USER = '' # YOUR IDEONE USER
PASS = '' # YOUR IDEONE PASSWORD

class TestIdeoneRubyApi < Test::Unit::TestCase
  def test_initialize
    omit_if(USER.empty? || PASS.empty?, "Specify ideone USER and PASS")

    instance = Ideone.new
    assert_not_nil(instance)

    instance = Ideone.new(USER, PASS)
    assert_not_nil(instance)
  end

  def test_ideone_test
    omit_if(USER.empty? || PASS.empty?, "Specify ideone USER and PASS")

    instance = Ideone.new(USER, PASS)

    result = instance.test

    def compare_intersecting_keys(a, b)
      (a.keys & b.keys).all? {|k| a[k] == b[k]}
    end

    assert compare_intersecting_keys(result,{"error"=>"OK", "moreHelp"=>"ideone.com", "pi"=>"3.14", "answerToLifeAndEverything"=>"42", "oOok"=>true}) == true
    assert_not_nil result
  end

  def test_languages
    omit_if(USER.empty? || PASS.empty?, "Specify ideone USER and PASS")

    instance = Ideone.new(USER, PASS)

    result = instance.languages

    assert result.count > 10
    assert_not_nil result
  end

  def test_create_submission
    omit_if(USER.empty? || PASS.empty?, "Specify ideone USER and PASS")

    instance = Ideone.new(USER, PASS)

    code = <<-eos
puts "This is a test submission created from ideone-ruby-api. https://github.com/kennym/ideone-gem/blob/master/lib/ideone.rb"
    eos
    result = instance.create_submission(code, 17)

    assert result.is_a?(String)
    assert_not_nil result
  end

  def test_submission_status
    omit_if(USER.empty? || PASS.empty?, "Specify ideone USER and PASS")

    instance = Ideone.new(USER, PASS)

    result = instance.submission_status("nDRJO")

    assert_not_nil result
    assert_not_nil result[:status]
    assert_not_nil result[:result]
  end

  def test_submission_details
    omit_if(USER.empty? || PASS.empty?, "Specify ideone USER and PASS")

    instance = Ideone.new(USER, PASS)

    result = instance.submission_details("nDRJO")

    assert result.count == 16
    assert_not_nil result
  end
end


text:
require 'twilio-ruby'

# Get your Account SID and Auth Token from https://twilio.com/console
# To set up environmental variables, see http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
client = Twilio::REST::Client.new(account_sid, auth_token)

fleet_sid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
fleet_service = client.preview.deployed_devices.fleets(fleet_sid)

key_sid = 'KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
key = fleet_service.keys(key_sid).update(
  friendly_name: 'My New Device Key',
  device_sid: 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
)

puts key.friendly_name


text:
class RenameShoppeOptionValuesType < ActiveRecord::Migration
  def up
    rename_column :shoppe_option_values, :type, :option_type
  end

  def down
    rename_column :shoppe_option_values, :option_type, :type
  end
end


text:
package com.openxc.measurements;

import com.openxc.units.Level;
import com.openxc.util.Range;

/**
 * VolumeSetPoint will set the volume directly to any point between
 * minimum (0) and maximum (31)
 */
public class VolumeSetPoint extends BaseMeasurement<Level> {
	private final static String ID = "set_point_volume";
	private final static Range<Level> RANGE = new Range<Level>(new Level(0.0), new Level(31));

	public VolumeSetPoint(Number value) {
		super(new Level(value), RANGE);
	}

	public VolumeSetPoint(Level value) {
		super(value, RANGE);
	}

    @Override
    public String getGenericName() {
        return ID;
    }
}


text:
title: Access
---
Number of people served by dispensers across Uganda.

We collect and verify data on the number of households using a waterpoint. The number of people per household is estimated based on monthly evaluations of randomly selected households.


text:
<meta charset="utf-8">

  <img src="../photo_gallery/je/images/JE_002.jpg" class="image1 resizeme" data-description="

													Caption

The Isle of Jersey (officially called the Bailiwick of Jersey) is the largest of the Channel Islands in the Bay of Mont St. Michel off the northwest coast of France. This Terra satellite image vividly displays the island's agricultural patchwork terrain. Image courtesy of NASA.

													Dimensions
													File Size
													Download

													424 X 540
													39403 kb

													Usage

														Factbook photos - obtained from a wide variety of sources - are in the public domain and are copyright free.

Agency Copyright Notice

" data-link="../photo_gallery/je/images/JE_002.jpg">


text:
/* global client */
/* eslint-env mocha */
const chai = require('chai')
chai.should()
const testCaseFactory = require('./test-case-factory')
const path = require('path')
const { JSDOM } = require('jsdom')
const cucumberHtmlReporter = require('cucumber-html-reporter')

describe('Reporting features', () => {
  it('should work together with cucumber-html-reporter', () => {
    return testCaseFactory
      .create('cucumber-html-report-test')
      .feature('addition')
      .scenario('small numbers')
      .given('User is on the simple calculator page', () => client.init())
      .and('User enter 4 in A field', () => client.setValue('#a', 4))
      .and('User enter 5 in B field', () => client.setValue('#b', 5))
      .when('User press Add button', () => client.click('#add'))
      .then('The result should contain 9', () => client.assert.containsText('#result', 9))
      .scenario('big numbers')
      .given('User is on the simple calculator page')
      .and('User enter 4 in A field')
      .and('User enter 5 in B field')
      .when('User press Add button')
      .then('The result should contain 9')
      .feature('subtraction')
      .scenario('small numbers')
      .given('User is on the simple calculator page')
      .and('User enter 9 in A field', () => client.setValue('#a', 9))
      .and('User enter 3 in B field', () => client.setValue('#b', 3))
      .when('User press Subtract button', () => client.click('#subtract'))
      .then('The result should contain 6', () => client.assert.containsText('#result', 6))
      .scenario('big numbers')
      .given('User is on the simple calculator page')
      .and('User enter 4 in A field')
      .and('User enter 5 in B field')
      .when('User press Subtract button')
      .then('The result should contain -1', () => client.assert.containsText('#result', -1))
      .run()
      .then((result) => {
        createHTMLReport(result.testCasePath)
        return getCucumberHtmlReportWindow(result.testCasePath)
      })
      .then((dom) => {
        dom.window.document.querySelector('.navbar-header .label-success').textContent.should.equal('Passed: 2')
        dom.window.document.querySelector('.navbar-header .label-danger').textContent.should.equal('Failed: 0')
      })
  })

  it('should attach screenshots for failing scenarios', () => {
    return testCaseFactory
      .create('screenshot-attachement-test', { screenshots: true })
      .feature('addition')
      .scenario('small numbers')
      .given('User is on the simple calculator page', () => client.init())
      .and('User enter 4 in A field', () => client.setValue('#a', 4))
      .and('User enter 5 in B field', () => client.setValue('#b', 5))
      .when('User press Add button', () => client.click('#add'))
      .then('The result should contain 8', () => client.assert.containsText('#result', 8))
      .run()
      .then((result) => {
        createHTMLReport(result.testCasePath)
        return getCucumberHtmlReportWindow(result.testCasePath)
      })
      .then((dom) => {
        const feature = dom.window.document.querySelector('[href$="#collapseFeaturenightwatch_cucumber0"]')
        const featureMatch = feature.textContent.match(/^\s*(.*?):(.*?)\s*.*\s*$/)
        featureMatch.should.not.to.be.null
        featureMatch[1].should.equal('Feature')
        featureMatch[2].should.equal('addition')
        feature.querySelector('.label-danger').textContent.should.equal('1')

        const scenario = dom.window.document.querySelector('[href$="#collapseScenarionightwatch_cucumber0_0"]')
        const scenarioMatch = scenario.textContent.match(/^\s*(.*?):(.*?)\s*.*\s*.*\s*$/)
        scenarioMatch.should.not.to.be.null
        scenarioMatch[1].should.equal('Scenario')
        scenarioMatch[2].should.equal('small numbers')
        scenario.querySelector('.label-success').textContent.should.equal('4')
        scenario.querySelector('.label-danger').textContent.should.equal('1')

        const screenshot = dom.window.document.querySelector('#collapseScenarionightwatch_cucumber0_0 img.screenshot')
        screenshot.src.startsWith('data:image/png;base64,iVBOR').should.equal(true)
      })
  })
})

function createHTMLReport (testCasePath) {
  cucumberHtmlReporter.generate({
    theme: 'bootstrap',
    jsonFile: path.join(testCasePath, 'reports', 'cucumber.json'),
    output: path.join(testCasePath, 'reports', 'cucumber.html')
  })
}

function getCucumberHtmlReportWindow (testCasePath) {
  return JSDOM.fromFile(path.join(testCasePath, 'reports', 'cucumber.html'))
}


text:
/**
*	@file    SoXipOverlaySearch.h
*	@brief   Declaration of the SoXipOverlaySearch class
*	@author  Julien Gein
**/

#ifndef SOXIPOVERLAYSEARCH_H
#define SOXIPOVERLAYSEARCH_H

#include <Inventor/nodes/SoSubNode.h>
#include <Inventor/fields/SoSFBool.h>
#include <Inventor/fields/SoSFInt32.h>
#include <Inventor/fields/SoSFEnum.h>
#include <Inventor/fields/SoSFString.h>
#include <Inventor/fields/SoMFString.h>
#include <Inventor/fields/SoMFNode.h>
#include <Inventor/fields/SoSFShort.h>
#include <Inventor/fields/SoSFTrigger.h>

/**
*	@class SoXipOverlaySearch
*
* Overlay search engine. Retrieve a list of overlays
* from the specified scene graph and given some search criteria.
*
**/
class SoXipOverlaySearch : public SoNode
{
	SO_NODE_HEADER( SoXipOverlaySearch );

public:
	/// Constructor
	SoXipOverlaySearch();

	/// number of nodes upward where to start the search action
	SoSFShort		numNodesUpToContainer;
	/// shapes should match given label, if not ""
	SoMFString		label;
	/// shapes class name should match given type, if not ""
	SoSFString		type;
	/// shoudl the shapes be closed ?
	SoSFBool		closed;
	/// should the shapes be selected ?
	SoSFBool		selected;
	/// should the search action goes trough kits and groups ?
	SoSFBool		searchAll;
	/// perform the search action
	SoSFTrigger		search;

	/// list of found overlays
	SoMFNode		overlays;
	/// Number of overlay found
	SoSFInt32		numOverlays;

	/// Open Inventor class initialization
	static void initClass();

protected:
	/// Destructor
	~SoXipOverlaySearch();

	virtual void GLRender( SoGLRenderAction* action );
	virtual void handleEvent( SoHandleEventAction* action );
	virtual void doAction( SoAction* action );

	/// Select the matching shapes from a list of nodes
	virtual SoNodeList selectMatches( const SoNodeList& shapes );
	/// Select the matching shapes from a list of shapes
	virtual SoNodeList selectMatches( class SoXipShapeList* shapeList );

	/// Should the search be performed ?
	SbBool			m_doSearch;

private:
	static void searchSensorCB( void* userData, SoSensor* sensor );

	SoFieldSensor*	mSearchSensor;
};

#endif // SOXIPOVERLAYSEARCH_H


text:
package org.apache.streams.builders.threaded;

import com.google.common.util.concurrent.*;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;

import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import org.slf4j.LoggerFactory;

public class ThreadingController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadingController.class);

    private final String name;
    private final int maxNumberOfThreads;
    private final int priority;
    private final ThreadPoolExecutor threadPoolExecutor;
    private final ListeningExecutorService listeningExecutorService;
    private final Condition lock = new SimpleCondition();
    private final AtomicInteger numThreads;
    private final AtomicLong lastWorked = new AtomicLong(new Date().getTime());
    private final AtomicLong numberOfObservations = new AtomicLong(0);
    private final AtomicDouble sumOfObservations = new AtomicDouble(0);
    private final AtomicInteger workingNow = new AtomicInteger(0);

    private volatile double lastCPUObservation = 0.0;

    private static final long SCALE_CHECK = 2000;
    private Double scaleThreshold = .85;
    private ThreadingControllerCPUObserver threadingControllerCPUObserver = new DefaultThreadingControllerCPUObserver();

    private static final Integer NUM_PROCESSORS = Runtime.getRuntime().availableProcessors();

    public static final ThreadingController INSTANCE_LOW_PRIORITY = new ThreadingController("Apache Streams [low]", NUM_PROCESSORS, NUM_PROCESSORS * 2, Thread.NORM_PRIORITY - 2);
    public static final ThreadingController INSTANCE = new ThreadingController("Apache Streams [default]", NUM_PROCESSORS, NUM_PROCESSORS * 5, Thread.NORM_PRIORITY);
    public static final ThreadingController INSTANCE_HIGH_PRIORITY = new ThreadingController("Apache Streams [high]", NUM_PROCESSORS, NUM_PROCESSORS * 7, Thread.NORM_PRIORITY + 2);

    /**
     * Use for very low priority items... The thread-pool that runs this runs at priority
     * (Thread.NORM_PRIORITY - 2) = 3
     * @return
     * The threading controller
     */
    public static ThreadingController getInstanceLowPriority() {
        return INSTANCE_LOW_PRIORITY;
    }

    public static ThreadingController getInstance() {
        return INSTANCE;
    }

    public static ThreadingController getInstanceHighPriority() {
        return INSTANCE_HIGH_PRIORITY;
    }

    public String getName() {
        return name;
    }

    /**
     * The current number of threads in the core pool
     * @return
     * Integer representing the number of threads in the core pool.
     */
    public Integer getNumThreads()              { return this.numThreads.get(); }

    /**
     * The current priority of this threaded pool.
     * @return
     * The
     */
    public int getPriority() {
        return priority;
    }

    /**
     * The time interval that is being used to determine how often to scale our threads.
     * @return
     * long in millis
     */
    public Long getScaleCheck()                 { return SCALE_CHECK; }

    /**
     * Whether or not the thread-pool is running or if all the threads are currently asleep.
     * @return
     * A boolean representing whether or not the thread-pool is running.
     */
    public boolean isRunning()                  { return this.workingNow.get() > 0; }

    /**
     * The current CPU load measured for by the observer
     * @return
     * Double representing the current CPU load
     */
    public Double getProcessCpuLoad()           { return this.threadingControllerCPUObserver.getCPUPercentUtilization(); }

    /**
     * The last CPU usage that was used to calculate whether or not the thread pool should be adjusted
     * @return
     * Double representing that observation's CPU load
     */
    public Double getLastCPUObservation()       { return this.lastCPUObservation; }

    /**
     * The number of items that are currently executing right now.
     * @return
     * An integer of the number of items executing at this very moment.
     */
    public Integer getWorkingNow()              { return workingNow.get(); }

    /**
     * The class that is being used to provide the CPU load
     * @return
     * The canonical class name that is calculating the CPU usage.
     */
    public String getProcessCpuLoadClass()      { return this.threadingControllerCPUObserver.getClass().getCanonicalName(); }

    public void setThreadingControllerCPUObserver(ThreadingControllerCPUObserver threadingControllerCPUObserver) {
        this.threadingControllerCPUObserver = threadingControllerCPUObserver;
    }

    /**
     * A double representing when the thread-pool will be adjusted if > 10% of the value.
     * Or decreased if the pool is under utilized by 10% of the value.
     * @return
     * Double representing the threshold CPU usage value (percent)
     */
    public Double getScaleThreshold() {
        return scaleThreshold;
    }

    private ThreadingController(final String name, final int startThreadCount, final int maxNumberOfThreads, final int priority) {

        this.name = name;
        this.numThreads = new AtomicInteger(startThreadCount);
        this.maxNumberOfThreads = maxNumberOfThreads;
        this.priority = priority;

        this.threadPoolExecutor = new ThreadPoolExecutor(
                this.numThreads.get(),
                this.numThreads.get(),
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());

        this.threadPoolExecutor.setThreadFactory(new BasicThreadFactory.Builder()
                .priority(this.priority)
                .namingPattern(this.name + "- %d")
                .build());

        this.listeningExecutorService = MoreExecutors.listeningDecorator(this.threadPoolExecutor);
    }

    private class ThreadedCallbackWrapper implements FutureCallback<Object> {

        private final ThreadingControllerCallback callback;

        public ThreadedCallbackWrapper(ThreadingControllerCallback callback) {
            this.callback = callback;
        }

        @Override
        public void onSuccess(Object o) {
            callback.onSuccess(o);
            workingNow.decrementAndGet();
            lock.signal();
        }

        @Override
        public void onFailure(Throwable t) {
            callback.onFailure(t);
            workingNow.decrementAndGet();
            lock.signal();
        }
    }

    synchronized void execute(final Runnable command, final ThreadingControllerCallback callback) {

        this.numberOfObservations.incrementAndGet();
        this.sumOfObservations.addAndGet(this.getProcessCpuLoad());

        if((new Date().getTime() > (SCALE_CHECK + this.lastWorked.get())) && this.numberOfObservations.get() > Math.max(NUM_PROCESSORS/2, 2)) {

            double average = this.sumOfObservations.doubleValue() / this.numberOfObservations.doubleValue();
            this.lastCPUObservation = average;

            /* re-size the shared thread-pool if we aren't under significant stress */
            int currentThreadCount = this.numThreads.get();
            int newThreadCount = this.numThreads.get();

            /* Adjust to keep the processor between 72% & 88% */
            if (average < this.scaleThreshold * .9) {
                /* The processor isn't being worked that hard, we can add the unit here */
                newThreadCount = Math.min(this.maxNumberOfThreads, (newThreadCount + 1));
                if(newThreadCount != currentThreadCount) {
                    LOGGER.info("+++++++ SCALING UP THREAD POOL TO {} THREADS (CPU @ {}) ++++++++", newThreadCount, average);
                }
            } else if (average > this.scaleThreshold * 1.1) {
                newThreadCount = Math.max((newThreadCount - 1), NUM_PROCESSORS);
                if(newThreadCount != currentThreadCount) {
                    LOGGER.info("------- SCALING DOWN THREAD POOL TO {} THREADS (CPU @ {}) --------", newThreadCount, average);
                }
            }

            this.numThreads.set(newThreadCount);

            // wait
            while (this.workingNow.get() >= this.numThreads.get()) {
                try {
                    this.lock.await();
                } catch (InterruptedException e) {
                    /* no operation */
                }
            }

            if(newThreadCount != currentThreadCount) {
                this.threadPoolExecutor.setCorePoolSize(this.numThreads.get());
                this.threadPoolExecutor.setMaximumPoolSize(this.numThreads.get());
            }

            // reset our counters
            this.lastWorked.set(new Date().getTime());
            this.numberOfObservations.set(0);
            this.sumOfObservations.set(0);
        }
        else {
            if(new Date().getTime() > (SCALE_CHECK + this.lastWorked.get())) {
                // not enough observations reset the counters.
                this.lastWorked.set(new Date().getTime());
                this.numberOfObservations.set(0);
                this.sumOfObservations.set(0);
            }

            while (this.workingNow.get() >= this.numThreads.get()) {
                try {
                    this.lock.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        this.workingNow.incrementAndGet();

        Futures.addCallback(this.listeningExecutorService.submit(command), new ThreadedCallbackWrapper(callback));
    }
}


text:
package com.rollbar.web.example.server;

import com.rollbar.api.payload.data.Server;
import com.rollbar.notifier.provider.Provider;

public class ServerProvider implements Provider<Server> {

  @Override
  public Server provide() {
    return new Server.Builder()
        .codeVersion("1.0.0")
        .branch("master")
        .host("localhost")
        .build();
  }
}


text:
module Healthcheck
  class ApiTokens
    WARNING_THRESHOLD = 2.months.to_i
    CRITICAL_THRESHOLD = 1.month.to_i

    QUERY = <<-SQL.freeze
      SELECT tokens.resource_owner_id,
             tokens.application_id,
             tokens.expires_in
      FROM
        (
          SELECT resource_owner_id,
                 application_id,
                 revoked_at,
                 (oauth_access_tokens.expires_in -
                 (unix_timestamp(now()) -
                  unix_timestamp(oauth_access_tokens.created_at))) as expires_in
          FROM oauth_access_tokens
        ) tokens
      INNER JOIN users ON users.id = tokens.resource_owner_id
      WHERE tokens.revoked_at IS NULL
      AND users.email NOT LIKE '%@#{ENV['GOVUK_ENVIRONMENT_NAME']}.publishing.service.gov.uk'
      AND users.api_user = TRUE
      AND tokens.expires_in < #{WARNING_THRESHOLD}
    SQL

    def name
      :api_tokens
    end

    def message
      return "" unless expiring_tokens.any?

      "\n\n#{expiring_tokens.join("\n")}\n\n"
    end

    def status
      return :critical if expiring_tokens.any?(&:critical?)

      return :warning if expiring_tokens.any?

      :ok
    end

    def to_hash
      {
        message: message,
        status: status,
      }
    end

  private

    Record = Struct.new(:user_id, :application_id, :expires_in) do
      def critical?
        expires_in < CRITICAL_THRESHOLD
      end

      def user
        User.find(user_id)
      end

      def application
        Doorkeeper::Application.find(application_id)
      end

      def expires_in_days
        expires_in / 1.day.to_i
      end

      def to_s
        "#{user.name} token for #{application.name} expires in #{expires_in_days} days"
      end
    end

    def expiring_tokens
      @expiring_tokens ||= begin
        records = ActiveRecord::Base.connection.execute(QUERY)
        records.to_a.map { |raw_array| Record.new(*raw_array) }
      end
    end
  end
end


text:
package com.google.android.exoplayer2.audio;

import static com.google.android.exoplayer2.util.Util.castNonNull;

import android.media.AudioTimestamp;
import android.media.AudioTrack;
import android.os.SystemClock;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Util;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

/**
 * Wraps an {@link AudioTrack}, exposing a position based on {@link
 * AudioTrack#getPlaybackHeadPosition()} and {@link AudioTrack#getTimestamp(AudioTimestamp)}.
 *
 *
Call {@link #setAudioTrack(AudioTrack, int, int, int)} to set the audio track to wrap. Call
 * {@link #mayHandleBuffer(long)} if there is input data to write to the track. If it returns false,
 * the audio track position is stabilizing and no data may be written. Call {@link #start()}
 * immediately before calling {@link AudioTrack#play()}. Call {@link #pause()} when pausing the
 * track. Call {@link #handleEndOfStream(long)} when no more data will be written to the track. When
 * the audio track will no longer be used, call {@link #reset()}.
 */
/* package */ final class AudioTrackPositionTracker {

  /** Listener for position tracker events. */
  public interface Listener {

    /**
     * Called when the frame position is too far from the expected frame position.
     *
     * @param audioTimestampPositionFrames The frame position of the last known audio track
     *     timestamp.
     * @param audioTimestampSystemTimeUs The system time associated with the last known audio track
     *     timestamp, in microseconds.
     * @param systemTimeUs The current time.
     * @param playbackPositionUs The current playback head position in microseconds.
     */
    void onPositionFramesMismatch(
        long audioTimestampPositionFrames,
        long audioTimestampSystemTimeUs,
        long systemTimeUs,
        long playbackPositionUs);

    /**
     * Called when the system time associated with the last known audio track timestamp is
     * unexpectedly far from the current time.
     *
     * @param audioTimestampPositionFrames The frame position of the last known audio track
     *     timestamp.
     * @param audioTimestampSystemTimeUs The system time associated with the last known audio track
     *     timestamp, in microseconds.
     * @param systemTimeUs The current time.
     * @param playbackPositionUs The current playback head position in microseconds.
     */
    void onSystemTimeUsMismatch(
        long audioTimestampPositionFrames,
        long audioTimestampSystemTimeUs,
        long systemTimeUs,
        long playbackPositionUs);

    /**
     * Called when the audio track has provided an invalid latency.
     *
     * @param latencyUs The reported latency in microseconds.
     */
    void onInvalidLatency(long latencyUs);

    /**
     * Called when the audio track runs out of data to play.
     *
     * @param bufferSize The size of the sink's buffer, in bytes.
     * @param bufferSizeMs The size of the sink's buffer, in milliseconds, if it is configured for
     *     PCM output. {@link C#TIME_UNSET} if it is configured for encoded audio output, as the
     *     buffered media can have a variable bitrate so the duration may be unknown.
     */
    void onUnderrun(int bufferSize, long bufferSizeMs);
  }

  /** {@link AudioTrack} playback states. */
  @Documented
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({PLAYSTATE_STOPPED, PLAYSTATE_PAUSED, PLAYSTATE_PLAYING})
  private @interface PlayState {}
  /** @see AudioTrack#PLAYSTATE_STOPPED */
  private static final int PLAYSTATE_STOPPED = AudioTrack.PLAYSTATE_STOPPED;
  /** @see AudioTrack#PLAYSTATE_PAUSED */
  private static final int PLAYSTATE_PAUSED = AudioTrack.PLAYSTATE_PAUSED;
  /** @see AudioTrack#PLAYSTATE_PLAYING */
  private static final int PLAYSTATE_PLAYING = AudioTrack.PLAYSTATE_PLAYING;

  /**
   * AudioTrack timestamps are deemed spurious if they are offset from the system clock by more than
   * this amount.
   *
   *
This is a fail safe that should not be required on correctly functioning devices.
   */
  private static final long MAX_AUDIO_TIMESTAMP_OFFSET_US = 5 * C.MICROS_PER_SECOND;

  /**
   * AudioTrack latencies are deemed impossibly large if they are greater than this amount.
   *
   *
This is a fail safe that should not be required on correctly functioning devices.
   */
  private static final long MAX_LATENCY_US = 5 * C.MICROS_PER_SECOND;

  private static final long FORCE_RESET_WORKAROUND_TIMEOUT_MS = 200;

  private static final int MAX_PLAYHEAD_OFFSET_COUNT = 10;
  private static final int MIN_PLAYHEAD_OFFSET_SAMPLE_INTERVAL_US = 30000;
  private static final int MIN_LATENCY_SAMPLE_INTERVAL_US = 500000;

  private final Listener listener;
  private final long[] playheadOffsets;

  @Nullable private AudioTrack audioTrack;
  private int outputPcmFrameSize;
  private int bufferSize;
  @Nullable private AudioTimestampPoller audioTimestampPoller;
  private int outputSampleRate;
  private boolean needsPassthroughWorkarounds;
  private long bufferSizeUs;

  private long smoothedPlayheadOffsetUs;
  private long lastPlayheadSampleTimeUs;

  @Nullable private Method getLatencyMethod;
  private long latencyUs;
  private boolean hasData;

  private boolean isOutputPcm;
  private long lastLatencySampleTimeUs;
  private long lastRawPlaybackHeadPosition;
  private long rawPlaybackHeadWrapCount;
  private long passthroughWorkaroundPauseOffset;
  private int nextPlayheadOffsetIndex;
  private int playheadOffsetCount;
  private long stopTimestampUs;
  private long forceResetWorkaroundTimeMs;
  private long stopPlaybackHeadPosition;
  private long endPlaybackHeadPosition;

  /**
   * Creates a new audio track position tracker.
   *
   * @param listener A listener for position tracking events.
   */
  public AudioTrackPositionTracker(Listener listener) {
    this.listener = Assertions.checkNotNull(listener);
    if (Util.SDK_INT >= 18) {
      try {
        getLatencyMethod = AudioTrack.class.getMethod("getLatency", (Class<?>[]) null);
      } catch (NoSuchMethodException e) {
        // There's no guarantee this method exists. Do nothing.
      }
    }
    playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT];
  }

  /**
   * Sets the {@link AudioTrack} to wrap. Subsequent method calls on this instance relate to this
   * track's position, until the next call to {@link #reset()}.
   *
   * @param audioTrack The audio track to wrap.
   * @param outputEncoding The encoding of the audio track.
   * @param outputPcmFrameSize For PCM output encodings, the frame size. The value is ignored
   *     otherwise.
   * @param bufferSize The audio track buffer size in bytes.
   */
  public void setAudioTrack(
      AudioTrack audioTrack,
      @C.Encoding int outputEncoding,
      int outputPcmFrameSize,
      int bufferSize) {
    this.audioTrack = audioTrack;
    this.outputPcmFrameSize = outputPcmFrameSize;
    this.bufferSize = bufferSize;
    audioTimestampPoller = new AudioTimestampPoller(audioTrack);
    outputSampleRate = audioTrack.getSampleRate();
    needsPassthroughWorkarounds = needsPassthroughWorkarounds(outputEncoding);
    isOutputPcm = Util.isEncodingLinearPcm(outputEncoding);
    bufferSizeUs = isOutputPcm ? framesToDurationUs(bufferSize / outputPcmFrameSize) : C.TIME_UNSET;
    lastRawPlaybackHeadPosition = 0;
    rawPlaybackHeadWrapCount = 0;
    passthroughWorkaroundPauseOffset = 0;
    hasData = false;
    stopTimestampUs = C.TIME_UNSET;
    forceResetWorkaroundTimeMs = C.TIME_UNSET;
    latencyUs = 0;
  }

  public long getCurrentPositionUs(boolean sourceEnded) {
    if (Assertions.checkNotNull(this.audioTrack).getPlayState() == PLAYSTATE_PLAYING) {
      maybeSampleSyncParams();
    }

    // If the device supports it, use the playback timestamp from AudioTrack.getTimestamp.
    // Otherwise, derive a smoothed position by sampling the track's frame position.
    long systemTimeUs = System.nanoTime() / 1000;
    AudioTimestampPoller audioTimestampPoller = Assertions.checkNotNull(this.audioTimestampPoller);
    if (audioTimestampPoller.hasTimestamp()) {
      // Calculate the speed-adjusted position using the timestamp (which may be in the future).
      long timestampPositionFrames = audioTimestampPoller.getTimestampPositionFrames();
      long timestampPositionUs = framesToDurationUs(timestampPositionFrames);
      if (!audioTimestampPoller.isTimestampAdvancing()) {
        return timestampPositionUs;
      }
      long elapsedSinceTimestampUs = systemTimeUs - audioTimestampPoller.getTimestampSystemTimeUs();
      return timestampPositionUs + elapsedSinceTimestampUs;
    } else {
      long positionUs;
      if (playheadOffsetCount == 0) {
        // The AudioTrack has started, but we don't have any samples to compute a smoothed position.
        positionUs = getPlaybackHeadPositionUs();
      } else {
        // getPlaybackHeadPositionUs() only has a granularity of ~20 ms, so we base the position off
        // the system clock (and a smoothed offset between it and the playhead position) so as to
        // prevent jitter in the reported positions.
        positionUs = systemTimeUs + smoothedPlayheadOffsetUs;
      }
      if (!sourceEnded) {
        positionUs -= latencyUs;
      }
      return positionUs;
    }
  }

  /** Starts position tracking. Must be called immediately before {@link AudioTrack#play()}. */
  public void start() {
    Assertions.checkNotNull(audioTimestampPoller).reset();
  }

  /** Returns whether the audio track is in the playing state. */
  public boolean isPlaying() {
    return Assertions.checkNotNull(audioTrack).getPlayState() == PLAYSTATE_PLAYING;
  }

  /**
   * Checks the state of the audio track and returns whether the caller can write data to the track.
   * Notifies {@link Listener#onUnderrun(int, long)} if the track has underrun.
   *
   * @param writtenFrames The number of frames that have been written.
   * @return Whether the caller can write data to the track.
   */
  public boolean mayHandleBuffer(long writtenFrames) {
    @PlayState int playState = Assertions.checkNotNull(audioTrack).getPlayState();
    if (needsPassthroughWorkarounds) {
      // An AC-3 audio track continues to play data written while it is paused. Stop writing so its
      // buffer empties. See [Internal: b/18899620].
      if (playState == PLAYSTATE_PAUSED) {
        // We force an underrun to pause the track, so don't notify the listener in this case.
        hasData = false;
        return false;
      }

      // A new AC-3 audio track's playback position continues to increase from the old track's
      // position for a short time after is has been released. Avoid writing data until the playback
      // head position actually returns to zero.
      if (playState == PLAYSTATE_STOPPED && getPlaybackHeadPosition() == 0) {
        return false;
      }
    }

    boolean hadData = hasData;
    hasData = hasPendingData(writtenFrames);
    if (hadData && !hasData && playState != PLAYSTATE_STOPPED && listener != null) {
      listener.onUnderrun(bufferSize, C.usToMs(bufferSizeUs));
    }

    return true;
  }

  /**
   * Returns an estimate of the number of additional bytes that can be written to the audio track's
   * buffer without running out of space.
   *
   *
May only be called if the output encoding is one of the PCM encodings.
   *
   * @param writtenBytes The number of bytes written to the audio track so far.
   * @return An estimate of the number of bytes that can be written.
   */
  public int getAvailableBufferSize(long writtenBytes) {
    int bytesPending = (int) (writtenBytes - (getPlaybackHeadPosition() * outputPcmFrameSize));
    return bufferSize - bytesPending;
  }

  /** Returns whether the track is in an invalid state and must be recreated. */
  public boolean isStalled(long writtenFrames) {
    return forceResetWorkaroundTimeMs != C.TIME_UNSET
        && writtenFrames > 0
        && SystemClock.elapsedRealtime() - forceResetWorkaroundTimeMs
            >= FORCE_RESET_WORKAROUND_TIMEOUT_MS;
  }

  /**
   * Records the writing position at which the stream ended, so that the reported position can
   * continue to increment while remaining data is played out.
   *
   * @param writtenFrames The number of frames that have been written.
   */
  public void handleEndOfStream(long writtenFrames) {
    stopPlaybackHeadPosition = getPlaybackHeadPosition();
    stopTimestampUs = SystemClock.elapsedRealtime() * 1000;
    endPlaybackHeadPosition = writtenFrames;
  }

  /**
   * Returns whether the audio track has any pending data to play out at its current position.
   *
   * @param writtenFrames The number of frames written to the audio track.
   * @return Whether the audio track has any pending data to play out.
   */
  public boolean hasPendingData(long writtenFrames) {
    return writtenFrames > getPlaybackHeadPosition()
        || forceHasPendingData();
  }

  /**
   * Pauses the audio track position tracker, returning whether the audio track needs to be paused
   * to cause playback to pause. If {@code false} is returned the audio track will pause without
   * further interaction, as the end of stream has been handled.
   */
  public boolean pause() {
    resetSyncParams();
    if (stopTimestampUs == C.TIME_UNSET) {
      // The audio track is going to be paused, so reset the timestamp poller to ensure it doesn't
      // supply an advancing position.
      Assertions.checkNotNull(audioTimestampPoller).reset();
      return true;
    }
    // We've handled the end of the stream already, so there's no need to pause the track.
    return false;
  }

  /**
   * Resets the position tracker. Should be called when the audio track previous passed to {@link
   * #setAudioTrack(AudioTrack, int, int, int)} is no longer in use.
   */
  public void reset() {
    resetSyncParams();
    audioTrack = null;
    audioTimestampPoller = null;
  }

  private void maybeSampleSyncParams() {
    long playbackPositionUs = getPlaybackHeadPositionUs();
    if (playbackPositionUs == 0) {
      // The AudioTrack hasn't output anything yet.
      return;
    }
    long systemTimeUs = System.nanoTime() / 1000;
    if (systemTimeUs - lastPlayheadSampleTimeUs >= MIN_PLAYHEAD_OFFSET_SAMPLE_INTERVAL_US) {
      // Take a new sample and update the smoothed offset between the system clock and the playhead.
      playheadOffsets[nextPlayheadOffsetIndex] = playbackPositionUs - systemTimeUs;
      nextPlayheadOffsetIndex = (nextPlayheadOffsetIndex + 1) % MAX_PLAYHEAD_OFFSET_COUNT;
      if (playheadOffsetCount < MAX_PLAYHEAD_OFFSET_COUNT) {
        playheadOffsetCount++;
      }
      lastPlayheadSampleTimeUs = systemTimeUs;
      smoothedPlayheadOffsetUs = 0;
      for (int i = 0; i < playheadOffsetCount; i++) {
        smoothedPlayheadOffsetUs += playheadOffsets[i] / playheadOffsetCount;
      }
    }

    if (needsPassthroughWorkarounds) {
      // Don't sample the timestamp and latency if this is an AC-3 passthrough AudioTrack on
      // platform API versions 21/22, as incorrect values are returned. See [Internal: b/21145353].
      return;
    }

    maybePollAndCheckTimestamp(systemTimeUs, playbackPositionUs);
    maybeUpdateLatency(systemTimeUs);
  }

  private void maybePollAndCheckTimestamp(long systemTimeUs, long playbackPositionUs) {
    AudioTimestampPoller audioTimestampPoller = Assertions.checkNotNull(this.audioTimestampPoller);
    if (!audioTimestampPoller.maybePollTimestamp(systemTimeUs)) {
      return;
    }

    // Perform sanity checks on the timestamp and accept/reject it.
    long audioTimestampSystemTimeUs = audioTimestampPoller.getTimestampSystemTimeUs();
    long audioTimestampPositionFrames = audioTimestampPoller.getTimestampPositionFrames();
    if (Math.abs(audioTimestampSystemTimeUs - systemTimeUs) > MAX_AUDIO_TIMESTAMP_OFFSET_US) {
      listener.onSystemTimeUsMismatch(
          audioTimestampPositionFrames,
          audioTimestampSystemTimeUs,
          systemTimeUs,
          playbackPositionUs);
      audioTimestampPoller.rejectTimestamp();
    } else if (Math.abs(framesToDurationUs(audioTimestampPositionFrames) - playbackPositionUs)
        > MAX_AUDIO_TIMESTAMP_OFFSET_US) {
      listener.onPositionFramesMismatch(
          audioTimestampPositionFrames,
          audioTimestampSystemTimeUs,
          systemTimeUs,
          playbackPositionUs);
      audioTimestampPoller.rejectTimestamp();
    } else {
      audioTimestampPoller.acceptTimestamp();
    }
  }

  private void maybeUpdateLatency(long systemTimeUs) {
    if (isOutputPcm
        && getLatencyMethod != null
        && systemTimeUs - lastLatencySampleTimeUs >= MIN_LATENCY_SAMPLE_INTERVAL_US) {
      try {
        // Compute the audio track latency, excluding the latency due to the buffer (leaving
        // latency due to the mixer and audio hardware driver).
        latencyUs =
            castNonNull((Integer) getLatencyMethod.invoke(Assertions.checkNotNull(audioTrack)))
                    * 1000L
                - bufferSizeUs;
        // Sanity check that the latency is non-negative.
        latencyUs = Math.max(latencyUs, 0);
        // Sanity check that the latency isn't too large.
        if (latencyUs > MAX_LATENCY_US) {
          listener.onInvalidLatency(latencyUs);
          latencyUs = 0;
        }
      } catch (Exception e) {
        // The method existed, but doesn't work. Don't try again.
        getLatencyMethod = null;
      }
      lastLatencySampleTimeUs = systemTimeUs;
    }
  }

  private long framesToDurationUs(long frameCount) {
    return (frameCount * C.MICROS_PER_SECOND) / outputSampleRate;
  }

  private void resetSyncParams() {
    smoothedPlayheadOffsetUs = 0;
    playheadOffsetCount = 0;
    nextPlayheadOffsetIndex = 0;
    lastPlayheadSampleTimeUs = 0;
  }

  /**
   * If passthrough workarounds are enabled, pausing is implemented by forcing the AudioTrack to
   * underrun. In this case, still behave as if we have pending data, otherwise writing won't
   * resume.
   */
  private boolean forceHasPendingData() {
    return needsPassthroughWorkarounds
        && Assertions.checkNotNull(audioTrack).getPlayState() == AudioTrack.PLAYSTATE_PAUSED
        && getPlaybackHeadPosition() == 0;
  }

  /**
   * Returns whether to work around problems with passthrough audio tracks. See [Internal:
   * b/18899620, b/19187573, b/21145353].
   */
  private static boolean needsPassthroughWorkarounds(@C.Encoding int outputEncoding) {
    return Util.SDK_INT < 23
        && (outputEncoding == C.ENCODING_AC3 || outputEncoding == C.ENCODING_E_AC3);
  }

  private long getPlaybackHeadPositionUs() {
    return framesToDurationUs(getPlaybackHeadPosition());
  }

  /**
   * {@link AudioTrack#getPlaybackHeadPosition()} returns a value intended to be interpreted as an
   * unsigned 32 bit integer, which also wraps around periodically. This method returns the playback
   * head position as a long that will only wrap around if the value exceeds {@link Long#MAX_VALUE}
   * (which in practice will never happen).
   *
   * @return The playback head position, in frames.
   */
  private long getPlaybackHeadPosition() {
    AudioTrack audioTrack = Assertions.checkNotNull(this.audioTrack);
    if (stopTimestampUs != C.TIME_UNSET) {
      // Simulate the playback head position up to the total number of frames submitted.
      long elapsedTimeSinceStopUs = (SystemClock.elapsedRealtime() * 1000) - stopTimestampUs;
      long framesSinceStop = (elapsedTimeSinceStopUs * outputSampleRate) / C.MICROS_PER_SECOND;
      return Math.min(endPlaybackHeadPosition, stopPlaybackHeadPosition + framesSinceStop);
    }

    int state = audioTrack.getPlayState();
    if (state == PLAYSTATE_STOPPED) {
      // The audio track hasn't been started.
      return 0;
    }

    long rawPlaybackHeadPosition = 0xFFFFFFFFL & audioTrack.getPlaybackHeadPosition();
    if (needsPassthroughWorkarounds) {
      // Work around an issue with passthrough/direct AudioTracks on platform API versions 21/22
      // where the playback head position jumps back to zero on paused passthrough/direct audio
      // tracks. See [Internal: b/19187573].
      if (state == PLAYSTATE_PAUSED && rawPlaybackHeadPosition == 0) {
        passthroughWorkaroundPauseOffset = lastRawPlaybackHeadPosition;
      }
      rawPlaybackHeadPosition += passthroughWorkaroundPauseOffset;
    }

    if (Util.SDK_INT <= 29) {
      if (rawPlaybackHeadPosition == 0
          && lastRawPlaybackHeadPosition > 0
          && state == PLAYSTATE_PLAYING) {
        // If connecting a Bluetooth audio device fails, the AudioTrack may be left in a state
        // where its Java API is in the playing state, but the native track is stopped. When this
        // happens the playback head position gets stuck at zero. In this case, return the old
        // playback head position and force the track to be reset after
        // {@link #FORCE_RESET_WORKAROUND_TIMEOUT_MS} has elapsed.
        if (forceResetWorkaroundTimeMs == C.TIME_UNSET) {
          forceResetWorkaroundTimeMs = SystemClock.elapsedRealtime();
        }
        return lastRawPlaybackHeadPosition;
      } else {
        forceResetWorkaroundTimeMs = C.TIME_UNSET;
      }
    }

    if (lastRawPlaybackHeadPosition > rawPlaybackHeadPosition) {
      // The value must have wrapped around.
      rawPlaybackHeadWrapCount++;
    }
    lastRawPlaybackHeadPosition = rawPlaybackHeadPosition;
    return rawPlaybackHeadPosition + (rawPlaybackHeadWrapCount << 32);
  }
}


text:
{% assign rbrace = "}" %}
{% assign rbrace2 = rbrace | append: rbrace %}
{% assign lbrace = "{" %}

            {{ include.name | replace: "[]", "[0]"}}={{ include.defaultValue }}

                {{ include.description
                    | replace: "
", "
"
                    | replace: "
", "
"
                    | replace: "@code", ""
                    | replace: "@value", ""
                    | replace: "@deprecation", "Deprecation:"
                    | replace: "@deprecated", "Deprecation:"
                    | replace: "@link", ""
                    | replace: rbrace2, rbrace
                    | replace: "<", "<"
                    | replace: ">", ">"
                }}

            {% if include.duration %}

 This settings supports the
                java.time.Duration syntax <sup data-bs-toggle="tooltip" data-bs-placment="top" data-bs-html="true" title="
The format of the value will be PTnHnMnS, where n is the relevant hours, minutes or seconds part of the duration. Any fractional seconds are placed after a decimal point in the seconds section. If a section has a zero value, it is omitted. The hours, minutes and seconds will all have the same sign. Example values
                    could be in the form of PT20S, PT15M, PT10H, PT6D, P2DT3H4M.
                    If the value is set to 0 or never, the duration will be set to zero. If the value is blank, set to -1,
                    or infinite, the value will effectively represent an unending duration.
">[?].

            {% endif %}

            {% if include.expressionLanguage %}

 This setting supports the Spring Expression Language.

            {% endif %}

            {% if include.owner.size > 0 %}

 {{ include.owner }}.

            {% endif %}

        {% if include.deprecationLevel.size > 0 %}

 Deprecation status is {{ include.deprecationLevel }}
                {% if include.deprecationReplacement.size > 0 %}
                    with a replacement setting: {{ include.deprecationReplacement | default: "N/A" }}.
                {% else %}
                    without a replacement setting.
                {% endif %}

        {% endif %}


text:
package org.apache.jena.atlas.io ;

import org.junit.Test ;
import static org.junit.Assert.* ;

public class TestIndentedWriter {

    @Test
    public void write01() {
        try (IndentedLineBuffer b = new IndentedLineBuffer()) {
            b.print("hell") ;
            b.print("o") ;
            assertEquals("hello", b.asString()) ;
        }
    }

    @Test
    public void write02() {
        try (IndentedLineBuffer b = new IndentedLineBuffer()) {
            b.incIndent() ;
            b.print("hell") ;
            b.print("o") ;
            b.decIndent() ;
            assertEquals("  hello", b.asString()) ;
        }
    }

    @Test
    public void write03() {
        try (IndentedLineBuffer b = new IndentedLineBuffer()) {
            b.incIndent() ;
            b.printf("0x%04X", 1) ;
            b.println() ;
            b.print("XX") ;
            b.decIndent() ;
            assertEquals("  0x0001\n  XX", b.asString()) ;
        }
    }

    @Test
    public void write04() {
        try (IndentedLineBuffer b = new IndentedLineBuffer()) {
            b.setLineNumbers(true);
            b.setNumberWidth(5);
            b.println("ABCD") ;
            b.print("XYZ") ;
            assertEquals("    1 ABCD\n    2 XYZ", b.asString()) ;
        }
    }

    @Test
    public void write05() {
        try (IndentedLineBuffer b = new IndentedLineBuffer()) {
            b.setLineNumbers(true);
            b.println("ABCD") ;
            b.println("XYZ") ;
            assertEquals("  1 ABCD\n  2 XYZ\n", b.asString()) ;
        }
    }

    @Test
    public void write06() {
        try (IndentedLineBuffer b = new IndentedLineBuffer()) {
            b.setLinePrefix("@.");
            b.println("ABCD") ;
            b.print("XYZ") ;
            assertEquals("@.ABCD\n@.XYZ", b.asString()) ;
        }
    }

    @Test
    public void write07() {
        try (IndentedLineBuffer b = new IndentedLineBuffer()) {
            b.setLinePrefix("@.");
            b.println("ABCD") ;
            assertEquals("@.ABCD\n", b.asString()) ;
        }
    }
}


text:
package org.postgresql.test.socketfactory;

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

import org.postgresql.PGProperty;
import org.postgresql.test.TestUtil;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.Connection;
import java.util.Properties;

public class SocketFactoryTestSuite {

  private static final String STRING_ARGUMENT = "name of a socket";

  private Connection _conn;

  @Before
  public void setUp() throws Exception {
    Properties properties = new Properties();
    properties.put(PGProperty.SOCKET_FACTORY.getName(), CustomSocketFactory.class.getName());
    properties.put(PGProperty.SOCKET_FACTORY_ARG.getName(), STRING_ARGUMENT);
    _conn = TestUtil.openDB(properties);
  }

  @After
  public void tearDown() throws Exception {
    TestUtil.closeDB(_conn);
  }

  /**
   * Test custom socket factory.
   */
  @Test
  public void testDatabaseMetaData() throws Exception {
    assertNotNull("Custom socket factory not null", CustomSocketFactory.getInstance());
    assertEquals(STRING_ARGUMENT, CustomSocketFactory.getInstance().getArgument());
    assertEquals(1, CustomSocketFactory.getInstance().getSocketCreated());
  }

}


text:
using System;
using System.Diagnostics.Contracts;
using System.Management.Automation;
using biz.dfch.CS.Testing.PowerShell;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;

namespace biz.dfch.CS.PowerShell.Commons.Tests
{
    [Cmdlet(VerbsDiagnostic.Test, "DefaultValues")]
    public class ArbitraryCmdlet : PsCmdletBase
    {
        public const int INT_PARAMETER1_DEFAULT_VALUE = 42;
        public const string STRING_PARAMETER1_DEFAULT_VALUE = "arbitrary-string-default-value1";
        public const string STRING_PARAMETER2_DEFAULT_VALUE = "arbitrary-string-default-value2";
        public const bool SWITCH_PARAMETER_DEFAULT_VALUE = true;

        [Parameter(Mandatory = true)]
        public int TestCase { get; set; }

        [Parameter(Mandatory = false)]
        [PSDefaultValue(Value = INT_PARAMETER1_DEFAULT_VALUE)]
        public int IntParameter1 { get; set; }

        [Parameter(Mandatory = false)]
        [PSDefaultValue(Value = STRING_PARAMETER1_DEFAULT_VALUE)]
        public string StringParameter1 { get; set; }

        [Parameter(Mandatory = true)]
        [PSDefaultValue(Value = STRING_PARAMETER2_DEFAULT_VALUE)]
        public string StringParameter2 { get; set; }

        [Parameter(Mandatory = false)]
        [PSDefaultValue(Value = true)]
        public SwitchParameter SwitchParameter { get; set; }

        protected override void ProcessRecord()
        {
            switch (TestCase)
            {
                case 1:
                    Contract.Assert(STRING_PARAMETER1_DEFAULT_VALUE == StringParameter1);
                    break;
                case 2:
                    Contract.Assert(STRING_PARAMETER1_DEFAULT_VALUE != StringParameter1);
                    break;
                case 3:
                    Contract.Assert(SwitchParameter == true);
                    break;
                case 4:
                    Contract.Assert(SwitchParameter == false);
                    break;
                default:
                    var invalidTestCase = false;
                    Contract.Assert(invalidTestCase);
                    break;
            }

            base.ProcessRecord();
        }
    }

    [TestClass]
    public class PsCmdletBaseTest
    {
        [TestMethod]
        public void TestCase1()
        {
            var sut = typeof(ArbitraryCmdlet);

            var parameters = "-TestCase 1 -StringParameter2 'tralala';";
            var result = PsCmdletAssert.Invoke(sut, parameters);
            Assert.IsNotNull(result);
            Assert.AreEqual(0, result.Count);
        }

        [TestMethod]
        public void TestCase2()
        {
            var sut = typeof(ArbitraryCmdlet);

            var parameters = "-TestCase 2 -StringParameter1 'some-string' -StringParameter2 'tralala';";
            var result = PsCmdletAssert.Invoke(sut, parameters);
            Assert.IsNotNull(result);
            Assert.AreEqual(0, result.Count);
        }

        [TestMethod]
        public void TestCase3()
        {
            var sut = typeof(ArbitraryCmdlet);

            var parameters = "-TestCase 3 -StringParameter2 'tralala';";
            var result = PsCmdletAssert.Invoke(sut, parameters);
            Assert.IsNotNull(result);
            Assert.AreEqual(0, result.Count);
        }

        [TestMethod]
        public void TestCase4()
        {
            var sut = typeof(ArbitraryCmdlet);

            var parameters = "-TestCase 4 -SwitchParameter:$false -StringParameter2 'tralala';";
            var result = PsCmdletAssert.Invoke(sut, parameters);
            Assert.IsNotNull(result);
            Assert.AreEqual(0, result.Count);
        }
    }
}


text:
<phpunit>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./src</directory>
            <exclude>
                <directory suffix=".php">Exception</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>


text: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">


text:
'use strict';

angular
.module('phoneDMServices', [])
.service('DeviceManager', ['Phone',
  function(Phone) {
    var allPhones = [];
    var initializeFlag = true;
    return {
      getAllPhones: function() {
        if (initializeFlag) {
          var tempPhoneList = Phone.query(function() {
            for (var i=0; i<tempPhoneList.length; i++) {
              allPhones.push({id: tempPhoneList[i].id, name: tempPhoneList[i].name,
                              snippet: tempPhoneList[i].snippet, age: tempPhoneList[i].age,
                              imageUrl: tempPhoneList[i].imageUrl});
            }
          });
          initializeFlag = false;
        }
        return allPhones;
      },
      addPhone: function(newPhone) {
        allPhones.push(newPhone);
        return allPhones;
      },
      findPhoneById: function(phoneId) {
        var phoneFound = null;
        for(var i = 0; i < allPhones.length; i++) {
          if (allPhones[i].id == phoneId) {
            phoneFound = allPhones[i];
            break;
          }
        }
        return phoneFound;
      },
      savePhone: function(editedPhone) {
        var phoneUpdated = false;
        for(var i = 0; i < allPhones.length; i++) {
          if (allPhones[i].id == editedPhone.id) {
            allPhones[i].name = editedPhone.name;
            allPhones[i].snippet = editedPhone.snippet;
            allPhones[i].age = editedPhone.age;
            phoneUpdated = true;
            break;
          }
        }
        return phoneUpdated;
      },
      deletePhone: function(phoneId) {
        var phoneDeleted = false;
        for(var i = 0; i < allPhones.length; i++) {
          if (allPhones[i].id == phoneId) {
            allPhones.splice(i,1);
            phoneDeleted = true;
            break;
          }
        }
        return phoneDeleted;
      }
    };
  }]);


text:
local AceGUI = LibStub("AceGUI-3.0")

-------------
-- Widgets --
-------------
--[[
	Widgets must provide the following functions
		Acquire() - Called when the object is aquired, should set everything to a default hidden state
		Release() - Called when the object is Released, should remove any anchors and hide the Widget

	And the following members
		frame - the frame or derivitive object that will be treated as the widget for size and anchoring purposes
		type - the type of the object, same as the name given to :RegisterWidget()

	Widgets contain a table called userdata, this is a safe place to store data associated with the wigdet
	It will be cleared automatically when a widget is released
	Placing values directly into a widget object should be avoided

	If the Widget can act as a container for other Widgets the following
		content - frame or derivitive that children will be anchored to

	The Widget can supply the following Optional Members

]]

----------------------------------
-- Blizzard Options Group	    --
----------------------------------
--[[
	Group Designed to be added to the bliz interface options panel
]]

do
	local Type = "BlizOptionsGroup"
	local Version = 5

	local function Acquire(self)

	end

	local function Release(self)
		self.frame:ClearAllPoints()
		self.frame:Hide()
		self:SetName()
	end

	local function okay(this)
		this.obj:Fire("okay")
	end

	local function cancel(this)
		this.obj:Fire("cancel")
	end

	local function defaults(this)
		this.obj:Fire("defaults")
	end

	local function SetName(self, name, parent)
		self.frame.name = name
		self.frame.parent = parent
	end

	local function OnShow(this)
		this.obj:Fire("OnShow")
	end

	local function OnHide(this)
		this.obj:Fire("OnHide")
	end

	local function OnWidthSet(self, width)
		local content = self.content
		local contentwidth = width - 63
		if contentwidth < 0 then
			contentwidth = 0
		end
		content:SetWidth(contentwidth)
		content.width = contentwidth
	end

	local function OnHeightSet(self, height)
		local content = self.content
		local contentheight = height - 26
		if contentheight < 0 then
			contentheight = 0
		end
		content:SetHeight(contentheight)
		content.height = contentheight
	end

	local function SetTitle(self, title)
		local content = self.content
		content:ClearAllPoints()
		if not title or title == "" then
			content:SetPoint("TOPLEFT",self.frame,"TOPLEFT",15,-10)
			self.label:SetText("")
		else
			content:SetPoint("TOPLEFT",self.frame,"TOPLEFT",15,-40)
			self.label:SetText(title)
		end
		content:SetPoint("BOTTOMRIGHT",self.frame,"BOTTOMRIGHT",-10,10)
	end

	local function Constructor()
		local frame = CreateFrame("Frame")
		local self = {}
		self.type = Type

		self.Release = Release
		self.Acquire = Acquire
		self.frame = frame
		self.SetName = SetName

		self.OnWidthSet = OnWidthSet
		self.OnHeightSet = OnHeightSet
		self.SetTitle = SetTitle

		frame.obj = self
		frame.okay = okay
		frame.cancel = cancel
		frame.defaults = defaults

		frame:Hide()
		frame:SetScript("OnHide",OnHide)
		frame:SetScript("OnShow",OnShow)

		local label = frame:CreateFontString(nil,"OVERLAY","GameFontNormalLarge")
		self.label = label
		label:SetPoint("TOPLEFT", frame, "TOPLEFT", 15, -15)
		label:SetPoint("BOTTOMRIGHT", frame, "TOPRIGHT", 10, -45)
		label:SetJustifyH("LEFT")
		label:SetJustifyV("TOP")

		--Container Support
		local content = CreateFrame("Frame",nil,frame)
		self.content = content
		content.obj = self
		content:SetPoint("TOPLEFT",frame,"TOPLEFT",15,-10)
		content:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-10,10)

		AceGUI:RegisterAsContainer(self)
		return self
	end

	AceGUI:RegisterWidgetType(Type,Constructor,Version)
end


text:
"""Request body validating middleware for OpenStack Identity resources."""

from keystone.common.validation import validators

def lazy_validate(request_body_schema, resource_to_validate):
    """A non-decorator way to validate a request, to be used inline.

    :param request_body_schema: a schema to validate the resource reference
    :param resource_to_validate: dictionary to validate
    :raises keystone.exception.ValidationError: if `resource_to_validate` is
            None. (see wrapper method below).
    :raises TypeError: at decoration time when the expected resource to
                       validate isn't found in the decorated method's
                       signature

    """
    schema_validator = validators.SchemaValidator(request_body_schema)
    schema_validator.validate(resource_to_validate)

def nullable(property_schema):
    """Clone a property schema into one that is nullable.

    :param dict property_schema: schema to clone into a nullable schema
    :returns: a new dict schema
    """
    # TODO(dstanek): deal with the case where type is already a list; we don't
    #                do that yet so I'm not wasting time on it
    new_schema = property_schema.copy()
    new_schema['type'] = [property_schema['type'], 'null']
    # NOTE(kmalloc): If enum is specified (such as our boolean case) ensure we
    # add null to the enum as well so that null can be passed/validated as
    # expected. Without adding to the enum, null will not validate as enum is
    # explicitly listing valid values. According to the JSON Schema
    # specification, the values must be unique in the enum array.
    if 'enum' in new_schema and None not in new_schema['enum']:
        # In the enum the 'null' is NoneType
        new_schema['enum'].append(None)
    return new_schema


text:
require 'jsduck/logger'

module JsDuck

  # Helper for JsDuck::Class for indexing its members.
  #
  # While indexing the members of a class it accesses the MembersIndex
  # instances of parent and mixins of that class through the
  # #members_index accessor.  This isn't the nicest approach, but
  # better than having all of this functionality inside the
  # JsDuck::Class itself.
  class MembersIndex
    def initialize(cls)
      @cls = cls
      @map_by_id = nil
      @global_map_by_id = nil
      @global_map_by_name = nil
    end

    # Returns hash of all members by name (including inherited ones)
    def global_by_name
      unless @global_map_by_name
        @global_map_by_name = {}

        global_by_id.each_pair do |id, m|
          @global_map_by_name[m[:name]] = [] unless @global_map_by_name[m[:name]]
          @global_map_by_name[m[:name]] << m
        end
      end

      @global_map_by_name
    end

    # Returns array of all members (including inherited ones)
    def all_global
      global_by_id.values
    end

    # Returns array of all local members (excludes inherited ones)
    def all_local
      local_by_id.values.reject {|m| m[:hide] }
    end

    # Clears the search cache.
    #
    # Using this degrades performance. It's currently triggered just
    # once after InheritDoc process is run. Avoid using it in other
    # places.
    def invalidate!
      @map_by_id = nil
      @global_map_by_id = nil
      @global_map_by_name = nil
    end

    protected

    # Returns hash of all members by ID (including inherited ones)
    def global_by_id
      unless @global_map_by_id
        # Make copy of parent class members.
        # Otherwise we'll be merging directly into parent class.
        @global_map_by_id = @cls.parent ? @cls.parent.members_index.global_by_id.clone : {}

        @cls.mixins.each do |mix|
          merge!(@global_map_by_id, mix.members_index.global_by_id)
        end

        # Exclude all non-inheritable static members
        @global_map_by_id.delete_if {|id, m| m[:static] && !m[:inheritable] }

        merge!(@global_map_by_id, local_by_id)
      end

      @global_map_by_id
    end

    # Returns hash of local members by ID (no inherited members)
    def local_by_id
      unless @map_by_id
        @map_by_id = {}

        @cls[:members].each do |m|
          @map_by_id[m[:id]] = m
        end
      end

      @map_by_id
    end

    private

    # merges second members hash into first one
    def merge!(hash1, hash2)
      hash2.each_pair do |name, m|
        if m[:hide]
          if hash1[name]
            hash1.delete(name)
          else
            msg = "@hide used but #{m[:tagname]} #{m[:name]} not found in parent class"
            Logger.warn(:hide, msg, m[:files][0])
          end
        else
          if hash1[name]
            store_overrides(hash1[name], m)
          end
          hash1[name] = m
        end
      end
    end

    # Invoked when merge! finds two members with the same name.
    # New member always overrides the old, but inside new we keep
    # a list of members it overrides.  Normally one member will
    # override one other member, but a member from mixin can override
    # multiple members - although there's not a single such case in
    # ExtJS, we have to handle it.
    #
    # Every overridden member is listed just once.
    def store_overrides(old, new)
      # Sometimes a class is included multiple times (like Ext.Base)
      # resulting in its members overriding themselves.  Because of
      # this, ignore overriding itself.
      if new[:owner] != old[:owner]
        new[:overrides] = [] unless new[:overrides]
        unless new[:overrides].any? {|m| m[:owner] == old[:owner] }
          # Make a copy of the important properties for us.  We can't
          # just push the actual `old` member itself, because there
          # can be circular overrides (notably with Ext.Base), which
          # will result in infinite loop when we try to convert our
          # class into JSON.
          new[:overrides] << {
            :name => old[:name],
            :owner => old[:owner],
          }
        end
      end
    end

  end

end


text:
<md-content layout-padding>
  <label>Please select the app to test</label>
</md-content>


text:
#include "cytypes.h"
#include "Pin_SS.h"

/* APIs are not generated for P15[7:6] on PSoC 5 */
#if !(CY_PSOC5A &&\
	 Pin_SS__PORT == 15 && ((Pin_SS__MASK & 0xC0) != 0))

/*******************************************************************************
* Function Name: Pin_SS_Write
********************************************************************************
*
* Summary:
*  Assign a new value to the digital port's data output register.
*
* Parameters:
*  prtValue:  The value to be assigned to the Digital Port.
*
* Return:
*  None
*
*******************************************************************************/
void Pin_SS_Write(uint8 value)
{
    uint8 staticBits = (Pin_SS_DR & (uint8)(~Pin_SS_MASK));
    Pin_SS_DR = staticBits | ((uint8)(value << Pin_SS_SHIFT) & Pin_SS_MASK);
}

/*******************************************************************************
* Function Name: Pin_SS_SetDriveMode
********************************************************************************
*
* Summary:
*  Change the drive mode on the pins of the port.
*
* Parameters:
*  mode:  Change the pins to one of the following drive modes.
*
*  Pin_SS_DM_STRONG     Strong Drive
*  Pin_SS_DM_OD_HI      Open Drain, Drives High
*  Pin_SS_DM_OD_LO      Open Drain, Drives Low
*  Pin_SS_DM_RES_UP     Resistive Pull Up
*  Pin_SS_DM_RES_DWN    Resistive Pull Down
*  Pin_SS_DM_RES_UPDWN  Resistive Pull Up/Down
*  Pin_SS_DM_DIG_HIZ    High Impedance Digital
*  Pin_SS_DM_ALG_HIZ    High Impedance Analog
*
* Return:
*  None
*
*******************************************************************************/
void Pin_SS_SetDriveMode(uint8 mode)
{
	CyPins_SetPinDriveMode(Pin_SS_0, mode);
}

/*******************************************************************************
* Function Name: Pin_SS_Read
********************************************************************************
*
* Summary:
*  Read the current value on the pins of the Digital Port in right justified
*  form.
*
* Parameters:
*  None
*
* Return:
*  Returns the current value of the Digital Port as a right justified number
*
* Note:
*  Macro Pin_SS_ReadPS calls this function.
*
*******************************************************************************/
uint8 Pin_SS_Read(void)
{
    return (Pin_SS_PS & Pin_SS_MASK) >> Pin_SS_SHIFT;
}

/*******************************************************************************
* Function Name: Pin_SS_ReadDataReg
********************************************************************************
*
* Summary:
*  Read the current value assigned to a Digital Port's data output register
*
* Parameters:
*  None
*
* Return:
*  Returns the current value assigned to the Digital Port's data output register
*
*******************************************************************************/
uint8 Pin_SS_ReadDataReg(void)
{
    return (Pin_SS_DR & Pin_SS_MASK) >> Pin_SS_SHIFT;
}

/* If Interrupts Are Enabled for this Pins component */
#if defined(Pin_SS_INTSTAT)

    /*******************************************************************************
    * Function Name: Pin_SS_ClearInterrupt
    ********************************************************************************
    * Summary:
    *  Clears any active interrupts attached to port and returns the value of the
    *  interrupt status register.
    *
    * Parameters:
    *  None
    *
    * Return:
    *  Returns the value of the interrupt status register
    *
    *******************************************************************************/
    uint8 Pin_SS_ClearInterrupt(void)
    {
        return (Pin_SS_INTSTAT & Pin_SS_MASK) >> Pin_SS_SHIFT;
    }

#endif /* If Interrupts Are Enabled for this Pins component */

#endif /* CY_PSOC5A... */

/* [] END OF FILE */


text:
<?php

namespace Google\Service\ApiKeysService;

class V2ServerKeyRestrictions extends \Google\Collection
{
  protected $collection_key = 'allowedIps';
  /**
   * @var string[]
   */
  public $allowedIps;

  /**
   * @param string[]
   */
  public function setAllowedIps($allowedIps)
  {
    $this->allowedIps = $allowedIps;
  }
  /**
   * @return string[]
   */
  public function getAllowedIps()
  {
    return $this->allowedIps;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(V2ServerKeyRestrictions::class, 'Google_Service_ApiKeysService_V2ServerKeyRestrictions');


text:
include_recipe "apt"

source_file = "/etc/apt/sources.list"
new_sources = [ "deb http://archive.canonical.com/ubuntu lucid partner",
                "deb-src http://archive.canonical.com/ubuntu lucid partner" ]

new_sources.each do |source|
  execute "echo '#{source}' >> #{source_file}" do
    not_if do `java -version`.include?("Java(TM) SE Runtime Environment") end
  end
end

execute "apt-get update" do
  not_if do `java -version`.include?("Java(TM) SE Runtime Environment") end
end

cookbook_file "/tmp/license_accept.txt" do
  source "license_accept.txt"
  mode "0644"
  not_if do `java -version`.include?("Java(TM) SE Runtime Environment") end
end

execute "/usr/bin/debconf-set-selections /tmp/license_accept.txt" do
  not_if do `java -version`.include?("Java(TM) SE Runtime Environment") end
end

package "sun-java6-jdk"

file "/tmp/license_accept.txt" do
  action :delete
end