text:
package gr.iti.mklab.sfc.utils;

import java.io.IOException;
import java.io.Reader;
import java.util.Arrays;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.WhitespaceTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;

import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;

public class MinHash {

    private Analyzer analyzer;

	private MinHash() {

    }

	public static MinHash getInstance(int hashBit, int num) {
		MinHash mh = new MinHash();
		mh.analyzer = new MinHashAnalyzer (hashBit, 0, num);

		return mh;
    }

    /**
     * Compare base64 strings for MinHash.
     *
     * @param numOfBits The number of MinHash bits
     * @param str1 MinHash base64 string
     * @param str2 MinHash base64 string
     *
     * @return similarity (0 to 1.0f)
     */
    public static float compare(final int numOfBits, final String str1, final String str2) {
        return compare(numOfBits, BaseEncoding.base64().decode(str1), BaseEncoding.base64().decode(str2));
    }

    /**
     * Compare base64 strings for MinHash.
     *
     * @param str1 MinHash base64 string
     * @param str2 MinHash base64 string
     *
     * @return similarity (0 to 1.0f)
     */
    public static float compare(final String str1, final String str2) {
        return compare(BaseEncoding.base64().decode(str1), BaseEncoding.base64().decode(str2));
    }

    /**
     * Compare bytes for MinHash.
     *
     * @param data1 MinHash bytes
     * @param data2 MinHash bytes
     * @return similarity (0 to 1.0f)
     */
    public static float compare(final byte[] data1, final byte[] data2) {
        return compare(data1.length * 8, data1, data2);
    }

    /**
     * Compare bytes for MinHash.
     *
     * @param numOfBits The number of MinHash bits
     * @param data1 MinHash bytes
     * @param data2 MinHash bytes
     * @return similarity (0 to 1.0f)
     */
    public static float compare(final int numOfBits, final byte[] data1, final byte[] data2) {

        if (data1.length != data2.length) {
            return 0;
        }

        final int count = countSameBits(data1, data2);
        return (float) count / (float) numOfBits;
    }

    protected static int countSameBits(final byte[] data1, final byte[] data2) {
        int count = 0;
        for (int i = 0; i < data1.length; i++) {
            byte b1 = data1[i];
            byte b2 = data2[i];
            for (int j = 0; j < 8; j++) {
                if ((b1 & 1) == (b2 & 1)) {
                    count++;
                }
                b1 >>= 1;
                b2 >>= 1;
            }
        }
        return count;
    }

    /**
     * Create hash functions.
     *
     * @param seed a base seed
     * @param num the number of hash functions.
     * @return
     */
    public static HashFunction[] createHashFunctions(final int seed, final int num) {
        final HashFunction[] hashFunctions = new HashFunction[num];
        for (int i = 0; i < num; i++) {
            hashFunctions[i] = Hashing.murmur3_128(seed + i);
        }

        return hashFunctions;
    }

    /**
     * Calculates MinHash value.
     *
     * @param text a target text
     * @return MinHash value
     * @throws IOException
     */
    public byte[] calculate(final String text) throws IOException {
        byte[] value = null;
        try (TokenStream stream = analyzer.tokenStream("minhash", text)) {
            final CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);
            stream.reset();
            if (stream.incrementToken()) {
                final String minhashValue = termAtt.toString();
                value = BaseEncoding.base64().decode(minhashValue);
            }
            stream.end();
        }
        return value;
    }

    /**
     * Calculates MinHash value.
     *
     * @param analyzer analyzer to parse a text
     * @param text a target text
     * @return MinHash value
     * @throws IOException
     */
    public static byte[] calculate(final Analyzer analyzer, final String text) throws IOException {
        byte[] value = null;
        try (TokenStream stream = analyzer.tokenStream("minhash", text)) {
            final CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);
            stream.reset();
            if (stream.incrementToken()) {
                final String minhashValue = termAtt.toString();
                value = BaseEncoding.base64().decode(minhashValue);
            }
            stream.end();
        }
        return value;
    }

    /**
     * Calculates MinHash value.
     *
     * @param data data with analyzer, text and the number of bits
     * @return MinHash value
     * @throws IOException
     */
    public static byte[] calculate(final Data data) throws IOException {
        return calculate(data.analyzer, data.text);
    }

    /**
     * Calculates MinHash value.
     *
     * @param data data with analyzer, text and the number of bits
     * @return MinHash value
     * @throws IOException
     */
    public static byte[] calculate(final Data[] data) throws IOException {
        int bitSize = 0;
        for (final Data target : data) {
            bitSize += target.numOfBits;
        }
        int pos = 0;
        final BitSet bitSet = new BitSet(bitSize);
        for (final Data target : data) {
            int count = 0;
            final byte[] bytes = calculate(target);
            for (final byte b : bytes) {
                byte bits = b;
                for (int j = 0; j < 8; j++) {
                    bitSet.set(pos, (bits & 0x1) == 0x1);
                    pos++;
                    count++;
                    if (count >= target.numOfBits) {
                        break;
                    }
                    bits >>= 1;
                }
            }
        }
        return bitSet.toByteArray();
    }

    /**
     * Returns a string formatted by bits.
     *
     * @param data
     * @return
     */
    public static String toBinaryString(final byte[] data) {
        if (data == null) {
            return null;
        }
        final StringBuilder buf = new StringBuilder(data.length * 8);
        for (final byte element : data) {
            byte bits = element;
            for (int j = 0; j < 8; j++) {
                if ((bits & 0x80) == 0x80) {
                    buf.append('1');
                } else {
                    buf.append('0');
                }
                bits <<= 1;
            }
            buf.append(' ');
        }
        return buf.toString();
    }

    /**
     * Returns a string formatted by bits.
     *
     * @param data
     * @return
     */
    public static String toString(final byte[] data) {
        if (data == null) {
            return null;
        }

        return BaseEncoding.base64().encode(data);
    }

    /**
     * Count the number of true bits.
     *
     * @param data a target data
     * @return the number of true bits
     */
    public static int bitCount(final byte[] data) {
        int count = 0;
        for (final byte element : data) {
            byte bits = element;
            for (int j = 0; j < 8; j++) {
                if ((bits & 1) == 1) {
                    count++;
                }
                bits >>= 1;
            }
        }
        return count;
    }

    /**
     * Create a target data which has analyzer, text and the number of bits.
     *
     * @param analyzer
     * @param text
     * @param numOfBits
     * @return
     */
    public static Data newData(final Analyzer analyzer, final String text, final int numOfBits) {
        return new Data(analyzer, text, numOfBits);
    }

    public static class Data {
        final int numOfBits;

        final String text;

        final Analyzer analyzer;

        Data(final Analyzer analyzer, final String text, final int numOfBits) {
            this.numOfBits = numOfBits;
            this.text = text;
            this.analyzer = analyzer;
        }
    }

    public static class BitSet {

        final byte[] data;

        final int nbit;

        public BitSet(final int nbit) {
            this.nbit = nbit;
            if (nbit == 0) {
                throw new IllegalArgumentException("nbit is above 0.");
            }

            data = new byte[(nbit - 1) / 8 + 1];
        }

        public void set(final int bitIndex, final boolean value) {
            final int bytePos = bitIndex / 8;
            final int bitPos = bitIndex % 8;

            if (bytePos >= data.length) {
                return;
            }

            switch (bitPos) {
            case 0:
                data[bytePos] = (byte) (data[bytePos] & 0xfe);
                if (value) {
                    data[bytePos] = (byte) (data[bytePos] | 0x01);
                }
                break;
            case 1:
                data[bytePos] = (byte) (data[bytePos] & 0xfd);
                if (value) {
                    data[bytePos] = (byte) (data[bytePos] | 0x02);
                }
                break;
            case 2:
                data[bytePos] = (byte) (data[bytePos] & 0xfb);
                if (value) {
                    data[bytePos] = (byte) (data[bytePos] | 0x04);
                }
                break;
            case 3:
                data[bytePos] = (byte) (data[bytePos] & 0xf7);
                if (value) {
                    data[bytePos] = (byte) (data[bytePos] | 0x08);
                }
                break;
            case 4:
                data[bytePos] = (byte) (data[bytePos] & 0xef);
                if (value) {
                    data[bytePos] = (byte) (data[bytePos] | 0x10);
                }
                break;
            case 5:
                data[bytePos] = (byte) (data[bytePos] & 0xdf);
                if (value) {
                    data[bytePos] = (byte) (data[bytePos] | 0x20);
                }
                break;
            case 6:
                data[bytePos] = (byte) (data[bytePos] & 0xbf);
                if (value) {
                    data[bytePos] = (byte) (data[bytePos] | 0x40);
                }
                break;
            case 7:
                data[bytePos] = (byte) (data[bytePos] & 0x7f);
                if (value) {
                    data[bytePos] = (byte) (data[bytePos] | 0x80);
                }
                break;
            default:
                break;
            }
        }

        public byte[] toByteArray() {
            return data;
        }
    }

	public static class MinHashTokenFilter extends TokenFilter {

	    private final CharTermAttribute charTermAttribute = addAttribute(CharTermAttribute.class);
	    private final PositionIncrementAttribute positionIncrementAttribute = addAttribute(PositionIncrementAttribute.class);

	    private HashFunction[] hashFunctions;

	    private int hashBit;

	    private long[] minHashValues;

	    private String minHash;

	    public MinHashTokenFilter(final TokenStream input, final HashFunction[] hashFunctions, final int hashBit) {
	        super(input);

	        this.hashFunctions = hashFunctions;
	        this.hashBit = hashBit;
	        this.minHashValues = new long[hashFunctions.length];
	    }

	    @Override
	    public final boolean incrementToken() throws IOException {
	        final int functionsSize = hashFunctions.length;
	        while (input.incrementToken()) {
	            final String term = charTermAttribute.toString();
	            for (int i = 0; i < functionsSize; i++) {
	            	final HashCode hashCode = hashFunctions[i].hashString(term);
	                final long value = hashCode.asLong();
	                if (value < minHashValues[i]) {
	                    minHashValues[i] = value;
	                }
	            }
	        }

	        if (minHash != null) {
	            return false;
	        }

	        minHash = BaseEncoding.base64().encode(calculateMinHash(minHashValues, hashBit));

	        charTermAttribute.setEmpty().append(minHash);
	        positionIncrementAttribute.setPositionIncrement(1);

	        return true;
	    }

	    @Override
	    public void reset() throws IOException {
	        super.reset();
	        Arrays.fill(minHashValues, Long.MAX_VALUE);
	        minHash = null;
	    }

	    protected static byte[] calculateMinHash(final long[] minHashValues, final int hashBit) {
	        final int shift = 1;
	        final int radix = 1 << shift;
	        final long mask = radix - 1;
	        int pos = 0;
	        final int nbits = minHashValues.length * hashBit;
	        final BitSet bitSet = new BitSet(nbits);
	        for (long i : minHashValues) {
	            for (int j = 0; j < hashBit; j++) {
	                bitSet.set(pos, (int) (i & mask) == 1);
	                pos++;
	                i >>>= shift;
	            }
	        }
	        return bitSet.toByteArray();
	    }

	}

	public static class MinHashAnalyzer extends Analyzer {

		private HashFunction[] hashFunctions;
		private int hashBit;

	    public MinHashAnalyzer (final int hashBit, final int seed, final int num) {
	    	this.hashFunctions = MinHash.createHashFunctions(seed, num);
	    	this.hashBit = hashBit;
	    }

		@Override
		protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
	        final Tokenizer tokenizer = new WhitespaceTokenizer(reader);
	        final TokenStream stream = new MinHashTokenFilter(tokenizer, hashFunctions, hashBit);

	        return new TokenStreamComponents(tokenizer, stream);
		}

	}
}


