text:
using rpc_char_t = unsigned char;
using rpc_wchar_t = unsigned short;
using rpc_tchar_t = std::conditional<sizeof(TCHAR) == sizeof(wchar_t), rpc_wchar_t, rpc_char_t>::type;

//-----------------------------------------------------------------------------
// Generic Text Extensions
//
// TODO: This is more than generic text now, and the conversions can take
// advantage of the convert<> template instead

// char_t
//
// Typedef for an ANSI character
using char_t = char;

// tchar_t
//
// Typedef for a generic text character
using tchar_t = std::conditional<sizeof(TCHAR) == sizeof(wchar_t), wchar_t, char>::type;

namespace std {

	// std::tstring
	//
	// Typedef for a generic text std::[w]string
	using tstring = conditional<sizeof(TCHAR) == sizeof(wchar_t), wstring, string>::type;

	// std::to_string (conversion)
	//
	inline string to_string(const wchar_t* psz, int cch)
	{
		if(psz == nullptr) return string();

		// Create a buffer big enough to hold the converted string data and convert it
		int buffercch = WideCharToMultiByte(CP_UTF8, 0, psz, cch, nullptr, 0, nullptr, nullptr);
		auto buffer = std::make_unique<char_t[]>(buffercch);
		WideCharToMultiByte(CP_UTF8, 0, psz, cch, buffer.get(), buffercch, nullptr, nullptr);

		// Construct an std::string around the converted character data
		return string(buffer.get(), buffercch);
	}

	// std::to_string overloads
	//
	inline string to_string(const wchar_t* psz) { return to_string(psz, -1); }
	inline string to_string(const char_t* psz, int cch) { return string(psz, cch); }
	inline string to_string(const char_t* psz) { return string(psz); }
	inline string to_string(const wstring& str) { return to_string(str.data(), static_cast<int>(str.size())); }

	// std::to_wstring (conversion)
	//
	inline wstring to_wstring(const char_t* psz, int cch)
	{
		if(psz == nullptr) return wstring();

		// Create a buffer big enough to hold the converted string data and convert it
		int buffercch = MultiByteToWideChar(CP_UTF8, 0, psz, cch, nullptr, 0);
		auto buffer = std::make_unique<wchar_t[]>(buffercch);
		MultiByteToWideChar(CP_UTF8, 0, psz, cch, buffer.get(), buffercch);

		// Construct an std::wstring around the converted character data
		return wstring(buffer.get(), buffercch);
	}

	// std::to_wstring overloads
	//
	inline wstring to_wstring(const char_t* psz) { return to_wstring(psz, -1); }
	inline wstring to_wstring(const wchar_t* psz, int cch) { return wstring(psz, cch); }
	inline wstring to_wstring(const wchar_t* psz) { return wstring(psz); }
	inline wstring to_wstring(const string& str) { return to_wstring(str.data(), static_cast<int>(str.size())); }

	// std::to_tstring
	//
	// Generic text wrapper around std::to_[w]string
	template <typename _type> inline tstring to_tstring(_type value)
	{
#ifdef _UNICODE
		return to_wstring(value);
#else
		return to_string(value);
#endif
	}

	// std::to_tstring
	//
	// Generic text wrapper around std::to_[w]string
	template <typename _type> inline tstring to_tstring(_type value, int cch)
	{
#ifdef _UNICODE
		return to_wstring(value, cch);
#else
		return to_string(value, cch);
#endif
	}

	// std::ltrim
	//
	// Performs a left trim of a string
	inline string ltrim(const string& str)
	{
		auto left = find_if_not(str.begin(), str.end(), isspace);
		return string(left, str.end());
	}

	inline wstring ltrim(const wstring& str)
	{
		auto left = find_if_not(str.begin(), str.end(), iswspace);
		return wstring(left, str.end());
	}

	inline string ltrim(const string& str, const char_t& value)
	{
		auto left = find_if_not(str.begin(), str.end(), [&](char_t ch) { return ch == value; } );
		return string(left, str.end());
	}

	inline wstring ltrim(const wstring& str, const wchar_t& value)
	{
		auto left = find_if_not(str.begin(), str.end(), [&](wchar_t ch) { return ch == value; } );
		return wstring(left, str.end());
	}

	// std::rtrim
	//
	// Performs a right trim of a string
	inline string rtrim(const string& str)
	{
		auto right = find_if_not(str.rbegin(), str.rend(), isspace);
		return string(str.begin(), right.base());
	}

	inline wstring rtrim(const wstring& str)
	{
		auto right = find_if_not(str.rbegin(), str.rend(), iswspace);
		return wstring(str.begin(), right.base());
	}

	inline string rtrim(const string& str, const char_t& value)
	{
		auto right = find_if_not(str.rbegin(), str.rend(), [&](char_t ch) { return ch == value; } );
		return string(str.begin(), right.base());
	}

	inline wstring rtrim(const wstring& str, const wchar_t& value)
	{
		auto right = find_if_not(str.rbegin(), str.rend(), [&](wchar_t ch) { return ch == value; });
		return wstring(str.begin(), right.base());
	}

	// std::trim
	//
	// Performs a full trim of a string
	inline string trim(const string& str)
	{
		auto left = find_if_not(str.begin(), str.end(), isspace);
		auto right = find_if_not(str.rbegin(), str.rend(), isspace);
		return (right.base() <= left) ? string() : string(left, right.base());
	}

	inline wstring trim(const wstring& str)
	{
		auto left = find_if_not(str.begin(), str.end(), iswspace);
		auto right = find_if_not(str.rbegin(), str.rend(), iswspace);
		return (right.base() <= left) ? wstring() : wstring(left, right.base());
	}

	inline string trim(const string& str, const char_t& value)
	{
		auto lambda = [&](char_t ch) { return ch == value; };
		auto left = find_if_not(str.begin(), str.end(), lambda);
		auto right = find_if_not(str.rbegin(), str.rend(), lambda);
		return (right.base() <= left) ? string() : string(left, right.base());
	}

	inline wstring trim(const wstring& str, const wchar_t& value)
	{
		auto lambda = [&](wchar_t ch) { return ch == value; };
		auto left = find_if_not(str.begin(), str.end(), lambda);
		auto right = find_if_not(str.rbegin(), str.rend(), lambda);
		return (right.base() <= left) ? wstring() : wstring(left, right.base());
	}

	inline bool startswith(const string& str, const char& value)
	{
		return !str.empty() && str[0] == value;
	}

	inline bool startswith(const wstring& str, const wchar_t& value)
	{
		return !str.empty() && str[0] == value;
	}

	inline bool endswith(const string& str, const char_t& value)
	{
		return !str.empty() && str[str.size() - 1] == value;
	}

	inline bool endswith(const wstring& str, const wchar_t& value)
	{
		return !str.empty() && str[str.size() - 1] == value;
	}

} // namespace std

//-----------------------------------------------------------------------------

#pragma warning(pop)

#endif	// __GENERIC_TEXT_H_

redpajama_set_name: RedPajamaGithub


text:
class Person
  def greet
    puts "hello"
  end
end

class Person
  def greet_with_log
    puts "calling method"
    greet_without_log
    puts "method called"
  end

  alias_method :greet_without_log, :greet
  alias_method :greet, :greet_with_log
end

Person.new.greet


text:
import { LayaGPU } from "../webgl/LayaGPU";

/**
 * @internal
 * 封装GL命令
 */
export class LayaGL {
    static ARRAY_BUFFER_TYPE_DATA: number = 0;           	//创建ArrayBuffer时的类型为Data
    static ARRAY_BUFFER_TYPE_CMD: number = 1;            	//创建ArrayBuffer时的类型为Command

    static ARRAY_BUFFER_REF_REFERENCE: number = 0;			//创建ArrayBuffer时的类型为引用
    static ARRAY_BUFFER_REF_COPY: number = 1;				//创建ArrayBuffer时的类型为拷贝

    static UPLOAD_SHADER_UNIFORM_TYPE_ID: number = 0;      //data按照ID传入
    static UPLOAD_SHADER_UNIFORM_TYPE_DATA: number = 1;    //data按照数据传入

    static instance: WebGLRenderingContext;
    static layaGPUInstance: LayaGPU;
}


text:
DOTFILES=${0:a:h}

# Prompt for confirmation before overwriting files
echo "\e[38;5;160mWarning! This script will overwrite the following files:\e[0m"
for source in $(find -H $DOTFILES -name '*.link'); do
  dest="$HOME/.${source:t:r}"
  if [[ -e "$dest" ]]; then
    echo "$dest"
  fi
done
read -q "REPLY?Are you sure you want to continue (y|n)?"
echo ""
if [[ $REPLY != "y" ]]; then
  echo "Canceled"
  exit 1
fi

# Install zplug
# https://github.com/zplug/zplug
export ZPLUG_HOME=$HOME/.zplug
if [[ ! -d "${ZPLUG_HOME}" ]]; then
  git clone "https://github.com/zplug/zplug" "${ZPLUG_HOME}"
fi

# Link dotfiles to home directory
for source in $(find -H $DOTFILES -name '*.link'); do
  dest="$HOME/.${source:t:r}"
  rm -rf "$dest"
  ln -s "$source" "$dest"
  echo "link $source to $dest"
done

# Install zplug managed libraries/plugins
source "$HOME/.zshrc"
zplug install

# Install Atom packages
if [[ -x "$(command -v apm)" ]]; then
  apm install --packages-file "${DOTFILES}/atom.link/installed-packages.txt"
fi

# Install Vundle
mkdir -p "$HOME/.vim/bundle"
if [[ ! -d "$HOME/.vim/bundle/Vundle.vim" ]]; then
  git clone "https://github.com/VundleVim/Vundle.vim.git" "$HOME/.vim/bundle/Vundle.vim"
fi
vim +PluginInstall +qall


text:
FOUNDATION_EXPORT double TJPSengmentVersionNumber;
FOUNDATION_EXPORT const unsigned char TJPSengmentVersionString[];


text:
This will be a simple API that can start, stop, restart, and log output from executables. It will make it easy to run an executable persistently in the background.

# License

**executor** is licensed under the BSD 2-clause license. See [LICENSE](LICENSE).

```
Copyright (c) 2014, Alex Nichol.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```


text:
require( Merb::ActiveSupport::AS_CORE_EXT_DIR / :array / :access )
class Array
  include ActiveSupport::CoreExtensions::Array::Access
end


text:
/*
  The liquid + gas water content model is an algebraic model with dependencies.

  Generated via evaluator_generator with:
Water content for a two-phase, liquid+water vapor evaluator.

  Authors: Ethan Coon (ecoon@lanl.gov)
*/

#include "Teuchos_ParameterList.hpp"
#include "dbc.hh"
#include "liquid_gas_water_content_model.hh"

namespace Amanzi {
namespace Flow {
namespace Relations {

// Constructor from ParameterList
LiquidGasWaterContentModel::LiquidGasWaterContentModel(Teuchos::ParameterList& plist)
{
  InitializeFromPlist_(plist);
}

// Initialize parameters
void
LiquidGasWaterContentModel::InitializeFromPlist_(Teuchos::ParameterList& plist)
{

}

// main method
double
LiquidGasWaterContentModel::WaterContent(double phi, double sl, double nl, double sg, double ng, double omega, double cv) const
{
  return cv*phi*(ng*omega*sg + nl*sl);
}

double
LiquidGasWaterContentModel::DWaterContentDPorosity(double phi, double sl, double nl, double sg, double ng, double omega, double cv) const
{
  return cv*(ng*omega*sg + nl*sl);
}

double
LiquidGasWaterContentModel::DWaterContentDSaturationLiquid(double phi, double sl, double nl, double sg, double ng, double omega, double cv) const
{
  return cv*nl*phi;
}

double
LiquidGasWaterContentModel::DWaterContentDMolarDensityLiquid(double phi, double sl, double nl, double sg, double ng, double omega, double cv) const
{
  return cv*phi*sl;
}

double
LiquidGasWaterContentModel::DWaterContentDSaturationGas(double phi, double sl, double nl, double sg, double ng, double omega, double cv) const
{
  return cv*ng*omega*phi;
}

double
LiquidGasWaterContentModel::DWaterContentDMolarDensityGas(double phi, double sl, double nl, double sg, double ng, double omega, double cv) const
{
  return cv*omega*phi*sg;
}

double
LiquidGasWaterContentModel::DWaterContentDMolFracGas(double phi, double sl, double nl, double sg, double ng, double omega, double cv) const
{
  return cv*ng*phi*sg;
}

double
LiquidGasWaterContentModel::DWaterContentDCellVolume(double phi, double sl, double nl, double sg, double ng, double omega, double cv) const
{
  return phi*(ng*omega*sg + nl*sl);
}

} //namespace
} //namespace
} //namespace


text:
package ca.tsc.rss;

import android.util.Log;
import ca.tsc.base.task_queue.BackgroundTask;
import ca.tsc.base.task_queue.BackgroundTaskQueue;
import ca.tsc.base.task_queue.BackgroundTaskQueue.IBackgroundTaskQueueListener;
import ca.tsc.base.task_queue.ProgressData;
import java.util.ArrayList;
import java.util.List;

public class RSSFeedDownloadTaskQueue extends BackgroundTaskQueue {

    static class DownloadFeedProgressData extends ProgressData<RSSFeedDownloadTask, IRSSFeed> {
        DownloadFeedProgressData(RSSFeedDownloadTask task, IRSSFeed result) {
            super(task, result);
        }
    }

    public static class RSSFeedDownloadTask extends BackgroundTask<RSSLoaderTask, IBackgroundTaskQueueListener> {
        public RSSFeedDownloadTask(RSSLoaderTask data, IBackgroundTaskQueueListener listener) {
            super(new Long(0), data, listener);
        }
    }

    public RSSFeedDownloadTaskQueue(int initialCapacity) {
        super(initialCapacity);
    }

    public void requestFeed(RSSLoaderTask data, IBackgroundTaskQueueListener listener) {
        super.requestResult(new RSSFeedDownloadTask(data, listener));
        Log.i("MyTag", "requesting result for feed:" + data.getFeed().getTitle());
    }

    public void requestFeeds(List<RSSLoaderTask> datas, IBackgroundTaskQueueListener listener) {
        List<BackgroundTask<?, ?>> tasks = new ArrayList();
        for (RSSLoaderTask data : datas) {
            tasks.add(new RSSFeedDownloadTask(data, listener));
        }
        super.requestResults(tasks, listener);
    }

    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
    }

    public Object performTask(BackgroundTask<?, ?> t) throws Exception {
        RSSLoaderTask task = (RSSLoaderTask) t.getData();
        Log.i("MyTag", "Processing feed:" + task.getFeed().getTitle());
        task.execute(new Boolean[0]);
        task.get();
        Log.i("MyTag", "Feed done:" + task.getFeed().getTitle());
        return null;
    }
}


text:
var util = require("../util-lint");

// See https://docs.angularjs.org/api/ng/provider/$compileProvider#directive