text:
import java.util.Vector;
import java.util.Enumeration;

public class ConcreteSubject implements Subject {
	private Vector observerVector = new java.util.Vector();
	public void attach(Observer ob) {
		observerVector.addElement(ob);
	}
	public void detach(Observer ob) {
		observerVector.removeElement(ob);
	}
	public void notifyObservers() {
		Enumeration enumeration = observers();
		while (enumeration.hasMoreElements()) {
			((Observer)enumeration.nextElement()).update();
		}
	}
	public Enumeration observers() {
		return ((Vector)observerVector.clone()).elements();
	}
	public void change() {
		System.out.println("Change in ConcreteSubject");
		notifyObservers();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package de.hsmainz.cs.semgis.arqextension.geometry;

import java.util.List;

import com.hp.hpl.jena.sparql.engine.binding.Binding;
import com.hp.hpl.jena.sparql.expr.NodeValue;
import com.hp.hpl.jena.sparql.function.FunctionEnv;
import com.hp.hpl.jena.vocabulary.XSD;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.simplify.DouglasPeuckerSimplifier;

import de.hsmainz.cs.semgis.arqextension.SingleGeometrySpatialFunction;
import de.hsmainz.cs.semgis.arqextension.datatypes.GeoSPARQLLiteral;

public class Simplify extends SingleGeometrySpatialFunction{

	@Override
	protected NodeValue exec(Geometry g, GeoSPARQLLiteral datatype, Binding binding, List<NodeValue> evalArgs,
			String uri, FunctionEnv env) {
		DouglasPeuckerSimplifier simpl=new DouglasPeuckerSimplifier(g);
		simpl.setDistanceTolerance(evalArgs.get(0).getDouble());
		simpl.setEnsureValid(evalArgs.get(1).getBoolean());
		return makeNodeValue(simpl.getResultGeometry(),datatype);
	}

	@Override
	protected String[] getRestOfArgumentTypes() {
		// TODO Auto-generated method stub
		return new String[]{XSD.xdouble.getURI(),XSD.xboolean.getURI()};
	}

}


text:
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Desktop.Analyzers
{
    /// <summary>
    /// CA3065: Review DataView CollectionString
    /// </summary>
    public abstract class ReviewDataViewCollectionStringFixer : CodeFixProvider
    {
        public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(ReviewDataViewCollectionStringAnalyzer.RuleId);

        public sealed override FixAllProvider GetFixAllProvider()
        {
            // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers
            return WellKnownFixAllProviders.BatchFixer;
        }

        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            // This is to get rid of warning CS1998, please remove when implementing this analyzer
            await new Task(() => { });
            throw new NotImplementedException();
        }
    }
}


text:
<?php