exports['test directive signature validation'] = function() {

  // Number => error
  util.assertLint("angular.module('app1').directive('', 10)", {
    messages : [{"message":"Invalid argument at 2: cannot convert from number to Array|Function.prototype",
                 "from":37,
                 "to":39,
                 "severity":"error",
                 "file":"test1.js"}
               ]
  });

  // Array => OK
  util.assertLint("angular.module('app1').directive('', [])", {
    messages : [
               ]
  });

  // Function => OK
  util.assertLint("angular.module('app1').directive('', function() {})", {
    messages : [
               ]
  });

}


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.simplity.examples</groupId>
		<artifactId>examples</artifactId>
		<version>1.2.1-SNAPSHOT</version>
	</parent>
	<artifactId>mcHelloWorld</artifactId>
	<name>mcHelloWorld</name>
	<url>http://maven.apache.org</url>
	<packaging>jar</packaging>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-server</artifactId>
			<version>9.4.0.v20161208</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-servlet</artifactId>
			<version>9.4.0.v20161208</version>
		</dependency>
		<dependency>
			<groupId>org.simplity</groupId>
			<artifactId>kernel</artifactId>
			<version>1.2.1-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.7</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.7</version>
		</dependency>
	</dependencies>
	<build>
	  <resources>
      <resource>
        <directory>src/main/resources</directory>
        <excludes>
        	<exclude>comp/**</exclude>
        </excludes>
	</resource>
	</resources>
		<plugins>
			<plugin>
				<artifactId>maven-resources-plugin</artifactId>
				<version>3.0.2</version>
				<executions>
					<execution>
						<id>copy-resources</id>
						<phase>install</phase>
						<goals>
							<goal>copy-resources</goal>
						</goals>
						<configuration>
							<outputDirectory>${basedir}/target/comp</outputDirectory>
							<resources>
								<resource>
									<directory>src/main/resources/comp</directory>
									<filtering>true</filtering>
								</resource>
							</resources>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>3.0.0</version>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
						<configuration>
							<transformers>
								<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<mainClass>org.simplity.examples.App</mainClass>
								</transformer>
								<transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
									<resource>/comp</resource>
								</transformer>
							</transformers>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
ORDER BY b,a,c


text:
var React = require('react');
var ReactDOM = require('react-dom');

var ReactLayeredComponentMixin = {
    componentWillUnmount: function() {
        this._unrenderLayer();
        document.body.removeChild(this._target);
    },
    componentDidUpdate: function() {
        this._renderLayer();
    },
    componentDidMount: function() {
        // Appending to the body is easier than managing the z-index of everything on the page.
        // It's also better for accessibility and makes stacking a snap (since components will stack
        // in mount order).
        this._target = document.createElement('div');
        document.body.appendChild(this._target);
        this._renderLayer();
    },
    _renderLayer: function() {
        // By calling this method in componentDidMount() and componentDidUpdate(), you're effectively
        // creating a "wormhole" that funnels React's hierarchical updates through to a DOM node on an
        // entirely different part of the page.
        //React.render(this.renderLayer(), this._target);
        ReactDOM.render(this.renderLayer(), this._target);
    },
    _unrenderLayer: function() {
        ReactDOM.unmountComponentAtNode(this._target);
    }
};

module.exports = ReactLayeredComponentMixin;


text:
package org.apache.druid.query.groupby;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.druid.collections.NonBlockingPool;
import org.apache.druid.common.guava.GuavaUtils;
import org.apache.druid.data.input.MapBasedInputRow;
import org.apache.druid.data.input.MapBasedRow;
import org.apache.druid.data.input.Row;
import org.apache.druid.data.input.impl.DimensionSchema;
import org.apache.druid.data.input.impl.DimensionsSpec;
import org.apache.druid.data.input.impl.StringDimensionSchema;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.Pair;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.java.util.common.granularity.Granularity;
import org.apache.druid.java.util.common.guava.Accumulator;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.common.guava.Sequences;
import org.apache.druid.query.ResourceLimitExceededException;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.PostAggregator;
import org.apache.druid.query.dimension.DimensionSpec;
import org.apache.druid.segment.RowBasedColumnSelectorFactory;
import org.apache.druid.segment.column.ValueType;
import org.apache.druid.segment.incremental.IncrementalIndex;
import org.apache.druid.segment.incremental.IncrementalIndexSchema;
import org.apache.druid.segment.incremental.IndexSizeExceededException;
import org.joda.time.DateTime;

import javax.annotation.Nullable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class GroupByQueryHelper
{
  public static final String CTX_KEY_SORT_RESULTS = "sortResults";

  public static <T> Pair<IncrementalIndex, Accumulator<IncrementalIndex, T>> createIndexAccumulatorPair(
      final GroupByQuery query,
      @Nullable final GroupByQuery subquery,
      final GroupByQueryConfig config,
      NonBlockingPool<ByteBuffer> bufferPool
  )
  {
    final GroupByQueryConfig querySpecificConfig = config.withOverrides(query);
    final Granularity gran = query.getGranularity();
    final DateTime timeStart = query.getIntervals().get(0).getStart();
    final boolean combine = subquery == null;

    DateTime granTimeStart = timeStart;
    if (!(Granularities.ALL.equals(gran))) {
      granTimeStart = gran.bucketStart(timeStart);
    }

    final List<AggregatorFactory> aggs;
    if (combine) {
      aggs = Lists.transform(
          query.getAggregatorSpecs(),
          new Function<AggregatorFactory, AggregatorFactory>()
          {
            @Override
            public AggregatorFactory apply(AggregatorFactory input)
            {
              return input.getCombiningFactory();
            }
          }
      );
    } else {
      aggs = query.getAggregatorSpecs();
    }

    final List<String> dimensions = Lists.transform(
        query.getDimensions(),
        new Function<DimensionSpec, String>()
        {
          @Override
          public String apply(DimensionSpec input)
          {
            return input.getOutputName();
          }
        }
    );
    final IncrementalIndex index;

    final boolean sortResults = query.getContextValue(CTX_KEY_SORT_RESULTS, true);

    // All groupBy dimensions are strings, for now.
    final List<DimensionSchema> dimensionSchemas = new ArrayList<>();
    for (DimensionSpec dimension : query.getDimensions()) {
      dimensionSchemas.add(new StringDimensionSchema(dimension.getOutputName()));
    }

    final IncrementalIndexSchema indexSchema = new IncrementalIndexSchema.Builder()
        .withDimensionsSpec(new DimensionsSpec(dimensionSchemas, null, null))
        .withMetrics(aggs.toArray(new AggregatorFactory[0]))
        .withQueryGranularity(gran)
        .withMinTimestamp(granTimeStart.getMillis())
        .build();

    if (query.getContextValue("useOffheap", false)) {
      index = new IncrementalIndex.Builder()
          .setIndexSchema(indexSchema)
          .setDeserializeComplexMetrics(false)
          .setConcurrentEventAdd(true)
          .setSortFacts(sortResults)
          .setMaxRowCount(querySpecificConfig.getMaxResults())
          .buildOffheap(bufferPool);
    } else {
      index = new IncrementalIndex.Builder()
          .setIndexSchema(indexSchema)
          .setDeserializeComplexMetrics(false)
          .setConcurrentEventAdd(true)
          .setSortFacts(sortResults)
          .setMaxRowCount(querySpecificConfig.getMaxResults())
          .buildOnheap();
    }

    Accumulator<IncrementalIndex, T> accumulator = new Accumulator<IncrementalIndex, T>()
    {
      @Override
      public IncrementalIndex accumulate(IncrementalIndex accumulated, T in)
      {
        final MapBasedRow mapBasedRow;

        if (in instanceof MapBasedRow) {
          mapBasedRow = (MapBasedRow) in;
        } else if (in instanceof ResultRow) {
          final ResultRow row = (ResultRow) in;
          mapBasedRow = row.toMapBasedRow(combine ? query : subquery);
        } else {
          throw new ISE("Unable to accumulate something of type [%s]", in.getClass());
        }

        try {
          accumulated.add(
              new MapBasedInputRow(
                  mapBasedRow.getTimestamp(),
                  dimensions,
                  mapBasedRow.getEvent()
              )
          );
        }
        catch (IndexSizeExceededException e) {
          throw new ResourceLimitExceededException(e.getMessage());
        }

        return accumulated;
      }
    };
    return new Pair<>(index, accumulator);
  }

  public static <T> Pair<Queue, Accumulator<Queue, T>> createBySegmentAccumulatorPair()
  {
    // In parallel query runner multiple threads add to this queue concurrently
    Queue init = new ConcurrentLinkedQueue<>();
    Accumulator<Queue, T> accumulator = new Accumulator<Queue, T>()
    {
      @Override
      public Queue accumulate(Queue accumulated, T in)
      {
        if (in == null) {
          throw new ISE("Cannot have null result");
        }
        accumulated.offer(in);
        return accumulated;
      }
    };
    return new Pair<>(init, accumulator);
  }

  // Used by GroupByStrategyV1
  public static IncrementalIndex makeIncrementalIndex(
      GroupByQuery query,
      @Nullable GroupByQuery subquery,
      GroupByQueryConfig config,
      NonBlockingPool<ByteBuffer> bufferPool,
      Sequence<ResultRow> rows
  )
  {
    final Pair<IncrementalIndex, Accumulator<IncrementalIndex, ResultRow>> indexAccumulatorPair =
        GroupByQueryHelper.createIndexAccumulatorPair(query, subquery, config, bufferPool);

    return rows.accumulate(indexAccumulatorPair.lhs, indexAccumulatorPair.rhs);
  }

  // Used by GroupByStrategyV1
  public static Sequence<ResultRow> postAggregate(final GroupByQuery query, IncrementalIndex<?> index)
  {
    return Sequences.map(
        Sequences.simple(index.iterableWithPostAggregations(query.getPostAggregatorSpecs(), query.isDescending())),
        input -> {
          final ResultRow resultRow = toResultRow(query, input);

          if (query.getResultRowHasTimestamp()) {
            resultRow.set(0, query.getGranularity().toDateTime(resultRow.getLong(0)).getMillis());
          }

          return resultRow;
        }
    );
  }

  /**
   * Returns types for fields that will appear in the Rows output from "query". Useful for feeding them into
   * {@link RowBasedColumnSelectorFactory}.
   *
   * @param query groupBy query
   *
   * @return row types
   */
  public static Map<String, ValueType> rowSignatureFor(final GroupByQuery query)
  {
    final ImmutableMap.Builder<String, ValueType> types = ImmutableMap.builder();

    for (DimensionSpec dimensionSpec : query.getDimensions()) {
      types.put(dimensionSpec.getOutputName(), dimensionSpec.getOutputType());
    }

    for (AggregatorFactory aggregatorFactory : query.getAggregatorSpecs()) {
      final String typeName = aggregatorFactory.getTypeName();
      final ValueType valueType;
      if (typeName != null) {
        valueType = GuavaUtils.getEnumIfPresent(ValueType.class, StringUtils.toUpperCase(typeName));
      } else {
        valueType = null;
      }
      if (valueType != null) {
        types.put(aggregatorFactory.getName(), valueType);
      }
    }

    // Don't include post-aggregators since we don't know what types they are.
    return types.build();
  }

  public static ResultRow toResultRow(final GroupByQuery query, final Row row)
  {
    final ResultRow resultRow = ResultRow.create(query.getResultRowSizeWithPostAggregators());
    int i = 0;

    if (query.getResultRowHasTimestamp()) {
      resultRow.set(i++, row.getTimestampFromEpoch());
    }

    for (DimensionSpec dimensionSpec : query.getDimensions()) {
      resultRow.set(i++, row.getRaw(dimensionSpec.getOutputName()));
    }

    for (AggregatorFactory aggregatorFactory : query.getAggregatorSpecs()) {
      resultRow.set(i++, row.getRaw(aggregatorFactory.getName()));
    }

    for (PostAggregator postAggregator : query.getPostAggregatorSpecs()) {
      resultRow.set(i++, row.getRaw(postAggregator.getName()));
    }

    return resultRow;
  }
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'expedia_api'

require 'minitest/spec'
require 'minitest/autorun'
require 'webmock/minitest'
require 'pry'

ExpediaApi.api_key = "test"


text:
package org.http4s
package headers

import cats.parse.Numbers
import cats.parse.Parser0
import org.http4s.util.Renderable
import org.http4s.util.Writer
import org.typelevel.ci._

object `X-B3-Flags` {

  def parse(s: String): ParseResult[`X-B3-Flags`] =
    ParseResult.fromParser(parser, "Invalid X-B3-Flags header")(s)

  private[http4s] val parser: Parser0[`X-B3-Flags`] =
    Numbers.digits
      .mapFilter { str =>
        try Some(str.toLong)
        catch { case _: NumberFormatException => None }
      }
      .map(fromLong)

  sealed trait Flag extends Product with Serializable {
    def longValue: Long
  }

  object Flag {
    case object Debug extends Flag {
      override def longValue: Long = 1 << 0
    }
    case object SamplingSet extends Flag {
      override def longValue: Long = 1 << 1
    }
    case object Sampled extends Flag {
      override def longValue: Long = 1 << 2
    }
  }

  private def bitIsSet(bit: Long, flagBits: Long): Boolean =
    (flagBits & bit) == bit

  // Pure API, despite internal mutation.
  def fromLong(flagBits: Long): `X-B3-Flags` = {
    var flags: Set[`X-B3-Flags`.Flag] = Set.empty

    if (bitIsSet(Flag.Debug.longValue, flagBits))
      flags = flags + Flag.Debug

    if (bitIsSet(Flag.SamplingSet.longValue, flagBits))
      flags = flags + Flag.SamplingSet

    if (bitIsSet(Flag.Sampled.longValue, flagBits))
      flags = flags + Flag.Sampled

    `X-B3-Flags`(flags)
  }

  implicit val headerInstance: Header[`X-B3-Flags`, Header.Single] =
    Header.createRendered(
      ci"X-B3-Flags",
      h =>
        new Renderable {
          def render(writer: Writer): writer.type =
            writer.append(h.flags.foldLeft(0L)((sum, next) => sum + next.longValue).toString)

        },
      parse,
    )

}

final case class `X-B3-Flags`(flags: Set[`X-B3-Flags`.Flag])


text:
<?php

namespace AppBundle\Repository;

/**
 * WalkingRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class WalkingRepository extends \Doctrine\ORM\EntityRepository
{
    public function sortByDistanceAndStep()
    {

    }

}


text:
import nova.flags
import nova.openstack.common.importutils

API = nova.openstack.common.importutils.import_class(
        nova.flags.FLAGS.volume_api_class)


text:
/**
 * @author Disciple_D
 * @homepage https://github.com/discipled/
 * @since 01/05/2017
 */

import axios from 'axios';

const URI_PREFIX = '/staff-management';

const ProjectResource = {
	query: params => axios
		.get(`${URI_PREFIX}/projects`, { params })
		.then(res => res.data),

	create: project => axios
		.post(`${URI_PREFIX}/projects`, project),

	update: (id, project) => axios
		.put(`${URI_PREFIX}/projects/${id}`, project),

	remove: id => axios
		.delete(`${URI_PREFIX}/projects/${id}`)
};

const StaffResource = {
	query: params => axios
		.get(`${URI_PREFIX}/staffs`, { params })
		.then(res => res.data),

	create: staff => axios
		.post(`${URI_PREFIX}/staffs`, staff),

	update: (id, staff) => axios
		.put(`${URI_PREFIX}/staffs/${id}`, staff),

	remove: id => axios
		.delete(`${URI_PREFIX}/staffs/${id}`)
};

export { ProjectResource, StaffResource };


text:
<?php
/** @author troussos **/

namespace elevate\HVObjects\Generic;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\XmlMap;
use JMS\Serializer\Annotation\XmlRoot;
use JMS\Serializer\Annotation\XmlAttribute;
use JMS\Serializer\Annotation\XmlValue;
use JMS\Serializer\Annotation\XmlList;
use JMS\Serializer\Annotation\Groups;

/** @XmlRoot("person-id") */
class PersonId
{
    /**
     * @Type("string")
     * @XmlAttribute
     */
    protected $name;

    /**
     * @XmlValue
     * @Type("string")
     */
    protected $id;

    /**
     * @param $id
     * @param $name
     */
    function __construct($id, $name)
    {
        $this->id   = $id;
        $this->name = $name;
        return $this;
    }

    /**
     * @param $id
     *
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    /**
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param $name
     *
     * @return $this
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}


text:
using App.Data;
using App.Data.Service.Abstraction;
using App.Data.Service.Implementation;
using Ninject;
using System;
using System.Web.Mvc;
using System.Web.Routing;

namespace App.Web.Infrastructure.ControllerFactory
{
	public class NinjectControllerFactory : DefaultControllerFactory
	{
		private IKernel ninjectKernel;

		public NinjectControllerFactory()
		{
			this.ninjectKernel = new StandardKernel();
			this.AddBindings();
		}

		protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
		{
			return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
		}

		private void AddBindings()
		{
			ninjectKernel.Bind<IUoWData>().To<UoWData>();
			ninjectKernel.Bind<IClientsService>().To<ClientsService>();
			ninjectKernel.Bind<IPagesService>().To<PagesService>();
			ninjectKernel.Bind<IOrdersService>().To<OrdersService>();
			ninjectKernel.Bind<IMaterialsService>().To<MaterialsService>();
			ninjectKernel.Bind<ITestimonialsService>().To<TestimonialsService>();
			ninjectKernel.Bind<IImagesService>().To<ImagesService>();
			ninjectKernel.Bind<IDocumentsService>().To<DocumentsService>();
			ninjectKernel.Bind<IConfigService>().To<ConfigService>();
			ninjectKernel.Bind<IMessagingService>().To<App.Data.Service.Implementation.EmailService>();
		}
	}
}


text:
#include <cstdint>
#include <string>

#include "absl/strings/str_cat.h"
#include "asylo/client.h"
#include "asylo/enclave.pb.h"
#include "asylo/examples/grpc_server/grpc_server_config.pb.h"
#include "asylo/examples/secure_grpc/attestation_domain.h"
#include "asylo/examples/secure_grpc/grpc_server_config.pb.h"
#include "asylo/identity/enclave_assertion_authority_config.pb.h"
#include "asylo/identity/enclave_assertion_authority_configs.h"
#include "asylo/identity/platform/sgx/sgx_identity.pb.h"
#include "asylo/platform/primitives/sgx/loader.pb.h"
#include "asylo/util/status.h"
#include "asylo/util/status_macros.h"

namespace examples {
namespace secure_grpc {
namespace {

constexpr char kServerAddress[] = "localhost";
constexpr char kEnclaveName[] = "secure_grpc_server";

}  // namespace

asylo::Status LoadGrpcServerEnclave(
    const std::string &enclave_path, int port,
    const asylo::SgxIdentityExpectation &expectation, bool debug_enclave) {
  // The EnclaveLoadConfig contains all configurations passed to the enclave for
  // initialization.
  asylo::EnclaveLoadConfig load_config;
  load_config.set_name(kEnclaveName);

  // The EnclaveConfig contains the address that the gRPC server will run on,
  // the ACL to enforce in the server, and its configuration for the SGX local
  // assertion authority.
  asylo::EnclaveConfig *config = load_config.mutable_config();
  config->SetExtension(examples::grpc_server::server_address, kServerAddress);
  config->SetExtension(examples::grpc_server::port, port);
  *config->MutableExtension(examples::secure_grpc::identity_expectation) =
      expectation;
  ASYLO_ASSIGN_OR_RETURN(
      *config->add_enclave_assertion_authority_configs(),
      asylo::CreateSgxLocalAssertionAuthorityConfig(kAttestationDomain));

  // The SgxLoadConfig sets up configuration specific to an SGX enclave,
  // including the location of the enclave binary and whether to run in debug
  // mode.
  asylo::SgxLoadConfig *sgx_config =
      load_config.MutableExtension(asylo::sgx_load_config);
  sgx_config->mutable_file_enclave_config()->set_enclave_path(enclave_path);
  sgx_config->set_debug(debug_enclave);

  asylo::EnclaveManager *manager = nullptr;
  ASYLO_ASSIGN_OR_RETURN(manager, asylo::EnclaveManager::Instance());

  // Load the enclave. Calling LoadEnclave() triggers a call to the Initialize()
  // method of the TrustedApplication.
  return manager->LoadEnclave(load_config);
}

asylo::StatusOr<int> GrpcServerEnclaveGetPort() {
  asylo::EnclaveManager *manager = nullptr;
  ASYLO_ASSIGN_OR_RETURN(manager, asylo::EnclaveManager::Instance());

  asylo::EnclaveClient *client = manager->GetClient(kEnclaveName);
  if (!client) {
    return asylo::Status(asylo::error::FAILED_PRECONDITION,
                         absl::StrCat(kEnclaveName, " not running"));
  }

  asylo::EnclaveInput enclave_input;
  asylo::EnclaveOutput enclave_output;
  ASYLO_RETURN_IF_ERROR(client->EnterAndRun(enclave_input, &enclave_output));
  if (!enclave_output.HasExtension(server_port)) {
    return asylo::Status(asylo::error::INTERNAL,
                         "Server output missing server_port extension");
  }
  return enclave_output.GetExtension(server_port);
}

asylo::Status DestroyGrpcServerEnclave() {
  asylo::EnclaveManager *manager = nullptr;
  ASYLO_ASSIGN_OR_RETURN(manager, asylo::EnclaveManager::Instance());

  asylo::EnclaveClient *client = manager->GetClient(kEnclaveName);
  if (!client) {
    return asylo::Status(asylo::error::FAILED_PRECONDITION,
                         absl::StrCat(kEnclaveName, " not running"));
  }

  asylo::EnclaveFinal final_input;
  return manager->DestroyEnclave(client, final_input);
}

}  // namespace secure_grpc
}  // namespace examples


text:
#import <XCTest/XCTest.h>

#ifdef COCOAPODS
#import <EarlGrey/EarlGrey.h>
#else
#import "third_party/objective_c/EarlGrey/EarlGrey/EarlGrey.h"
#endif

@interface FDLBuilderTestAppObjCEarlGreyTests : XCTestCase

@end

@implementation FDLBuilderTestAppObjCEarlGreyTests

#pragma mark - Tests

- (void)testOpenFDLFromAppGeneratedLink {
  // On first launch, a null FDL Received alert is displayed (by design); in
  // this case, we need to dismiss it in order to proceed
  BOOL hasFirstInstallAlertDisplayed = [self confirmPresenceOfFDLAlertWithURL:@"(null)"
                                                                    matchType:@"0"
                                                            minimumAppVersion:@"(null)"];
  if (hasFirstInstallAlertDisplayed) {
    [[EarlGrey selectElementWithMatcher:[GREYMatchers matcherForText:@"Dismiss"]]
        performAction:grey_tap()];
  }

  // Scroll down in the app until the Generate Link button can be pressed, then tap it
  [[[EarlGrey selectElementWithMatcher:[GREYMatchers matcherForText:@"Generate Link"]]
         usingSearchAction:grey_swipeFastInDirection(kGREYDirectionUp)
      onElementWithMatcher:grey_kindOfClass([UITableView class])] performAction:grey_tap()];

  // Find long link table view cell
  NSString *fdlLongLinkId = @"LinkTableViewCell-LinkTextView-Long link";

  // Find long link table view cell
  [[[EarlGrey selectElementWithMatcher:grey_accessibilityID(fdlLongLinkId)] atIndex:0]
      assert:[GREYAssertionBlock
                       assertionWithName:@"Long link non empty and valid"
                 assertionBlockWithError:^BOOL(id element, NSError *__strong *errorOrNil) {
                   XCTAssertTrue([element isKindOfClass:[UITextView class]]);
                   UITextView *longLinkTextView = element;
                   // ensure long link cell has non empty value
                   XCTAssertTrue(longLinkTextView.text.length > 0);
                   // ensure long link cell value is a valid URL
                   XCTAssertNotNil([NSURL URLWithString:longLinkTextView.text]);

                   return YES;
                 }]];
}

#pragma mark - Private

- (BOOL)waitForElementWithMatcher:(id<GREYMatcher>)matcher
            toBeVisibleWithinTime:(CFTimeInterval)timeInterval {
  return [[GREYCondition conditionWithName:@"Waiting for element to appear"
                                     block:^BOOL() {
                                       return [self isElementPresentWithMatcher:matcher];
                                     }] waitWithTimeout:timeInterval];
}

- (BOOL)isElementPresentWithMatcher:(id<GREYMatcher>)matcher {
  NSError *error = nil;

  [[[EarlGrey selectElementWithMatcher:matcher] atIndex:0] assertWithMatcher:grey_notNil()
                                                                       error:&error];

  if (error && (![error.domain isEqualToString:kGREYInteractionErrorDomain] ||
                error.code != kGREYInteractionElementNotFoundErrorCode)) {
    GREYFail(@"Unexpected error when trying to locate an element matching %@: %@", matcher, error);
  }
  return error == nil;
}

- (BOOL)confirmPresenceOfFDLAlertWithURL:(NSString *)URL
                               matchType:(NSString *)matchType
                       minimumAppVersion:(NSString *)minimumAppVersion {
  id<GREYMatcher> alertViewClass = grey_kindOfClass(NSClassFromString(@"_UIAlertControllerView"));
  NSString *expectedAlertText =
      [NSString stringWithFormat:@"URL [%@], matchType [%@], minimumAppVersion [%@]", URL,
                                 matchType, minimumAppVersion];

  return [self waitForElementWithMatcher:grey_allOf(grey_ancestor(alertViewClass),
                                                    grey_text(expectedAlertText), nil)
                   toBeVisibleWithinTime:10];
}

@end


text:
/**
 *
 */
package org.minnal.instrument.resource.creator;

import java.util.List;
import java.util.Set;

import javassist.CtClass;
import javassist.CtMethod;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.StringMemberValue;

import javax.ws.rs.DELETE;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.Context;

import org.apache.velocity.Template;
import org.minnal.instrument.resource.ResourceWrapper.ResourcePath;
import org.minnal.instrument.resource.metadata.ResourceMetaData;
import org.minnal.instrument.util.JavassistUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.wordnik.swagger.annotations.ApiOperation;

/**
 * @author ganeshs
 *
 */
public class DeleteMethodCreator extends AbstractMethodCreator {