	if(!defined("__IN_SYMPHONY__")) die("
Error

You cannot directly access this file
");

	require_once(EXTENSIONS . '/google_analytics_dashboard/vendor/autoload.php');

	/**
	 *
	 * @author Deux Huit Huit
	 * https://deuxhuithuit.com/
	 *
	 */
	class extension_google_analytics_dashboard extends Extension {

		/**
		 * Name of the extension
		 * @var string
		 */
		const EXT_NAME = 'Google Analytics Dashboard';

		/**
		 * Name of the extension
		 * @var string
		 */
		const PANEL_NAME = 'Google Analytics';

		private static $CHART_TYPES = array('LINE', 'COLUMN', 'BAR', 'TABLE', 'GEO', 'PIE');

		/* ********* DELEGATES ******* */

		public function getSubscribedDelegates() {
			return array(
				array(
					'page'      => '/backend/',
					'delegate'  => 'DashboardPanelRender',
					'callback'  => 'dashboard_render_panel'
				),
				array(
					'page'      => '/backend/',
					'delegate'  => 'DashboardPanelTypes',
					'callback'  => 'dashboard_panel_types'
				),
				array(
					'page'      => '/backend/',
					'delegate'  => 'DashboardPanelOptions',
					'callback'  => 'dashboard_panel_options'
				),
				array(
					'page'      => '/backend/',
					'delegate'  => 'DashboardPanelValidate',
					'callback'  => 'dashboard_panel_validate'
				),
			);
		}

		public function dashboard_render_panel($context) {
			if ($context['type'] != self::PANEL_NAME) {
				return;
			}
			$config = $context['config'];
			$height = isset($config['height']) ? $config['height'] : '225px';
			$i = new XMLElement('iframe', null, array(
				'src' => SYMPHONY_URL . '/extension/google_analytics_dashboard/?p=' . $context['id'],
				'style' => "width:100%;height:$height;",
				'frameborder' => 'no',
			));

			$context['panel']->appendChild($i);
		}

		public function dashboard_panel_types($context) {
			$context['types'][self::PANEL_NAME] = self::PANEL_NAME;
		}

		public function dashboard_panel_options($context) {
			if ($context['type'] != self::PANEL_NAME) {
				return;
			}
			$config = $context['existing_config'];
			if (empty($config)) {
				$handle = General::createHandle(self::EXT_NAME);
				$settings = Symphony::Configuration()->get($handle);
				if (!empty($settings)) {
					$config = $settings;
				}
			}

			$wrapper = new XMLElement('div');

			$fieldset = new XMLElement('fieldset', null, array('class' => 'settings'));
			$fieldset->appendChild(new XMLElement('legend', 'Google Analytics Options'));

			$label = Widget::Label('Google Analytics Service account email', Widget::Input('config[email]', $config['email']));
			$fieldset->appendChild($label);

			$label = Widget::Label('Google Analytics p12 key file path (absolute or DOCROOT relative)', Widget::Input('config[keyfile]', $config['keyfile']));
			$fieldset->appendChild($label);
			$wrapper->appendChild($fieldset);

			$fieldset = new XMLElement('fieldset', null, array('class' => 'settings'));
			$fieldset->appendChild(new XMLElement('legend', 'Reporting Options'));
			$layout = new XMLElement('div', null, array('class' => 'two columns'));
			$fieldset->appendChild($layout);

			if (!$config['start-date']) {
				$config['start-date'] = '30daysAgo';
			}
			$label = Widget::Label('Start date', Widget::Input('config[start-date]', $config['start-date']), 'column');
			$layout->appendChild($label);

			if (!$config['end-date']) {
				$config['end-date'] = 'yesterday';
			}
			$label = Widget::Label('End date', Widget::Input('config[end-date]', $config['end-date']), 'column');
			$layout->appendChild($label);

			if (!$config['dimensions']) {
				$config['dimensions'] = 'ga:date';
			}
			$label = Widget::Label('Dimensions', Widget::Input('config[dimensions]', $config['dimensions']), 'column');
			$layout->appendChild($label);

			if (!$config['metrics']) {
				$config['metrics'] = 'ga:sessions';
			}
			$label = Widget::Label('Metrics', Widget::Input('config[metrics]', $config['metrics']), 'column');
			$layout->appendChild($label);

			if (!$config['type']) {
				$config['type'] = 'LINE';
			}
			$lineOptions = array();
			foreach (self::$CHART_TYPES as $type) {
				$lineOptions[] = array($type, $config['type'] == $type, strtolower($type));
			}
			$label = Widget::Label('Chart type', Widget::Select('config[type]', $lineOptions), 'column');
			$layout->appendChild($label);

			$link = Widget::Anchor('Click here to explore available dimensions and metrics', 'https://developers.google.com/analytics/devguides/reporting/core/dimsmets', null, null, null, array('target' => '_blank'));
			$label = Widget::Label('Help
', $link, 'column');
			$layout->appendChild($label);
			$wrapper->appendChild($fieldset);

			$fieldset = new XMLElement('fieldset', null, array('class' => 'settings'));
			$fieldset->appendChild(new XMLElement('legend', 'Display Options'));

			$label = Widget::Label('Height (include units)', Widget::Input('config[height]', $config['height']));
			$fieldset->appendChild($label);

			$label = Widget::Label('Save as default', Widget::Input('default', 'on', 'checkbox'));
			$fieldset->appendChild($label);
			$wrapper->appendChild($fieldset);

			$context['form'] = $wrapper;
		}

		public function dashboard_panel_validate($context) {
			if ($context['type'] != self::PANEL_NAME) {
				return;
			}
			if (isset($_POST['default']) && $_POST['default'] == 'on') {
				$config = $context['existing_config'];
				if ($config == false) {
					$config = array();
				}
				$handle = General::createHandle(self::EXT_NAME);
				$client = static::createClient($config, $context['id']);
				if (!isset($config['at'])) {
					$config['at'] = $client->getAccessToken();
				}
				foreach ($config as $key => $value) {
					Symphony::Configuration()->set($key, $value, $handle);
				}
				Symphony::Configuration()->write();
			}
		}

		/* ********* GOOGLE CLIENT ******* */

		public static function createClient(array $config, $panelId) {
			$client = new Google_Client();
			$client->setClassConfig('Google_Cache_File', 'directory', TMP);
			$keyfile = $config['keyfile'];
			if (strpos($keyfile, '/') !== 0) {
				$keyfile = DOCROOT . '/' . $keyfile;
			}
			$key = @file_get_contents($keyfile);
			if (!!$key) {
				$cred = new Google_Auth_AssertionCredentials(
					$config['email'],
					array(Google_Service_Analytics::ANALYTICS_READONLY),
					$key
				);
				$client->setAssertionCredentials($cred);
				if ($client->getAuth()->isAccessTokenExpired()) {
					$client->getAuth()->refreshTokenWithAssertion($cred);
				}
			}
			return $client;
		}

		/* ********* INSTALL/UPDATE/UNINSTALL ******* */

		/**
		 * Creates the table needed for the settings of the field
		 */
		public function install() {
			return true;
		}

		/**
		 * This method will update the extension according to the
		 * previous and current version parameters.
		 * @param string $previousVersion
		 */
		public function update($previousVersion = false) {
			return true;
		}

		public function uninstall() {
			return true;
		}

	}


text:
<?php

namespace Inflador;

use Symfony\Component\Yaml\Yaml;

class ConfigFileReader
{
    public function read($configFile)
    {
        if (!file_exists($configFile)) {
            throw new \RuntimeException(sprintf('The config file "%s" does not exist.', $configFile));
        }

        $config = Yaml::parse($configFile);
        if ($this->isConfigNotValid($config)) {
            throw new \RuntimeException(sprintf('The config file "%s" is not valid.', $configFile));
        }

        return $config;
    }

    private function isConfigNotValid($config)
    {
        return !is_array($config);
    }
}


text:
using System;
using System.Linq;
using System.Reflection;
using Baseline;
using Baseline.Reflection;
using BaselineTypeDiscovery;
using Jasper.Attributes;

namespace Jasper;

internal static class ExtensionLoader
{
    private static Assembly[]? _extensions;

    internal static Assembly[] FindExtensionAssemblies()
    {
        if (_extensions != null)
        {
            return _extensions;
        }

        _extensions = AssemblyFinder
            .FindAssemblies(a => a.HasAttribute<JasperModuleAttribute>(), _ => { })
            .Concat(AppDomain.CurrentDomain.GetAssemblies())
            .Distinct()
            .Where(a => a.HasAttribute<JasperModuleAttribute>())
            .ToArray();

        var names = _extensions.Select(x => x.GetName().Name);

        Assembly[] FindDependencies(Assembly a)
        {
            return _extensions!.Where(x => names.Contains(x.GetName().Name)).ToArray();
        }

        _extensions = _extensions.TopologicalSort(FindDependencies, false).ToArray();

        return _extensions;
    }

    internal static void ApplyExtensions(JasperOptions options)
    {
        var assemblies = FindExtensionAssemblies();

        if (!assemblies.Any())
        {
            Console.WriteLine("No Jasper extensions are detected");
            return;
        }

        options.IncludeExtensionAssemblies(assemblies);

        var extensions = assemblies.Select(x => x.GetAttribute<JasperModuleAttribute>()!.JasperExtensionType)
            .Where(x => x != null)
            .Select(x => Activator.CreateInstance(x!)!.As<IJasperExtension>())
            .ToArray();

        options.ApplyExtensions(extensions);
    }
}


text:
package com.heliosapm.shorthand.instrumentor.shorthand.naming;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import com.heliosapm.shorthand.instrumentor.shorthand.ShorthandStaticInterceptor;
import com.heliosapm.shorthand.util.JSExpressionEvaluator;
import com.heliosapm.shorthand.util.StringHelper;

/**
 *
Title: Extractors

 *
Description: Contains various {@link ValueExtractor} classes

 *
Company: Helios Development Group LLC

 * @author Whitehead (nwhitehead AT heliosdev DOT org)
 *
com.heliosapm.shorthand.instrumentor.shorthand.naming.Extractors

 * TODO:  Need to add checks for synchronized calls and print warnings
 */

public class Extractors {

	/** A package name splitter */
	public static final Pattern DOT_SPLITTER = Pattern.compile("\\.");
	/** A white space cleaner */
	public static final Pattern WS_CLEANER = Pattern.compile("\\s+");

	/**
	 * Determines if there is a named attribute method (i.e. no params) with a non void return type in the passed class
	 * @param clazz The class to inspect
	 * @param methodName The name of the attribute method
	 * @return true if one was found, false otherwise
	 */
	public static boolean isMethod(Class<?> clazz, String methodName) {
		Method method = null;
		try {
			try {
				method = clazz.getDeclaredMethod(methodName);
			} catch (NoSuchMethodException e) {
				method = clazz.getMethod(methodName);
			}
			if(method==null) return false;
			return method.getReturnType()!=void.class && method.getReturnType()!=Void.class;
		} catch (Exception ex) {
			return false;
		}
	}

	/**
	 * Returns the first annotation instance found on the method where the annotation's class name or simple class name equals the passed name.
	 * If one is not found, the the class is searched for the same
	 * @param name The name we're searching for
	 * @param member The method or constructor to inspect
	 * @return a [possibly null] annotation
	 */
	public static Annotation getAnnotation(String name, Member member) {
		Annotation annotation = null;
		AnnotatedElement annotatedElement = (AnnotatedElement)member;
		for(Annotation ann: annotatedElement.getAnnotations()) {
			if(ann.annotationType().getName().equals(name) || ann.annotationType().getSimpleName().equals(name)) {
				annotation = ann;
				break;
			}
		}
		if(annotation==null) {
			for(Annotation ann: member.getDeclaringClass().getAnnotations()) {
				if(ann.annotationType().getName().equals(name) || ann.annotationType().getSimpleName().equals(name)) {
					annotation = ann;
					break;
				}
			}
		}
		return annotation;
	}

	/**
	 * Determines if there is a named field in the passed class
	 * @param clazz The class to inspect
	 * @param fieldName The name of the field
	 * @return true if one was found, false otherwise
	 */
	public static boolean isField(Class<?> clazz, String fieldName) {
		Field field = null;
		try {
			try {
				field = clazz.getDeclaredField(fieldName);
			} catch (NoSuchFieldException e) {
				field = clazz.getField(fieldName);
			}
			return field!=null;
		} catch (Exception ex) {
			return false;
		}
	}

	/** Value extractor to return the {@link #toString()} of the "this" object or a field / attribute notation value.
	 * Pattern is [ \\$\\{this\\}|\\$\\{this:(.*?)\\} ]  */
	public static final ValueExtractor THIS = new ValueExtractor() {
		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.shorthand.instrumentor.shorthand.naming.ValueExtractor#getStringReplacement(java.lang.CharSequence, java.lang.Class, java.lang.reflect.Method, java.lang.Object[])
		 */
		@Override
		public String[] getStringReplacement(CharSequence expression, Class<?> clazz, Member member, Object...qualifiers) {
			String expr = WS_CLEANER.matcher(expression.toString().trim()).replaceAll("");
			Matcher matcher = MetricNamingToken.$THIS.pattern.matcher(expr);
			if(!matcher.matches()) throw new RuntimeException("Unexpected non-macthing $THIS expression [" + expression + "]");
			String matchedPattern = matcher.group(0);
			String codePoint = matcher.group(1);
			String extract = null;
			if(matchedPattern.equals("${this}") || matchedPattern.equals("${this:}") ) {
				extract = "$0";
			} else {
				extract = codePoint;
			}
			validateCodePoint("$THIS", clazz, member, extract + ";");
			return toArray("%s", extract);
		}
	};

	/**
	 * Attempts to compile a snippet to validate a code point
	 * @param name The extractor name
	 * @param clazz The class targetted for instrumentation
	 * @param member The method or constructor targetted for instrumentation
	 * @param codePoint The code point
	 */
	private static void validateCodePoint(String name, Class<?> clazz, Member member, String codePoint) {
		ClassPool cPool = new ClassPool(true);
		CtClass ctClass = null;
		cPool.appendClassPath(new ClassClassPath(clazz));
		try {
			ctClass = cPool.get(clazz.getName());
			cPool.importPackage(ShorthandStaticInterceptor.class.getPackage().getName());
			CtMethod ctMethod = ctClass.getMethod(member.getName(), StringHelper.getMemberDescriptor(member));
			ctClass.removeMethod(ctMethod);
			ctMethod.insertAfter(codePoint);
			ctClass.addMethod(ctMethod);
			ctClass.writeFile(System.getProperty("java.io.tmpdir") + File.separator + "js");
			ctClass.toBytecode();
		} catch (Exception ex) {
			throw new RuntimeException("Failed to validate " + name + "] codepoint for [" + clazz.getName() + "." + member.getName() + "]. Codepoint was [" + codePoint + "]", ex);
		} finally {
			if(ctClass!=null) ctClass.detach();
		}
	}

	/** Value extractor to return the {@link #toString()} of the indexed argument object or a field/attribute notation value
	 * Pattern is [ \\$\\{arg\\[(\\d+)\\]\\}|\\$\\{arg:(.*?)\\} ]
	 * */
	public static final ValueExtractor ARG = new ValueExtractor() {
		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.shorthand.instrumentor.shorthand.naming.ValueExtractor#getStringReplacement(java.lang.CharSequence, java.lang.Class, java.lang.reflect.Method, java.lang.Object[])
		 */
		@Override
		public String[] getStringReplacement(CharSequence expression, Class<?> clazz, Member member, Object...qualifiers) {
			String expr = WS_CLEANER.matcher(expression.toString().trim()).replaceAll("");
			Matcher matcher = MetricNamingToken.$ARG.pattern.matcher(expr);
			if(!matcher.matches()) throw new RuntimeException("Unexpected non-macthing $ARG expression [" + expression + "]");
			String matchedIndex = matcher.group(1);
			String codePoint = matcher.group(2);
			int index = -1;
			String extract = null;
			if(codePoint==null || codePoint.trim().isEmpty()) {
				try { index = Integer.parseInt(matchedIndex); } catch (Exception x) {
					throw new RuntimeException("Invalid $ARG expression [" + expression + "]. Neither a code-point or an index were matched");
				}
				Class<?>[] paramTypes = null;
				if(member instanceof Constructor) {
					paramTypes = ((Constructor<?>)member).getParameterTypes();
				} else {
					paramTypes = ((Method)member).getParameterTypes();
				}
				Class<?> argType = paramTypes[index];
				index++;
				if(argType.isPrimitive()) {
					extract = String.format("(\"\" + $%s)", index);
				} else {
					extract = String.format("ShorthandStaticInterceptor.nvl($%s)", index, index );
				}

			} else {
				extract = codePoint;
			}
			validateCodePoint("$ARG", clazz, member, extract + ";");
			return toArray("%s", extract);
		}
	};

	/** Value extractor to return the {@link #toString()} of the invocation return value object or a field/attribute notation value
	 *   Pattern is [ \\$\\{return(?::(.*))?\\} ]
	 * */
//	public static final ValueExtractor RETURN = new ValueExtractor() {
//		/**
//		 * {@inheritDoc}
//		 * @see com.heliosapm.shorthand.instrumentor.shorthand.naming.ValueExtractor#getStringReplacement(java.lang.CharSequence, java.lang.Class, java.lang.reflect.Method, java.lang.Object[])
//		 */
//		@Override
//		public String[] getStringReplacement(CharSequence expression, Class<?> clazz, Method method, Object...qualifiers) {
//			String expr = WS_CLEANER.matcher(expression.toString().trim()).replaceAll("");
//			Class<?> returnType = method.getReturnType();
//			if(returnType==Void.class || returnType==void.class) {
//				throw new RuntimeException("Invalid use of $RETURN token since method [" + clazz.getName() + "." + method.getName() + "] has a void return type");
//			}
//			String extract = null;
//			if(expr.equals("${return}") || expr.equals("${return:}")) {
//				if(returnType.isPrimitive()) {
//					extract = "$_";
//				} else {
//					extract = "($_==null ? \"\" : $_.toString())";
//				}
//			} else {
//				Matcher matcher = MetricNamingToken.$RETURN.pattern.matcher(expr);
//				if(!matcher.matches()) throw new RuntimeException("Unexpected non-macthing $RETURN expression [" + expression + "]");
//				extract = matcher.group(1);
//			}
//			validateCodePoint("$RETURN", clazz, method, extract + ";");
//			return toArray("%s", extract);
//		}
//	};

	/** Value extractor to validate and return the code point of a freeform $JAVA naming token
	 *   Pattern is [ \\$\\{java(?::(.*))?\\} ]
	 * */
	public static final ValueExtractor JAVA = new ValueExtractor() {
		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.shorthand.instrumentor.shorthand.naming.ValueExtractor#getStringReplacement(java.lang.CharSequence, java.lang.Class, java.lang.reflect.Method, java.lang.Object[])
		 */
		@Override
		public String[] getStringReplacement(CharSequence expression, Class<?> clazz, Member member, Object...qualifiers) {
			String expr = WS_CLEANER.matcher(expression.toString().trim()).replaceAll("");
			Matcher matcher = MetricNamingToken.$JAVA.pattern.matcher(expr);
			if(!matcher.matches()) throw new RuntimeException("Unexpected non-macthing $JAVAexpression [" + expression + "]");
			String extract = String.format("(\"\" + (%s))",  matcher.group(1));
			validateCodePoint("$JAVA", clazz, member, extract + ";");
			return toArray("%s", extract);
		}
	};

	/** Value extractor to return the {@link #toString()} of the value of the annotation attribute on the method (or failing that, on the class) or a field/attribute notation value.
	  Pattern is [ \\$\\{(.*?)@\\((.*?)\\)(.*?)\\} ]  */
	public static final ValueExtractor ANNOTATION = new ValueExtractor() {
		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.shorthand.instrumentor.shorthand.naming.ValueExtractor#getStringReplacement(java.lang.CharSequence, java.lang.Class, java.lang.reflect.Method, java.lang.Object[])
		 */
		@Override
		public String[] getStringReplacement(CharSequence expression, Class<?> clazz, Member member, Object...qualifiers) {
			String expr = WS_CLEANER.matcher(expression.toString().trim()).replaceAll("");
			Matcher matcher = MetricNamingToken.$ANNOTATION.pattern.matcher(expr);
			if(!matcher.matches()) throw new RuntimeException("Unexpected non-macthing $ANNOTATION expression [" + expr + "]");
			String preAnnotationCode = matcher.group(1);
			String annotationName = matcher.group(2);
			String postAnnotationCode = matcher.group(3);

			Annotation ann = getAnnotation(annotationName, member);
			if(ann==null) {
				throw new RuntimeException("No annotation named [" + annotationName + "] found on  [" + clazz.getName() + "." + member.getName() + "] for expression [" + expr + "]");
			}

			if(preAnnotationCode==null) preAnnotationCode=""; else preAnnotationCode = preAnnotationCode.trim();
			if(postAnnotationCode==null) postAnnotationCode=""; else postAnnotationCode = postAnnotationCode.trim();

			Object result = null;
			try {
				result = JSExpressionEvaluator.getInstance().evaluate(String.format("%s##0##%s", preAnnotationCode, postAnnotationCode), ann);
			} catch (Exception ex) {
				throw new RuntimeException("Failed to evaluate $ANNOTATION expression [" + expr + "]", ex);
			}

			if(result==null) throw new RuntimeException("$ANNOTATION expression [" + expr + "] returned null");

			return toArray(result.toString());
		}

	};

	/** A package name or member value extractor. Pattern is [ \\$\\{package(?:\\[(\\d+)\\])?\\} ] */
	public static final ValueExtractor PACKAGE = new ValueExtractor() {
		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.shorthand.instrumentor.shorthand.naming.ValueExtractor#getStringReplacement(java.lang.CharSequence, java.lang.Class, java.lang.reflect.Method, java.lang.Object[])
		 */
		@Override
		public String[] getStringReplacement(CharSequence expression, Class<?> clazz, Member member, Object... args) {
			Matcher matcher = MetricNamingToken.$PACKAGE.pattern.matcher(expression);
			if(!matcher.matches()) throw new RuntimeException("Unexpected non-macthing $PACKAGE expression [" + expression + "]");
			String strIndex = matcher.group(1);
			if(strIndex==null || strIndex.trim().isEmpty()) {
				return toArray(clazz.getPackage().getName().replace('.', '/'));
			}
			int index = -1;
			try {
				index = Integer.parseInt(matcher.group(1));
			} catch (Exception ex) {
				throw new RuntimeException("Failed to extract index from  $PACKAGE expression [" + expression + "]", ex);
			}
			return toArray(DOT_SPLITTER.split(clazz.getPackage().getName())[index]);
		}
	};

	/** A simple class name value extractor */
	public static final ValueExtractor CLASS = new ValueExtractor() {
		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.shorthand.instrumentor.shorthand.naming.ValueExtractor#getStringReplacement(java.lang.CharSequence, java.lang.Class, java.lang.reflect.Method, java.lang.Object[])
		 */
		@Override
		public String[] getStringReplacement(CharSequence expression, Class<?> clazz, Member member, Object... args) {
			return toArray(clazz.getSimpleName());
		}
	};

	/** A method name value extractor */
	public static final ValueExtractor METHOD = new ValueExtractor() {
		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.shorthand.instrumentor.shorthand.naming.ValueExtractor#getStringReplacement(java.lang.CharSequence, java.lang.Class, java.lang.reflect.Method, java.lang.Object[])
		 */
		@Override
		public String[] getStringReplacement(CharSequence expression, Class<?> clazz, Member member, Object... args) {
			return toArray(member.getName());
		}
	};

	/**
	 * Convenience method to return a varg as a first class array
	 * @param strings The strings to return as an array
	 * @return a string array
	 */
	public static String[] toArray(String...strings) {
		return strings;
	}

	/**
	 * Simple out formatted logger
	 * @param fmt The format of the message
	 * @param args The message arguments
	 */
	public static void log(String fmt, Object...args) {
		System.out.println(String.format(fmt, args));
	}

}

/*
	Some Test Groovy for these patterns
*/

/*
==================================================================================
	$PACKAGE
==================================================================================
import java.util.regex.*;
p = Pattern.compile('\\$\\{package(?:\\[(\\d+)\\])?\\}');
v = 'foo.bar.snafu';
expr = '${package[0]}';

m = p.matcher(expr);
if(!m.matches()) {
    println "No Match";
} else {
    ind = m.group(1);
    if(ind==null || ind.trim().isEmpty()) {
        println "--->[${v.replace('.', '/')}]";
    } else {
        int index = Integer.parseInt(ind.trim());
        println "--->[${v.split("\\.")[index]}]";

    }
}

*/


text:
package net.mgsx.game.plugins.btree.tasks;

import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.ai.btree.annotation.TaskAttribute;

import net.mgsx.game.core.annotations.TaskAsset;
import net.mgsx.game.core.storage.EntityGroup;
import net.mgsx.game.core.storage.EntityGroupStorage;
import net.mgsx.game.plugins.btree.BTreePlugin.EntityLeafTask;
import net.mgsx.game.plugins.btree.annotations.TaskAlias;
import net.mgsx.game.plugins.core.components.Transform2DComponent;

@TaskAlias("emit")
public class EntityGroupEmitter extends EntityLeafTask
{
	@TaskAsset(EntityGroup.class)
	@TaskAttribute(required=true)
	public String fileName;

	/** when relative, current entity position is added to emitted entities position. When not (absolute)
	 * then emitted entities position is set to current entity position. */
	@TaskAttribute
	public boolean relative = false;

	@Override
	public com.badlogic.gdx.ai.btree.Task.Status execute()
	{
		Transform2DComponent selfTransform = Transform2DComponent.components.get(getEntity());
		for(Entity entityClone : EntityGroupStorage.get(getObject().assets, getObject().engine, fileName)){
			if(selfTransform != null){
				Transform2DComponent transform = Transform2DComponent.components.get(entityClone);
				if(transform != null){
					if(relative){
						transform.position.add(selfTransform.position);
					}else{
						transform.position.set(selfTransform.position);
					}
				}
			}
		}
		return Status.SUCCEEDED;
	}
}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">


text:
module Uber
  module Delivery
    class Delivery < Base
      attr_accessor :courier, :created_at, :currency_code, :delivery_id,
                    :dropoff, :fee, :items, :order_reference_id, :pickup, :quote_id,
                    :status, :tracking_url, :batch

      def created_at
        @created_at && ::Time.at(@created_at)
      end
    end
  end
end


text:
package org.nusco.narjillos.persistence.serialization;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.nusco.narjillos.core.physics.Vector;
import org.nusco.narjillos.creature.body.Mouth;
import org.nusco.narjillos.persistence.serialization.JSON;

public class JSONMouthSerializationTest {

	@Test
	public void serializesAndDeserializesCompasses() {
		Mouth mouth = new Mouth();
		mouth.tick(Vector.ZERO, Vector.polar(179, 1), 15);

		String json = JSON.toJson(mouth, Mouth.class);
		Mouth deserialized = JSON.fromJson(json, Mouth.class);

		assertEquals(mouth.getDirection(), deserialized.getDirection());
	}
}


text:
cask "font-noto-sans-egyptian-hieroglyphs" do
  version :latest
  sha256 :no_check

  url "https://noto-website-2.storage.googleapis.com/pkgs/NotoSansEgyptianHieroglyphs-unhinted.zip",
      verified: "noto-website-2.storage.googleapis.com/"
  name "Noto Sans Egyptian Hieroglyphs"
  homepage "https://www.google.com/get/noto/#sans-egyp"

  font "NotoSansEgyptianHieroglyphs-Regular.ttf"
end


text:
package executor

import (
	"github.com/pingcap/errors"
	"github.com/pingcap/tidb/distsql"
	"github.com/pingcap/tidb/expression"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/parser/model"
	"github.com/pingcap/tidb/parser/mysql"
	plannercore "github.com/pingcap/tidb/planner/core"
	"github.com/pingcap/tidb/sessionctx"
	transaction "github.com/pingcap/tidb/store/driver/txn"
	"github.com/pingcap/tidb/table"
	"github.com/pingcap/tidb/table/tables"
	"github.com/pingcap/tidb/tablecodec"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/chunk"
	"github.com/pingcap/tidb/util/codec"
	"github.com/pingcap/tidb/util/rowcodec"
)

type memIndexReader struct {
	ctx           sessionctx.Context
	index         *model.IndexInfo
	table         *model.TableInfo
	kvRanges      []kv.KeyRange
	desc          bool
	conditions    []expression.Expression
	addedRows     [][]types.Datum
	addedRowsLen  int
	retFieldTypes []*types.FieldType
	outputOffset  []int
	// belowHandleCols is the handle's position of the below scan plan.
	belowHandleCols plannercore.HandleCols
}

func buildMemIndexReader(us *UnionScanExec, idxReader *IndexReaderExecutor) *memIndexReader {
	kvRanges := idxReader.kvRanges
	outputOffset := make([]int, 0, len(us.columns))
	for _, col := range idxReader.outputColumns {
		outputOffset = append(outputOffset, col.Index)
	}
	return &memIndexReader{
		ctx:             us.ctx,
		index:           idxReader.index,
		table:           idxReader.table.Meta(),
		kvRanges:        kvRanges,
		desc:            us.desc,
		conditions:      us.conditions,
		retFieldTypes:   retTypes(us),
		outputOffset:    outputOffset,
		belowHandleCols: us.belowHandleCols,
	}
}

func (m *memIndexReader) getMemRows() ([][]types.Datum, error) {
	tps := make([]*types.FieldType, 0, len(m.index.Columns)+1)
	cols := m.table.Columns
	for _, col := range m.index.Columns {
		tps = append(tps, &cols[col.Offset].FieldType)
	}
	switch {
	case m.table.PKIsHandle:
		for _, col := range m.table.Columns {
			if mysql.HasPriKeyFlag(col.Flag) {
				tps = append(tps, &col.FieldType)
				break
			}
		}
	case m.table.IsCommonHandle:
		pkIdx := tables.FindPrimaryIndex(m.table)
		for _, pkCol := range pkIdx.Columns {
			colInfo := m.table.Columns[pkCol.Offset]
			tps = append(tps, &colInfo.FieldType)
		}
	default: // ExtraHandle Column tp.
		tps = append(tps, types.NewFieldType(mysql.TypeLonglong))
	}

	mutableRow := chunk.MutRowFromTypes(m.retFieldTypes)
	err := iterTxnMemBuffer(m.ctx, m.kvRanges, func(key, value []byte) error {
		data, err := m.decodeIndexKeyValue(key, value, tps)
		if err != nil {
			return err
		}

		mutableRow.SetDatums(data...)
		matched, _, err := expression.EvalBool(m.ctx, m.conditions, mutableRow.ToRow())
		if err != nil || !matched {
			return err
		}
		m.addedRows = append(m.addedRows, data)
		return nil
	})

	if err != nil {
		return nil, err
	}
	// TODO: After refine `IterReverse`, remove below logic and use `IterReverse` when do reverse scan.
	if m.desc {
		reverseDatumSlice(m.addedRows)
	}
	return m.addedRows, nil
}

func (m *memIndexReader) decodeIndexKeyValue(key, value []byte, tps []*types.FieldType) ([]types.Datum, error) {
	hdStatus := tablecodec.HandleDefault
	if mysql.HasUnsignedFlag(tps[len(tps)-1].Flag) {
		hdStatus = tablecodec.HandleIsUnsigned
	}
	colInfos := tables.BuildRowcodecColInfoForIndexColumns(m.index, m.table)
	colInfos = tables.TryAppendCommonHandleRowcodecColInfos(colInfos, m.table)
	values, err := tablecodec.DecodeIndexKV(key, value, len(m.index.Columns), hdStatus, colInfos)
	if err != nil {
		return nil, errors.Trace(err)
	}

	ds := make([]types.Datum, 0, len(m.outputOffset))
	for _, offset := range m.outputOffset {
		d, err := tablecodec.DecodeColumnValue(values[offset], tps[offset], m.ctx.GetSessionVars().Location())
		if err != nil {
			return nil, err
		}
		ds = append(ds, d)
	}
	return ds, nil
}

type memTableReader struct {
	ctx           sessionctx.Context
	table         *model.TableInfo
	columns       []*model.ColumnInfo
	kvRanges      []kv.KeyRange
	desc          bool
	conditions    []expression.Expression
	addedRows     [][]types.Datum
	retFieldTypes []*types.FieldType
	colIDs        map[int64]int
	buffer        allocBuf
	pkColIDs      []int64
}

type allocBuf struct {
	// cache for decode handle.
	handleBytes []byte
	rd          *rowcodec.BytesDecoder
}

func buildMemTableReader(us *UnionScanExec, tblReader *TableReaderExecutor) *memTableReader {
	colIDs := make(map[int64]int, len(us.columns))
	for i, col := range us.columns {
		colIDs[col.ID] = i
	}

	colInfo := make([]rowcodec.ColInfo, 0, len(us.columns))
	for i := range us.columns {
		col := us.columns[i]
		colInfo = append(colInfo, rowcodec.ColInfo{
			ID:         col.ID,
			IsPKHandle: us.table.Meta().PKIsHandle && mysql.HasPriKeyFlag(col.Flag),
			Ft:         rowcodec.FieldTypeFromModelColumn(col),
		})
	}

	pkColIDs := tables.TryGetCommonPkColumnIds(us.table.Meta())
	if len(pkColIDs) == 0 {
		pkColIDs = []int64{-1}
	}
	rd := rowcodec.NewByteDecoder(colInfo, pkColIDs, nil, us.ctx.GetSessionVars().Location())
	return &memTableReader{
		ctx:           us.ctx,
		table:         us.table.Meta(),
		columns:       us.columns,
		kvRanges:      tblReader.kvRanges,
		desc:          us.desc,
		conditions:    us.conditions,
		retFieldTypes: retTypes(us),
		colIDs:        colIDs,
		buffer: allocBuf{
			handleBytes: make([]byte, 0, 16),
			rd:          rd,
		},
		pkColIDs: pkColIDs,
	}
}

// TODO: Try to make memXXXReader lazy, There is no need to decode many rows when parent operator only need 1 row.
func (m *memTableReader) getMemRows() ([][]types.Datum, error) {
	mutableRow := chunk.MutRowFromTypes(m.retFieldTypes)
	err := iterTxnMemBuffer(m.ctx, m.kvRanges, func(key, value []byte) error {
		row, err := m.decodeRecordKeyValue(key, value)
		if err != nil {
			return err
		}

		mutableRow.SetDatums(row...)
		matched, _, err := expression.EvalBool(m.ctx, m.conditions, mutableRow.ToRow())
		if err != nil || !matched {
			return err
		}
		m.addedRows = append(m.addedRows, row)
		return nil
	})
	if err != nil {
		return nil, err
	}

	// TODO: After refine `IterReverse`, remove below logic and use `IterReverse` when do reverse scan.
	if m.desc {
		reverseDatumSlice(m.addedRows)
	}
	return m.addedRows, nil
}

func (m *memTableReader) decodeRecordKeyValue(key, value []byte) ([]types.Datum, error) {
	handle, err := tablecodec.DecodeRowKey(key)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return m.decodeRowData(handle, value)
}

// decodeRowData uses to decode row data value.
func (m *memTableReader) decodeRowData(handle kv.Handle, value []byte) ([]types.Datum, error) {
	values, err := m.getRowData(handle, value)
	if err != nil {
		return nil, err
	}
	ds := make([]types.Datum, 0, len(m.columns))
	for _, col := range m.columns {
		offset := m.colIDs[col.ID]
		d, err := tablecodec.DecodeColumnValue(values[offset], &col.FieldType, m.ctx.GetSessionVars().Location())
		if err != nil {
			return nil, err
		}
		ds = append(ds, d)
	}
	return ds, nil
}

// getRowData decodes raw byte slice to row data.
func (m *memTableReader) getRowData(handle kv.Handle, value []byte) ([][]byte, error) {
	colIDs := m.colIDs
	pkIsHandle := m.table.PKIsHandle
	buffer := &m.buffer
	ctx := m.ctx.GetSessionVars().StmtCtx
	if rowcodec.IsNewFormat(value) {
		return buffer.rd.DecodeToBytes(colIDs, handle, value, buffer.handleBytes)
	}
	values, err := tablecodec.CutRowNew(value, colIDs)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if values == nil {
		values = make([][]byte, len(colIDs))
	}
	// Fill the handle and null columns.
	for _, col := range m.columns {
		id := col.ID
		offset := colIDs[id]
		if m.table.IsCommonHandle {
			for i, colID := range m.pkColIDs {
				if colID == col.ID && !types.NeedRestoredData(&col.FieldType) {
					// Only try to decode handle when there is no corresponding column in the value.
					// This is because the information in handle may be incomplete in some cases.
					// For example, prefixed clustered index like 'primary key(col1(1))' only store the leftmost 1 char in the handle.
					if values[offset] == nil {
						values[offset] = handle.EncodedCol(i)
						break
					}
				}
			}
		} else if (pkIsHandle && mysql.HasPriKeyFlag(col.Flag)) || id == model.ExtraHandleID {
			var handleDatum types.Datum
			if mysql.HasUnsignedFlag(col.Flag) {
				// PK column is Unsigned.
				handleDatum = types.NewUintDatum(uint64(handle.IntValue()))
			} else {
				handleDatum = types.NewIntDatum(handle.IntValue())
			}
			handleData, err1 := codec.EncodeValue(ctx, buffer.handleBytes, handleDatum)
			if err1 != nil {
				return nil, errors.Trace(err1)
			}
			values[offset] = handleData
			continue
		}
		if hasColVal(values, colIDs, id) {
			continue
		}
		// no need to fill default value.
		values[offset] = []byte{codec.NilFlag}
	}

	return values, nil
}

func hasColVal(data [][]byte, colIDs map[int64]int, id int64) bool {
	offset, ok := colIDs[id]
	if ok && data[offset] != nil {
		return true
	}
	return false
}

type processKVFunc func(key, value []byte) error

func iterTxnMemBuffer(ctx sessionctx.Context, kvRanges []kv.KeyRange, fn processKVFunc) error {
	txn, err := ctx.Txn(true)
	if err != nil {
		return err
	}

	tempTableData := ctx.GetSessionVars().TemporaryTableData
	for _, rg := range kvRanges {
		iter := txn.GetMemBuffer().SnapshotIter(rg.StartKey, rg.EndKey)
		if tempTableData != nil {
			snapIter, err := tempTableData.Iter(rg.StartKey, rg.EndKey)
			if err != nil {
				return err
			}

			iter, err = transaction.NewUnionIter(iter, snapIter, false)
			if err != nil {
				return err
			}
		}

		for ; iter.Valid(); err = iter.Next() {
			if err != nil {
				return err
			}
			// check whether the key was been deleted.
			if len(iter.Value()) == 0 {
				continue
			}
			err = fn(iter.Key(), iter.Value())
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func reverseDatumSlice(rows [][]types.Datum) {
	for i, j := 0, len(rows)-1; i < j; i, j = i+1, j-1 {
		rows[i], rows[j] = rows[j], rows[i]
	}
}

func (m *memIndexReader) getMemRowsHandle() ([]kv.Handle, error) {
	handles := make([]kv.Handle, 0, m.addedRowsLen)
	err := iterTxnMemBuffer(m.ctx, m.kvRanges, func(key, value []byte) error {
		handle, err := tablecodec.DecodeIndexHandle(key, value, len(m.index.Columns))
		if err != nil {
			return err
		}
		handles = append(handles, handle)
		return nil
	})
	if err != nil {
		return nil, err
	}

	if m.desc {
		for i, j := 0, len(handles)-1; i < j; i, j = i+1, j-1 {
			handles[i], handles[j] = handles[j], handles[i]
		}
	}
	return handles, nil
}

type memIndexLookUpReader struct {
	ctx           sessionctx.Context
	index         *model.IndexInfo
	columns       []*model.ColumnInfo
	table         table.Table
	desc          bool
	conditions    []expression.Expression
	retFieldTypes []*types.FieldType

	idxReader *memIndexReader

	// partition mode
	partitionMode     bool                  // if it is accessing a partition table
	partitionTables   []table.PhysicalTable // partition tables to access
	partitionKVRanges [][]kv.KeyRange       // kv ranges for these partition tables
}

func buildMemIndexLookUpReader(us *UnionScanExec, idxLookUpReader *IndexLookUpExecutor) *memIndexLookUpReader {
	kvRanges := idxLookUpReader.kvRanges
	outputOffset := []int{len(idxLookUpReader.index.Columns)}
	memIdxReader := &memIndexReader{
		ctx:             us.ctx,
		index:           idxLookUpReader.index,
		table:           idxLookUpReader.table.Meta(),
		kvRanges:        kvRanges,
		desc:            idxLookUpReader.desc,
		retFieldTypes:   retTypes(us),
		outputOffset:    outputOffset,
		belowHandleCols: us.belowHandleCols,
	}

	return &memIndexLookUpReader{
		ctx:           us.ctx,
		index:         idxLookUpReader.index,
		columns:       idxLookUpReader.columns,
		table:         idxLookUpReader.table,
		desc:          idxLookUpReader.desc,
		conditions:    us.conditions,
		retFieldTypes: retTypes(us),
		idxReader:     memIdxReader,

		partitionMode:     idxLookUpReader.partitionTableMode,
		partitionKVRanges: idxLookUpReader.partitionKVRanges,
		partitionTables:   idxLookUpReader.prunedPartitions,
	}
}

func (m *memIndexLookUpReader) getMemRows() ([][]types.Datum, error) {
	kvRanges := [][]kv.KeyRange{m.idxReader.kvRanges}
	tbls := []table.Table{m.table}
	if m.partitionMode {
		m.idxReader.desc = false // keep-order if always false for IndexLookUp reading partitions so this parameter makes no sense
		kvRanges = m.partitionKVRanges
		tbls = tbls[:0]
		for _, p := range m.partitionTables {
			tbls = append(tbls, p)
		}
	}

	tblKVRanges := make([]kv.KeyRange, 0, 16)
	numHandles := 0
	for i, tbl := range tbls {
		m.idxReader.kvRanges = kvRanges[i]
		handles, err := m.idxReader.getMemRowsHandle()
		if err != nil {
			return nil, err
		}
		if len(handles) == 0 {
			continue
		}
		numHandles += len(handles)
		tblKVRanges = append(tblKVRanges, distsql.TableHandlesToKVRanges(getPhysicalTableID(tbl), handles)...)
	}
	if numHandles == 0 {
		return nil, nil
	}

	colIDs := make(map[int64]int, len(m.columns))
	for i, col := range m.columns {
		colIDs[col.ID] = i
	}

	tblInfo := m.table.Meta()
	colInfos := make([]rowcodec.ColInfo, 0, len(m.columns))
	for i := range m.columns {
		col := m.columns[i]
		colInfos = append(colInfos, rowcodec.ColInfo{
			ID:         col.ID,
			IsPKHandle: tblInfo.PKIsHandle && mysql.HasPriKeyFlag(col.Flag),
			Ft:         rowcodec.FieldTypeFromModelColumn(col),
		})
	}
	pkColIDs := tables.TryGetCommonPkColumnIds(tblInfo)
	if len(pkColIDs) == 0 {
		pkColIDs = []int64{-1}
	}
	rd := rowcodec.NewByteDecoder(colInfos, pkColIDs, nil, nil)
	memTblReader := &memTableReader{
		ctx:           m.ctx,
		table:         m.table.Meta(),
		columns:       m.columns,
		kvRanges:      tblKVRanges,
		conditions:    m.conditions,
		addedRows:     make([][]types.Datum, 0, numHandles),
		retFieldTypes: m.retFieldTypes,
		colIDs:        colIDs,
		pkColIDs:      pkColIDs,
		buffer: allocBuf{
			handleBytes: make([]byte, 0, 16),
			rd:          rd,
		},
	}

	return memTblReader.getMemRows()
}


text:
package org.spongepowered.common.world.gen;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.spongepowered.api.GameRegistry;
import org.spongepowered.api.world.gen.WorldGeneratorModifier;
import org.spongepowered.common.Sponge;
import org.spongepowered.common.registry.SpongeGameRegistry;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Class that handles the registry of world generators. The methods in
 * {@link GameRegistry} simply call methods on this class.
 *
 * @see GameRegistry#getType(Class, String) with {@link WorldGeneratorModifier}
 * @see GameRegistry#getAllOf(Class) with {@link WorldGeneratorModifier}
 * @see GameRegistry#registerWorldGeneratorModifier(WorldGeneratorModifier)
 */
public final class WorldGeneratorRegistry {

    public static WorldGeneratorRegistry getInstance() {
        SpongeGameRegistry registry = (SpongeGameRegistry) Sponge.getGame().getRegistry();
        return registry.getWorldGeneratorRegistry();
    }

    /**
     * Map of id => modifier.
     */
    private final Map<String, WorldGeneratorModifier> modifiers = Maps.newHashMap();

    public Map<String, WorldGeneratorModifier> viewModifiersMap() {
        return Collections.unmodifiableMap(this.modifiers);
    }

    public void registerModifier(WorldGeneratorModifier modifier) {
        checkNotNull(modifier, "modifier");
        String id = modifier.getId();
        checkId(id, "World generator ID");

        this.modifiers.put(id.toLowerCase(), modifier);
    }

    private void checkId(String id, String subject) {
        checkArgument(id.indexOf(' ') == -1, subject + " " + id + " may not contain a space");
    }

    /**
     * Gets the string list for the modifiers, for saving purposes.
     *
     * @param modifiers
     *            The modifiers
     * @return The string list
     * @throws IllegalArgumentException
     *             If any of the modifiers is not registered
     */
    public ImmutableCollection<String> toIds(Collection<WorldGeneratorModifier> modifiers) {
        ImmutableList.Builder<String> ids = ImmutableList.builder();
        for (WorldGeneratorModifier modifier : modifiers) {
            checkNotNull(modifier, "modifier (in collection)");
            String id = modifier.getId();
            checkArgument(this.modifiers.containsKey(id),
                    "unregistered modifier in collection");
            ids.add(id);
        }
        return ids.build();
    }

    /**
     * Gets the world generator modifiers with the given id. If no world
     * generator modifier can be found with a certain id, a message is logged
     * and the id is skipped.
     *
     * @param ids
     *            The ids
     * @return The modifiers
     */
    public Collection<WorldGeneratorModifier> toModifiers(Collection<String> ids) {
        List<WorldGeneratorModifier> modifiers = Lists.newArrayList();
        for (String id : ids) {
            WorldGeneratorModifier modifier = this.modifiers.get(id);
            if (modifier != null) {
                modifiers.add(modifier);
            } else {
                Sponge.getLogger().error("World generator modifier with id " + id + " not found. Missing plugin?");
            }
        }
        return modifiers;
    }

    /**
     * Checks that all modifiers are registered.
     *
     * @param modifiers
     *            The modifiers
     * @throws IllegalArgumentException
     *             If a modifier is not registered
     */
    public void checkAllRegistered(Collection<WorldGeneratorModifier> modifiers) {
        // We simply call toIds, that checks all world generators
        toIds(modifiers);
    }

}


text:
require 'rspec-system/spec_helper'
require 'rspec-system-puppet/helpers'

include RSpecSystemPuppet::Helpers

RSpec.configure do |c|
  proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
  c.tty = true
  c.include RSpecSystemPuppet::Helpers

  c.before :suite do
    puppet_install
    puppet_module_install(:source => proj_root, :module_name => 'masq')
    shell('puppet module install puppetlabs-firewall')
    shell('puppet module install fiddyspence-sysctl
  end
end


text:
package ru.sdroman.springbeans.storages;

import ru.sdroman.springbeans.models.User;
import ru.sdroman.springbeans.utils.Repository;

import java.util.List;

/**
 * @author sdroman
 * @since 08.2018
 */

public class JdbcStorage extends Repository implements Storage {

    /**
     * Adds user.
     *
     * @param user User
     */
    @Override
    public int add(User user) {
        return (int) super.execute(session -> {
            return session.save(user);
        });
    }

    /**
     * Updates user.
     *
     * @param user User
     */
    @Override
    public void updateUser(User user) {
        super.execute(session -> {
            session.saveOrUpdate(user);
        });
    }

    /**
     * Removes user.
     *
     * @param user User
     */
    @Override
    public void deleteUser(User user) {
        super.execute(session -> {
            session.delete(user);
        });
    }

    /**
     * Returns user by id.
     *
     * @param userId int
     * @return User
     */
    @Override
    public User getUser(int userId) {
        return (User) super.execute(session -> {
            return session.createQuery("from User where id=:id")
                    .setParameter("id", userId)
                    .uniqueResult();
        });
    }

    /**
     * Returns all users.
     *
     * @return List<User>
     */
    @Override
    public List<User> getUsers() {
        return super.execute(session -> (List<User>) session.createQuery("from User").list());
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pertusaria kerguelena Zahlbr.

### Remarks
null


text:
namespace ATM.Models.Validation
{
    public class Validator
    {
        private const int CardNumberLength = 10;
        private const int CardPinLength = 4;

        public bool IsValidCardNumber(string cardNumber)
        {
            var isValidCardNumber = !string.IsNullOrEmpty(cardNumber) && cardNumber.Trim().Length == CardNumberLength;
            return isValidCardNumber;
        }

        public bool IsValidCardPin(string cardPin)
        {
            var isValidCardPin = !string.IsNullOrEmpty(cardPin) && cardPin.Trim().Length == CardPinLength;
            return isValidCardPin;
        }

        public bool IsPermittedWithdrawalAmount(decimal withdrawalAmount, decimal moneyInCardAccount)
        {
            var isPermittedWithdrawalAmount = withdrawalAmount > 0 && moneyInCardAccount >= withdrawalAmount;
            return isPermittedWithdrawalAmount;
        }

        public bool IsPinCodeMatches(string expected, string actual)
        {
            var isPinCodeMatches = expected == actual;
            return isPinCodeMatches;
        }
    }
}


text:
//
//  GTLAnalyticsAccounts.h
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Google Analytics API (analytics/v3)
// Description:
//   View and manage your Google Analytics data
// Documentation:
//   https://developers.google.com/analytics/
// Classes:
//   GTLAnalyticsAccounts (0 custom class methods, 8 custom properties)

#if GTL_BUILT_AS_FRAMEWORK
  #import "GTL/GTLObject.h"
#else
  #import "GTLObject.h"
#endif

@class GTLAnalyticsAccount;

// ----------------------------------------------------------------------------
//
//   GTLAnalyticsAccounts
//

// An account collection provides a list of Analytics accounts to which a user
// has access. The account collection is the entry point to all management
// information. Each resource in the collection corresponds to a single
// Analytics account.

// This class supports NSFastEnumeration over its "items" property. It also
// supports -itemAtIndex: to retrieve individual objects from "items".

@interface GTLAnalyticsAccounts : GTLCollectionObject

// A list of accounts.
@property (nonatomic, retain) NSArray *items;  // of GTLAnalyticsAccount

// The maximum number of entries the response can contain, regardless of the
// actual number of entries returned. Its value ranges from 1 to 1000 with a
// value of 1000 by default, or otherwise specified by the max-results query
// parameter.
@property (nonatomic, retain) NSNumber *itemsPerPage;  // intValue

// Collection type.
@property (nonatomic, copy) NSString *kind;

// Next link for this account collection.
@property (nonatomic, copy) NSString *nextLink;

// Previous link for this account collection.
@property (nonatomic, copy) NSString *previousLink;

// The starting index of the entries, which is 1 by default or otherwise
// specified by the start-index query parameter.
@property (nonatomic, retain) NSNumber *startIndex;  // intValue

// The total number of results for the query, regardless of the number of
// results in the response.
@property (nonatomic, retain) NSNumber *totalResults;  // intValue

// Email ID of the authenticated user
@property (nonatomic, copy) NSString *username;

@end


text: export * from './widget';


text:
<?php

namespace Eltrino\PrintOrder\Model\Resource\GuestOrder;

class Collection extends \Magento\Framework\Model\Resource\Db\Collection\AbstractCollection
{
    /**
     * Clean expired guests orders.
     *
     * @return \Eltrino\PrintOrder\Model\Resource\GuestOrder\Collection
     */
    public function cleanExpiredGuestsOrders()
    {
        $this->addOrder('expired_at')
            ->addFieldToFilter(
                'expired_at',
                ['to' => date('Y-m-d H:i:s', time())]
            );
        \Zend_Debug::dump($this->getSelect()->__toString());
        $this->walk('delete');

        return $this;
    }

    /**
     */
    protected function _construct()
    {
        $this->_init('Eltrino\PrintOrder\Model\GuestOrder', 'Eltrino\PrintOrder\Model\Resource\GuestOrder');
    }
}