	private static final Logger logger = LoggerFactory.getLogger(DeleteMethodCreator.class);

	/**
	 * @param ctClass
	 * @param resource
	 * @param resourcePath
	 * @param basePath
	 */
	public DeleteMethodCreator(CtClass ctClass, ResourceMetaData resource, ResourcePath resourcePath, String basePath) {
		super(ctClass, resource, resourcePath, basePath);
	}

	private static Template deleteMethodTemplate = engine.getTemplate("META-INF/templates/delete_method.vm");

	@Override
	protected Template getTemplate() {
		return deleteMethodTemplate;
	}

	@Override
	protected void addParamAnnotations(CtMethod ctMethod) {
		Annotation[][] annotations = new Annotation[1][0];
		Annotation parameterAnnotation = new Annotation(Context.class.getCanonicalName(), ctMethod.getMethodInfo().getConstPool());
		annotations[0] = new Annotation[1];
		annotations[0][0] = parameterAnnotation;
		JavassistUtils.addParameterAnnotation(ctMethod, annotations);
	}

	@Override
	protected Annotation getApiOperationAnnotation() {
		ConstPool constPool = getCtClass().getClassFile().getConstPool();
		Annotation annotation = new Annotation(ApiOperation.class.getCanonicalName(), constPool);
		annotation.addMemberValue("value", new StringMemberValue("Delete " + getResourcePath().getNodePath().getName() + " by id", constPool));
		return annotation;
	}

	@Override
	protected Set<String> getPermissions() {
		return getPermissions(HttpMethod.DELETE);
	}

	@Override
	protected List<Annotation> getApiResponseAnnotations() {
		return Lists.newArrayList(getNoContentResponseAnnotation(), getNotFoundResponseAnnotation());
	}

	@Override
	protected String getHttpMethod() {
		return HttpMethod.DELETE;
	}

	@Override
	protected Class<?> getHttpAnnotation() {
		return DELETE.class;
	}

	@Override
	protected List<Annotation> getApiAdditionalParamAnnotations() {
		return Lists.newArrayList();
	}
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// @ts-nocheck
// TODO(crbug.com/1011811): Enable TypeScript compiler checks

window.viewportSize = {
  width: 800,
  height: 600
};
window.deviceScaleFactor = 1;
window.emulationScaleFactor = 1;
window.pageScaleFactor = 1;
window.pageZoomFactor = 1;
window.scrollX = 0;
window.scrollY = 0;

export function reset(resetData) {
  window.viewportSize = resetData.viewportSize;
  window.deviceScaleFactor = resetData.deviceScaleFactor;
  window.pageScaleFactor = resetData.pageScaleFactor;
  window.pageZoomFactor = resetData.pageZoomFactor;
  window.emulationScaleFactor = resetData.emulationScaleFactor;
  window.scrollX = Math.round(resetData.scrollX);
  window.scrollY = Math.round(resetData.scrollY);

  window.canvas = document.getElementById('canvas');
  if (window.canvas) {
    window.canvas.width = deviceScaleFactor * viewportSize.width;
    window.canvas.height = deviceScaleFactor * viewportSize.height;
    window.canvas.style.width = viewportSize.width + 'px';
    window.canvas.style.height = viewportSize.height + 'px';

    window.context = canvas.getContext('2d');
    window.context.scale(deviceScaleFactor, deviceScaleFactor);

    window.canvasWidth = viewportSize.width;
    window.canvasHeight = viewportSize.height;
  }

  doReset();
}

function doReset() {
}

export function setPlatform(platform) {
  window.platform = platform;
  document.body.classList.add('platform-' + platform);
}

export function dispatch(message) {
  const functionName = message.shift();
  window[functionName].apply(null, message);
}

export function log(text) {
  let element = document.getElementById('log');
  if (!element) {
    element = document.body.createChild();
    element.id = 'log';
  }
  element.createChild('div').textContent = text;
}

export function eventHasCtrlOrMeta(event) {
  return window.platform === 'mac' ? (event.metaKey && !event.ctrlKey) : (event.ctrlKey && !event.metaKey);
}

Element.prototype.createChild = function(tagName, className) {
  const element = createElement(tagName, className);
  element.addEventListener('click', function(e) {
    e.stopPropagation();
  }, false);
  this.appendChild(element);
  return element;
};

Element.prototype.createTextChild = function(text) {
  const element = document.createTextNode(text);
  this.appendChild(element);
  return element;
};

Element.prototype.removeChildren = function() {
  if (this.firstChild) {
    this.textContent = '';
  }
};

export function createElement(tagName, className) {
  const element = document.createElement(tagName);
  if (className) {
    element.className = className;
  }
  return element;
}

String.prototype.trimEnd = function(maxLength) {
  if (this.length <= maxLength) {
    return String(this);
  }
  return this.substr(0, maxLength - 1) + '\u2026';
};

/**
 * @param {number} num
 * @param {number} min
 * @param {number} max
 * @return {number}
 */
Number.constrain = function(num, min, max) {
  if (num < min) {
    num = min;
  } else if (num > max) {
    num = max;
  }
  return num;
};


text:
package org.apache.rat.document.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;

import org.apache.commons.io.IOUtils;

public class DocumentImplUtils {

    public final static String toName(File file) {
        String path = file.getPath();
        return path.replace('\\', '/');
    }

    public static final boolean isZipStream(InputStream stream) {
        ZipInputStream zip = new ZipInputStream(stream);
        try {
            zip.getNextEntry();
            return true;
        } catch (IOException e) {
            return false;
        } finally {
            IOUtils.closeQuietly(zip);
        }
    }

    public static final boolean isZip(File file) {
        try {
            return isZipStream(new FileInputStream(file));
        } catch (IOException e) {
            return false;
        }
    }

}


text:
.class public Lcom/tencent/mm/sdk/modelmsg/ShowMessageFromWX;
.super Ljava/lang/Object;

# direct methods
.method private constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
ifeq ($(CHAINS_ROOT),)
  $(error CHAINS_ROOT not defined, use make install-chains-202105 CHAINS_ROOT=<dir>)
endif

install:
	rsync -av --copy-unsafe-links --exclude __pycache__ --exclude '.*' bin js py $(ACMACSD_ROOT)/share/conf/clades.mapi $(CHAINS_ROOT)
	rsync -av --copy-unsafe-links --exclude __pycache__ --exclude '.*' --exclude chain202105 $(ACMACSD_ROOT)/sources/acmacs-py/py/acmacs_py $(CHAINS_ROOT)/py

# ======================================================================


text:
set -e
set -x

N_JOBS=$(grep -c ^processor /proc/cpuinfo)

echo ""
echo "Bazel will use ${N_JOBS} concurrent job(s)."
echo ""

# Run configure.
export TF_NEED_CUDA=0
export PYTHON_BIN_PATH=`which python2`
yes "" | $PYTHON_BIN_PATH configure.py

# Run bazel test command. Double test timeouts to avoid flakes.
# Setting KMP_BLOCKTIME to 0 lets OpenMP threads to sleep right after parallel execution
# in an MKL primitive. This reduces the effects of an oversubscription of OpenMP threads
# caused by executing multiple tests concurrently.
bazel test --test_tag_filters=-no_oss,-oss_serial,-gpu,-benchmark-test --test_lang_filters=cc,py -k \
    --jobs=${N_JOBS} --test_timeout 300,450,1200,3600 --build_tests_only \
    --config=mkl --test_env=KMP_BLOCKTIME=0 --config=opt --test_output=errors -- \
    //tensorflow/... -//tensorflow/compiler/... -//tensorflow/contrib/... -//tensorflow/lite/...


text:
package org.javers.core.graph;

import org.javers.core.metamodel.type.JaversProperty;

import java.util.Collections;
import java.util.List;

class ShallowMultiEdge extends AbstractMultiEdge {
    private final Object dehydratedPropertyValue;

    ShallowMultiEdge(JaversProperty property, Object dehydratedPropertyValue) {
        super(property);
        this.dehydratedPropertyValue = dehydratedPropertyValue;
    }

    @Override
    List<LiveNode> getReferences() {
        return Collections.emptyList();
    }

    @Override
    Object getDehydratedPropertyValue() {
        return dehydratedPropertyValue;
    }
}


text:
A Ruby on Rails user interface for Facebook ThreatExchange. Easily query and share share threat indicators using Facebook ThreatExchange.

For info on FB ThreatExchange: [https://developers.facebook.com/products/threat-exchange] (https://developers.facebook.com/products/threat-exchange)

A functional version of ThreatExchangeUI is available at [https://threatexchangeui.seventwentynine.com] (https://threatexchangeui.seventwentynine.com)

Implemented Features:

* Query threat indicators
* Show threat descriptors
* Render IP indicators on a world map
* Submit threat descriptors

## Getting started

Facebook App ID and App Secret are needed to interact with Facebook ThreatExchange. PostgresSQL is also needed to use ThreatExchangeUI. Add relevant types data to IndicatorType, PrivacyType, SeverityType, ShareLevelType, StatusType and ThreatType tables. See [https://developers.facebook.com/docs/threat-exchange/reference/apis/v2.5] (https://developers.facebook.com/docs/threat-exchange/reference/apis/v2.5) for details.

## Installation

Install required dependencies

    bundle install
    rake db:create
    rake db:migrate

## Bug reports

If you discover a bug with ThreatExchangeUI, please let me know (Twitter: @skills4ever)

## Contributing

1. Fork it ( https://github.com/skills4ever/ThreatExchangeUI/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
@implementation DAImageView

NSTrackingArea* tArea;
bool isOpened = 0;

@synthesize statusItem;
@synthesize menu;

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {}
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    if(isOpened) {
        [[NSColor selectedMenuItemColor] set];
        NSRectFill(dirtyRect);
    }
    [super drawRect:dirtyRect];
}

- (void)mouseEntered:(NSEvent *)theEvent {
    [super mouseEntered:theEvent];
    NSLog(@"enter");
}

- (void)mouseExited:(NSEvent *)theEvent {
    [super mouseExited:theEvent];
    NSLog(@"exit");
}

- (void)mouseDown:(NSEvent *)theEvent {
    [super mouseDown:theEvent];
    isOpened = true;
    [self setNeedsDisplay];
    [self.statusItem popUpStatusItemMenu:self.menu];
}

- (NSMenu*)menu {
    return menu;
}

- (void)setMenu:(NSMenu *)_menu {
    menu = _menu;
    [menu setDelegate:self];
}

- (void)menuDidClose:(NSMenu*)menu {
    isOpened = false;
}

- (void)updateTrackingAreas {
    [super updateTrackingAreas];
    if(tArea)
        [self removeTrackingArea:tArea];

    NSTrackingAreaOptions opts = NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
    tArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:opts owner:self userInfo:nil];
    [self addTrackingArea:tArea];
}

@end


text: $ANDROID_SDK/platform-tools/adb install -r Main.apk


text:
This is a basic key-value store with a RESTful front-end. Data is stored in a simple SQLite database, each value is encrypted with aes-128-ctr, and each row is signed with hmac-sha256. API authentication is handled by an API key.

## Prerequisites ##

 - nodejs
 - npm
 - Make
 - sqlite3
 - mocha

 ## Building ##

**Clone repository**

```bash
git clone https://github.com/astercrono/kvstore-server
cd kvstore-server
```

**Setup database and keys**

This will create the database and setup all the necessary keys (encryption, signing and API).

```bash
make new
```

**Setup**
```bash
make
```

## Running ##
To launch the server, just run app.js.
```bash
node app.js
```

I do, however, recommend using a process manager, such as *nodemon* or *forever*.

## Authentication ##

By default, your credentials will be location in $HOME/kvstore.secret, unless otherwise customized in the project's config.json file. To get your API key, open up this file and copy out the API key. Save this somewhere for later use.


text:
Get's the balance as well as when the balance was last updated of your starbucks card.

## Definition
https://sbux-card.azurewebsites.net/

## Parameters
**card_number:      String**

                   *required*

**                 pin:      String**

                   *required*

## Results Format

*200* Success:

    { "bal":"$20.00", "lastUpdated":"5/10/2015 10:42 AM" }

## Documentation

### Node.js

```Javascript

var request = require('request');

request.get(
    'https://sbux-card.azurewebsites.net/',
    { form: { 'card_number': '<card_number>',
              'pin': '<pin>' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
        }
    }
);
```
### Javascript

```Javascript
function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

var response = httpGet('https://sbux-card.azurewebsites.net/?card_number=' + cardNumber + '&pin=' + pin);
```


text:
module Grape
  module Middleware
    class ThrottleMiddleware < Grape::Middleware::Base
      COUNTER_START = 0
      def before
        endpoint = env['api.endpoint']
        logger   = options[:logger] || Logger.new(STDOUT)
        return unless throttle_options = endpoint.route_setting(:throttle)

        if limit = throttle_options[:hourly]
          period = 1.hour
        elsif limit = throttle_options[:daily]
          period = 1.day
        elsif limit = throttle_options[:monthly]
          period = 1.month
        elsif period = throttle_options[:period]
          limit = throttle_options[:limit]
        end
        if limit.nil? || period.nil?
          raise ArgumentError.new('Please set a period and limit (see documentation)')
        end

        user_key = options[:user_key]
        user_value = nil
        user_value = user_key.call(env) unless user_key.nil?
        user_value ||= "ip:#{env['REMOTE_ADDR']}"

        r = endpoint.routes.first
        rate_key = "#{r.route_method}:#{r.route_path}:#{user_value}"

        redis = options[:cache]
        begin
          redis.ping
          current = redis.get(rate_key).to_i
          if !current.nil? && current >= limit
            endpoint.error!("too many requests, please try again later", 429)
          else
            redis.multi do
              # Set the value of the key to COUNTER_START if the key does not already exist and
              # set the expiry only on creation to avoid clobbering it later
              redis.set(rate_key, COUNTER_START, { :nx => true, :ex => period.to_i } )
              redis.incr(rate_key)
            end
          end

        rescue Exception => e
          logger.warn(e.message)
        end

      end

    end
  end
end


text:
package org.apache.maven.classpath.munger.parse.pom;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StreamCorruptedException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import javax.servlet.Servlet;

import org.apache.maven.classpath.munger.AbstractTestSupport;
import org.apache.maven.classpath.munger.Dependency;
import org.apache.maven.classpath.munger.Repository;
import org.apache.maven.classpath.munger.parse.MavenDependency;
import org.apache.maven.classpath.munger.util.properties.PropertiesUtil;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;

/**
 * @author Lyor G.
 * @since Dec 24, 2013 1:12:25 PM
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PomDependenciesLoaderTest extends AbstractTestSupport {
    public PomDependenciesLoaderTest() {
        super();
    }

    @Test
    public void testPropertiesParsing() throws IOException {
        Map<String,String>  testProps=new TreeMap<String,String>();
        {
            Properties sysProps=System.getProperties();
            for (String name : sysProps.stringPropertyNames()) {
                if ("line.separator".equalsIgnoreCase(name)
                 || "file.separator".equalsIgnoreCase(name)) {
                    continue;   // avoid these issues
                }
                String  value=sysProps.getProperty(name);
                testProps.put(name, value);
            }
        }

        File    file=createTempFile(getCurrentTestName(), ".xml");
        PrintStream out=writePOMFilePreamble(new PrintStream(file, "UTF-8"));
        try {
            out.append('\t').println("<properties>");
            for (Map.Entry<String,String> pe : testProps.entrySet()) {
                String  name=pe.getKey(), value=pe.getValue();
                out.append("\t\t<").append(name).append('>').append(value).append("</").append(name).println('>');
            }
            out.append('\t').println("</properties>");

            out.println();
            out.println("</project>");
            if (out.checkError()) {
                throw new StreamCorruptedException("Failed to generate data");
            }
        } finally {
            out.close();
        }

        PomDependenciesLoader   loader=new PomDependenciesLoader(getCurrentTestLogger());
        loader.load(file);

        assertPropertySourceContents(testProps, loader.getProperties());
    }

    @Test
    public void testDependenciesParsing() throws IOException {
        List<? extends MavenDependency>    expected=
                Collections.unmodifiableList(
                        Arrays.asList(
                                new MavenDependency(getClass().getPackage().getName(), getClass().getSimpleName(), Dependency.DEFAULT_PACKAGING, "7.3.65"),
                                new MavenDependency(getClass().getPackage().getName(), getCurrentTestName(), Dependency.DEFAULT_PACKAGING, "10.2.71.813", "compile"),
                                new MavenDependency(Assert.class.getPackage().getName(), "junit", Dependency.DEFAULT_PACKAGING, "1.2.3", "runtime")
                            ));

        File    file=createTempFile(getCurrentTestName(), ".xml");
        PrintStream out=writePOMFilePreamble(new PrintStream(file, "UTF-8"));
        try {
            out.append('\t').println("<dependencies>");
            for (MavenDependency d : expected) {
                appendDependency(out, d);
            }
            for (MavenDependency d : new MavenDependency[] {
                    new MavenDependency(Servlet.class.getPackage().getName(), "servlet-api", Dependency.DEFAULT_PACKAGING, "3.0", "provided"),
                    new MavenDependency(String.class.getPackage().getName(), "tools", "1.7", Dependency.DEFAULT_PACKAGING, "system"),
                    new MavenDependency(Mockito.class.getPackage().getName(), "mockito-all", Dependency.DEFAULT_PACKAGING, "5.6.7", "test")
            }) {
                appendDependency(out, d);
            }
            out.append('\t').println("</dependencies>");

            out.println();
            out.println("</project>");
            if (out.checkError()) {
                throw new StreamCorruptedException("Failed to generate data");
            }
        } finally {
            out.close();
        }

        PomDependenciesLoader   loader=new PomDependenciesLoader(getCurrentTestLogger());
        loader.load(file);

        List<Dependency>    actual=loader.getDependencies();
        assertEquals("Mismatched result size", expected.size(), actual.size());
        for (int index=0; index < expected.size(); index++) {
            Dependency  eValue=expected.get(index), aValue=actual.get(index);
            assertEquals("Mismatched results at index=" + index, eValue, aValue);
        }
    }

    private <P extends PrintStream> P appendDependency(P out, MavenDependency d) {
        out.append("\t\t").println("<dependency>");
            out.append("\t\t\t").append("<groupId>").append(d.getGroupId()).println("</groupId>");
            out.append("\t\t\t").append("<artifactId>").append(d.getArtifactId()).println("</artifactId>");
            out.append("\t\t\t").append("<version>").append(d.getVersion()).println("</version>");
            out.append("\t\t\t").append("<type>").append(d.getPackaging()).println("</type>");

            String  scope=d.getScope();
            if (!PropertiesUtil.isEmpty(scope)) {
                out.append("\t\t\t").append("<scope>").append(scope).println("</scope>");
            }
        out.append("\t\t").println("</dependency>");

        return out;
    }

    @Test
    public void testParseRepositories() throws IOException {
        List<Repository>    expected=
                Collections.unmodifiableList(
                        Arrays.asList(
                                new Repository(getClass().getSimpleName(), "http://7.3.6.5:8080/maven/nexus"),
                                new Repository(getCurrentTestName(), "https://10.2.71.813/repo/maven2")
                            ));
        File    file=createTempFile(getCurrentTestName(), ".xml");
        PrintStream out=writePOMFilePreamble(new PrintStream(file, "UTF-8"));
        try {
            out.append('\t').println("<repositories>");
            for (Repository r : expected) {
                out.append("\t\t").println("<repository>");
                    out.append("\t\t\t").append("<id>").append(r.getId()).println("</id>");
                    out.append("\t\t\t").append("<name>").append(r.getId()).println("</name>");
                    out.append("\t\t\t").append("<url>").append(r.getUrl()).println("</url>");
                out.append("\t\t").println("</repository>");
            }
            out.append('\t').println("</repositories>");

            out.println();
            out.println("</project>");
            if (out.checkError()) {
                throw new StreamCorruptedException("Failed to generate data");
            }
        } finally {
            out.close();
        }

        PomDependenciesLoader   loader=new PomDependenciesLoader(getCurrentTestLogger());
        loader.load(file);

        List<Repository>    actual=loader.getRepositories();
        assertEquals("Mismatched result size", expected.size(), actual.size());
        for (int index=0; index < expected.size(); index++) {
            Repository  eValue=expected.get(index), aValue=actual.get(index);
            assertEquals("Mismatched results at index=" + index, eValue, aValue);
        }
    }

    private <P extends PrintStream> P writePOMFilePreamble(P out) {
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        out.println("<!-- " + getClass().getSimpleName() + "#" + getCurrentTestName() + " -->");
        out.println("<project xmlns=\"http://maven.apache.org/POM/4.0.0\"");
        out.append("\t\t").println("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
        out.append("\t\t").println("xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">");
        out.append('\t').println("<modelVersion>4.0.0</modelVersion>");
        out.append("\t\t").println("<groupId>org.apache.maven.classpath.munger</groupId>");
        out.append("\t\t").println("<artifactId>parent</artifactId>");
        out.append("\t\t").println("<packaging>pom</packaging>");
        out.append("\t\t").println("<name>" + getClass().getPackage().getName() + ":" + getCurrentTestName() + "</name>");
        out.append("\t\t").println("<version>1.0.0-CI-SNAPSHOT</version>");
        out.println();

        return out;
    }
}


text:
Your account has been created.

    {{ fields.email.label }}
    <input type="email" ng-model="data.email" class="form-control" id="email" maxlength="{{ fields.email.max_length }}">

    {{ fields.password.label }}
    <input type="password" ng-model="data.password" class="form-control" id="password">

    {{ fields.password2.label }}
    <input type="password" ng-model="data.password2" class="form-control" id="password2">

    {{ fields.name.label }}
    <input type="text" ng-model="data.name" class="form-control" id="name" maxlength="{{ fields.name.max_length }}">

<button type="submit" class="btn btn-default" translate>Register</button>


text:
//
//  AKSegmentArray.h
//  AudioKit
//
//  Created by Aurelius Prochazka on 1/4/15.
//  Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//

#import "AKParameter+Operation.h"

/** Trace a series of linear or exponential segments between specified points.
 */
NS_ASSUME_NONNULL_BEGIN
@interface AKSegmentArray : AKParameter

/// Creates the exponential segment array and populates it with the minimum information.
/// Use addValue:afterDuration to add more segments to the array.
/// An optional release segment can be added with addReleaseToFinalValue:afterDuration.
/// @param initialValue Starting value.
/// @param targetValue Value after time given by duration.
/// @param duration Duration in seconds of first segment.
/// @param concavity A value greater than zero is an initially slower change and less than zero is a quicker intial change.  Use zero for a linear change.
- (instancetype)initWithInitialValue:(AKConstant *)initialValue
                         targetValue:(AKConstant *)targetValue
                       afterDuration:(AKConstant *)duration
                           concavity:(AKConstant *)concavity;

/// Adds another segment.
/// @param value Value after time given by duration.
/// @param duration Duration in seconds.
/// @param concavity A value greater than zero is an initially slower change and less than zero is a quicker intial change.  Use zero for a linear change.
- (void)addValue:(AKConstant *)value
   afterDuration:(AKConstant *)duration
       concavity:(AKConstant *)concavity;

/// Creates the exponential segment array and populates it with the minimum information.
/// Use addValue:afterDuration to add more segments to the array.
/// An optional release segment can be added with addReleaseToFinalValue:afterDuration.
/// @param initialValue Starting value.
/// @param targetValue Value after time given by duration.
/// @param duration Duration in seconds of first segment.
- (instancetype)initWithInitialValue:(AKConstant *)initialValue
                         targetValue:(AKConstant *)targetValue
                       afterDuration:(AKConstant *)duration;

/// Adds a linear segment
/// @param value Value after time given by duration.
/// @param duration Duration in seconds.
- (void)addValue:(AKConstant *)value
   afterDuration:(AKConstant *)duration;

/// Creates a release segment.
/// @param value Value after time given by duration.
/// @param duration Duration in seconds.
/// @param concavity A value greater than zero is an initially slower change and less than zero is a quicker intial change.  Use zero for a linear change.
- (void)releaseToValue:(AKConstant *)value
         afterDuration:(AKConstant *)duration
             concavity:(AKConstant *)concavity;

@end
NS_ASSUME_NONNULL_END


text:
"""
Feed the whole image to the network.
"""

import tensorflow as tf

import image_augmentations

def input_nodes(
  # An array of paths to tfrecords files
  tfrecords,

  # Data augmentation depends on whether we are in train vs (test / eval) mode
  augment=True,

  # number of times to read the tfrecords
  num_epochs=None,

  # Data queue feeding the model
  batch_size=32,
  num_threads=2,
  shuffle_batch = True,
  capacity = 1000,
  min_after_dequeue = 96,

  # And tensorboard summaries of the images
  add_summaries=True,

  # Global configuration
  cfg=None):
  """
  Whole image

  tfrecords : an array of paths to .tfrecords files containing the Example protobufs

  """

  with tf.name_scope('inputs'):

    # Have a queue that produces the paths to the .tfrecords
    filename_queue = tf.train.string_input_producer(
      tfrecords,
      num_epochs=num_epochs
    )

    # Construct a Reader to read examples from the .tfrecords file
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)

    # Parse an Example to access the Features
    features = tf.parse_single_example(
      serialized_example,
      features = {
        'image/id' : tf.FixedLenFeature([], tf.string),
        'image/encoded'  : tf.FixedLenFeature([], tf.string),
        'image/class/label' : tf.FixedLenFeature([], tf.int64)
      }
    )

    image = tf.image.decode_jpeg(features['image/encoded'], channels=3)
    image = tf.cast(image, tf.float32)
    label = tf.cast(features['image/class/label'], tf.int32)
    image_id = features['image/id']

    if add_summaries:
      tf.image_summary('orig_image', tf.expand_dims(image, 0))

    if augment:
      image = image_augmentations.augment(image, cfg)
    else:
      if cfg.MAINTAIN_ASPECT_RATIO:
        # Resize the image up, then pad with 0s
        params = [image, tf.constant(cfg.INPUT_SIZE), tf.constant(cfg.INPUT_SIZE)]
        output = tf.py_func(image_augmentations.resize_image_maintain_aspect_ratio, params, [tf.float32], name="resize_maintain_aspect_ratio")
        image = output[0]
        image.set_shape([cfg.INPUT_SIZE, cfg.INPUT_SIZE, 3])

      else:
        image = tf.image.resize_images(image, (cfg.INPUT_SIZE, cfg.INPUT_SIZE))

    if add_summaries:
      tf.image_summary('train_image', tf.expand_dims(image, 0))

    image -= cfg.IMAGE_MEAN
    image /= cfg.IMAGE_STD

    # Place the images on another queue that will be sampled by the model
    if shuffle_batch:
      images, sparse_labels, image_ids = tf.train.shuffle_batch(
        [image, label, image_id],
        batch_size=batch_size,
        num_threads=num_threads,
        capacity= capacity, #batch_size * (num_threads + 2),
        # Ensures a minimum amount of shuffling of examples.
        min_after_dequeue= min_after_dequeue, # 3 * batch_size,
        seed = cfg.RANDOM_SEED,
      )

    else:
      images, sparse_labels, image_ids = tf.train.batch(
        [image, label, image_id],
        batch_size=batch_size,
        num_threads=num_threads,
        capacity= capacity, #batch_size * (num_threads + 2),
        enqueue_many=False
      )

  # return a batch of images and their labels
  return images, sparse_labels, image_ids


text:
package org.oscm.billingservice.business.calculation.revenue;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.math.BigDecimal;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatcher;

import org.oscm.billingservice.business.calculation.revenue.RevenueCalculatorBean;
import org.oscm.billingservice.business.calculation.revenue.model.OverallCosts;
import org.oscm.billingservice.business.model.billingresult.BillingDetailsType;
import org.oscm.billingservice.business.model.billingresult.OverallCostsType;
import org.oscm.billingservice.business.model.billingresult.VATType;
import org.oscm.billingservice.dao.BillingDataRetrievalServiceLocal;
import org.oscm.billingservice.dao.model.VatRateDetails;
import org.oscm.billingservice.service.model.BillingInput;
import org.oscm.domobjects.BillingResult;
import org.oscm.test.BigDecimalAsserts;

/**
 * @author kulle
 *
 */
public class RevenueCalculatorBeanVatTest {

    private RevenueCalculatorBean bean;
    private BillingDataRetrievalServiceLocal bdr;

    private BillingResult billingResult;
    private BillingInput billingInput;
    private BillingDetailsType billingDetails;
    private OverallCosts overallCosts;
    private VatRateDetails vatForCustomer;

    @Before
    public void setup() {
        bdr = mock(BillingDataRetrievalServiceLocal.class);
        bean = spy(new RevenueCalculatorBean());
        bean.bdr = bdr;

        billingInput = givenBillingInput("EUR");
        billingDetails = givenBillingDetails();
        billingResult = givenBillingResult();
        overallCosts = givenOverallCosts("EUR", BigDecimal.ZERO);

        vatForCustomer = mock(VatRateDetails.class);
        doReturn(vatForCustomer).when(bdr).loadVATForCustomer(anyLong(),
                anyLong(), anyLong());
    }

    private BillingInput givenBillingInput(String currency) {
        BillingInput.Builder builder = new BillingInput.Builder();
        builder.setCurrencyIsoCode(currency);
        return builder.build();
    }

    private BillingDetailsType givenBillingDetails() {
        OverallCostsType overallCostsType = mock(OverallCostsType.class);
        BillingDetailsType billingDetails = mock(BillingDetailsType.class);
        when(billingDetails.getOverallCosts()).thenReturn(overallCostsType);
        return billingDetails;
    }

    private OverallCosts givenOverallCosts(String currency, BigDecimal amount) {
        OverallCosts costs = OverallCosts.newInstance();
        return costs.set(currency, amount);
    }

    private BillingResult givenBillingResult() {
        return new BillingResult();
    }

    @Test
    public void includeVat_effectiveVatIsNull() {
        // given
        doReturn(null).when(vatForCustomer).getEffectiveVatRateForCustomer();

        // when
        bean.includeVat(billingDetails, billingInput, billingResult,
                overallCosts);

        // then
        OverallCostsType overallCostsType = billingDetails.getOverallCosts();
        verify(overallCostsType, never()).setVAT(any(VATType.class));
    }

    @Test
    public void includeVat_vat() {
        // given
        overallCosts = givenOverallCosts("EUR", BigDecimal.TEN);
        doReturn(vatForCustomer).when(bean).calculateVatCosts(
                any(VatRateDetails.class));
        doReturn(BigDecimal.ONE).when(vatForCustomer)
                .getEffectiveVatRateForCustomer();

        // when
        bean.includeVat(billingDetails, billingInput, billingResult,
                overallCosts);

        // then
        verify(vatForCustomer).setNetCosts(
                argThat(new ArgumentMatcher<BigDecimal>() {

                    @Override
                    public boolean matches(Object argument) {
                        BigDecimal b = (BigDecimal) argument;
                        BigDecimalAsserts.checkEquals(BigDecimal.TEN, b);
                        return true;
                    }
                }));
        OverallCostsType overallCostsType = billingDetails.getOverallCosts();
        verify(overallCostsType).setVAT(any(VATType.class));
    }

    @Test
    public void includeVat_grossAmount() {
        // given
        doReturn(BigDecimal.ONE).when(vatForCustomer).getTotalCosts();

        // when
        bean.includeVat(billingDetails, billingInput, billingResult,
                overallCosts);

        // then
        OverallCostsType overallCostsType = billingDetails.getOverallCosts();
        verify(overallCostsType).setGrossAmount(
                argThat(new ArgumentMatcher<BigDecimal>() {

                    @Override
                    public boolean matches(Object argument) {
                        BigDecimal b = (BigDecimal) argument;
                        BigDecimalAsserts.checkEquals(BigDecimal.ONE, b);
                        return true;
                    }
                }));
    }

}


text:
/*
 * echo_server_activator.c
 *
 *  \date       Sep 21, 2010
 *  \author    	Apache Celix Project Team
 *  \copyright	Apache License, Version 2.0
 */
#include <stdlib.h>

#include "bundle_activator.h"
#include "bundle_context.h"
#include "service_tracker.h"

#include "echo_server.h"
#include "echo_client_private.h"

struct echoActivator {
	echo_client_pt client;
	service_tracker_pt tracker;
};

celix_status_t bundleActivator_create(bundle_context_pt context, void **userData) {
	struct echoActivator * act = malloc(sizeof(*act));
	act->client = NULL;
	act->tracker = NULL;

	*userData = act;

	return CELIX_SUCCESS;
}

celix_status_t bundleActivator_start(void * userData, bundle_context_pt context) {
	struct echoActivator * act = (struct echoActivator *) userData;

	apr_pool_t *pool = NULL;
	service_tracker_pt tracker = NULL;
	echo_client_pt client = NULL;

	bundleContext_getMemoryPool(context, &pool);
	serviceTracker_create(pool, context, ECHO_SERVICE_NAME, NULL, &tracker);
	act->tracker = tracker;

	client = echoClient_create(tracker, pool);
	act->client = client;

	echoClient_start(act->client);
	serviceTracker_open(act->tracker);

	return CELIX_SUCCESS;
}

celix_status_t bundleActivator_stop(void * userData, bundle_context_pt context) {
	struct echoActivator * act = (struct echoActivator *) userData;
	serviceTracker_close(act->tracker);
	echoClient_stop(act->client);

	return CELIX_SUCCESS;
}

celix_status_t bundleActivator_destroy(void * userData, bundle_context_pt context) {
	struct echoActivator * act = (struct echoActivator *) userData;
	echoClient_destroy(act->client);

	return CELIX_SUCCESS;
}