text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright [2015] [Letsgood.com s.r.o.]
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.Copyright [2015] [Letsgood.com s.r.o.]
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  ~
  ~ Created by Bc. Pavel Stambrecht for Letsgood.com s.r.o.
  -->

<resources>

    <!-- Theme -->
    <color name="white">#FFFFFF</color>
    <color name="gray_brightness20">#333333</color>
    <color name="gray_brightness35">#595959</color>
    <color name="gray_brightness38">#606060</color>
    <color name="gray_brightness50">#808080</color>
    <color name="gray_brightness65">#A6A6A6</color>
    <color name="gray_brightness73">#BBBBBB</color>
    <color name="gray_brightness77">#C5C5C5</color>
    <color name="gray_brightness83">#D4D4D4</color>
    <color name="gray_brightness88">#E0E0E0</color>
    <color name="gray_brightness90">#E5E5E5</color>
    <color name="gray_brightness92">#EAEAEA</color>
    <color name="gray_brightness94">#F0F0F0</color>
    <color name="gray_brightness95">#F2F2F2</color>
    <color name="black">#000000</color>
    <color name="black_transparent">#19000000</color>
    <color name="black_transparent_dark">#CC000000</color>
    <color name="orange_light">#FFF0E0</color>
    <color name="orange_dark">#E68A00</color>
    <color name="orange">#FF9900</color>
    <color name="blue">#1364d6</color>
    <color name="red">#E43421</color>
    <color name="green">#33CC33</color>
    <color name="yellow">#FEFF82</color>
    <color name="transparent">@android:color/transparent</color>
    <color name="blue_fb">#1e5199</color>
    <color name="blue_twitter">#00a6ea</color>
    <color name="red_google">#ef1410</color>

    <!-- Default colors -->
    <color name="layout_bg_color">@color/white</color>
    <color name="layout_placeholder_bg_color">@color/gray_brightness92</color>
    <color name="app_color">@color/blue</color>
    <color name="app_color_dark">#000000</color>
    <color name="selector_color">@color/app_color</color>
    <color name="appbasetheme_color">@color/app_color</color>

    <!-- Actionbar -->
    <color name="actionBarBackground">@color/gray_brightness92</color>
    <color name="actionBarLabel">@color/app_color</color>
    <color name="actionBarSelector">@color/black_transparent</color>
    <color name="actionBarText">@color/app_color</color>
    <color name="actionBarOverflow">@color/black</color>

    <!-- ListView -->
    <color name="listviewBackgroundItem">@color/white</color>
    <color name="listviewBackgroundItemPressed">@color/gray_brightness94</color>
    <color name="listviewBackgroundItemSelected">@color/orange_light</color>
    <color name="listviewDivider">@color/gray_brightness73</color>
    <color name="gridViewBackgroundItem">@color/white</color>
    <color name="gridViewDivider">@color/gray_brightness88</color>
    <color name="listViewFooter">@color/black_transparent_dark</color>

    <!-- Button -->
    <color name="buttonBackgroundStartColor">@color/gray_brightness95</color>
    <color name="buttonBackgroundEndColod">@color/gray_brightness94</color>
    <color name="buttonBackgroundEndColorPressed">@color/gray_brightness92</color>
    <color name="buttonBackgroundStartColorPressed">@color/gray_brightness90</color>
    <color name="buttonShadow">@color/gray_brightness73</color>
    <color name="buttonStroke">@color/gray_brightness83</color>
    <color name="buttonStrokePressed">@color/gray_brightness73</color>
    <color name="buttonText">@color/gray_brightness38</color>

    <!-- TextView -->
    <color name="textTitle">@color/app_color</color>
    <color name="textDescription">@color/gray_brightness20</color>
    <color name="textListDescription">@color/gray_brightness50</color>
    <color name="textPlaceholder">@color/gray_brightness65</color>

    <!-- EditText -->
    <color name="editTextDescription">@color/gray_brightness38</color>
    <color name="editTextHint">@color/gray_brightness65</color>
    <color name="editTextStrokeColor">@color/gray_brightness65</color>
    <color name="editTextBackground">@color/white</color>

    <!-- Chat -->
    <color name="chatMessageUserBackground">#4d4c4a</color>
    <color name="chatMessageUserOwnerBackground">@color/app_color</color>
    <color name="chatMessageLeftBackground">#dce9f9</color>
    <color name="chatMessageRightBackground">#e7e5e2</color>
    <color name="chatMessageCenterBackground">#ffffff</color>
    <color name="chatMessageCenterBorder">@color/gray_brightness88</color>
    <color name="chatTypingBackground">#F288b824</color>

</resources>


text:
package de.tudarmstadt.ukp.jwktl.api.entry;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEdition;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEntry;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryPage;
import de.tudarmstadt.ukp.jwktl.api.IWiktionarySense;
import de.tudarmstadt.ukp.jwktl.api.filter.IWiktionaryEntryFilter;
import de.tudarmstadt.ukp.jwktl.api.filter.IWiktionarySenseFilter;
import de.tudarmstadt.ukp.jwktl.api.util.IWiktionaryIterator;
import de.tudarmstadt.ukp.jwktl.api.util.WiktionaryIterator;

/**
 * Abstract base class for implementations of {@link IWiktionaryEdition}s.
 * @author Christian M. Meyer
 */
public abstract class WiktionaryEdition extends AbstractWiktionary
		implements IWiktionaryEdition {

	protected boolean isClosed;

	/** Initializes the Wiktionary edition. */
	public WiktionaryEdition() {
		isClosed = false;
	}

	// -- Entries --

	public IWiktionaryEntry getEntryForId(long pageId, int entryIdx) {
		ensureOpen();
		IWiktionaryPage page = getPageForId(pageId);
		return (page == null ? null : page.getEntries().get(entryIdx));
	}

	public IWiktionaryEntry getEntryForWord(final String word,
			int entryIdx) {
		IWiktionaryPage page = getPageForWord(word);
		return (page == null ? null : page.getEntries().get(entryIdx));
	}

	public List<IWiktionaryEntry> getEntriesForWord(final String word,
			final IWiktionaryEntryFilter filter, boolean normalize) {
		ensureOpen();
		List<IWiktionaryEntry> result = new ArrayList<IWiktionaryEntry>();
		if (word == null || word.isEmpty())
			return result;

		List<IWiktionaryPage> pages = getPagesForWord(word, normalize);
		for (IWiktionaryPage page : pages)
			for (IWiktionaryEntry entry : page.getEntries())
				if (filter == null || filter.accept(entry))
					result.add(entry);

		return result;
	}

	public IWiktionaryIterator<IWiktionaryEntry> getAllEntries(
			final IWiktionaryEntryFilter filter,
			final boolean sortByTitle, final boolean normalize) {
		ensureOpen();
		return new WiktionaryIterator<IWiktionaryEntry>() {

			protected IWiktionaryIterator<IWiktionaryPage> allPages
					= getAllPages(null, sortByTitle, normalize);
			protected Iterator<? extends IWiktionaryEntry> entries;

			protected IWiktionaryEntry fetchNext() {
				do {
					// If there are no entries left, try to fetch the next page.
					if (entries == null || !entries.hasNext())
						if (fetchNextPage() == null)
							return null; // No page left.

					// As long as entries are left, return them!
					if (entries != null && entries.hasNext()) {
						IWiktionaryEntry result = entries.next();
						if (filter == null || filter.accept(result))
							return result;
					}
				} while (true);
			}

			protected IWiktionaryPage fetchNextPage() {
				if (!allPages.hasNext())
					return null;

				IWiktionaryPage result = allPages.next();
				entries = result.getEntries().iterator();
				return result;
			}

			protected void doClose() {
				allPages.close();
			}

		};
	}

	// -- Senses --

	public IWiktionarySense getSenseForId(long entryId, int senseIdx) {
		ensureOpen();
		IWiktionaryEntry entry = getEntryForId(entryId);
		return (entry == null ? null : entry.getSense(senseIdx));
	}

	public IWiktionarySense getSenseForId(long pageId, int entryIdx, int senseIdx) {
		ensureOpen();
		IWiktionaryEntry entry = getEntryForId(pageId, entryIdx);
		return (entry == null ? null : entry.getSense(senseIdx));
	}

	public List<IWiktionarySense> getSensesForWord(final String word,
			int entryIdx) {
		ensureOpen();
		IWiktionaryEntry entry = getEntryForWord(word, entryIdx);
		List<IWiktionarySense> result = new ArrayList<IWiktionarySense>();
		for (IWiktionarySense sense : entry.getSenses())
			result.add(sense);
		return result;
//		return (entry == null ? null : entry.getSenses());
	}

	public IWiktionarySense getSensesForWord(final String word,
			int entryIdx, int senseIdx) {
		ensureOpen();
		IWiktionaryEntry entry = getEntryForWord(word, entryIdx);
		return (entry == null ? null : entry.getSense(senseIdx));
	}

	public List<IWiktionarySense> getSensesForWord(final String word,
			final IWiktionarySenseFilter filter, boolean normalize) {
		ensureOpen();
		List<IWiktionarySense> result = new ArrayList<IWiktionarySense>();
		if (word == null || word.isEmpty())
			return result;

		List<IWiktionaryPage> pages = getPagesForWord(word, normalize);
		for (IWiktionaryPage page : pages)
			for (IWiktionaryEntry entry : page.getEntries())
				for (IWiktionarySense sense : entry.getSenses())
					if (filter == null || filter.accept(sense))
						result.add(sense);

		return result;
	}

	public IWiktionaryIterator<IWiktionarySense> getAllSenses(
			final IWiktionarySenseFilter filter,
			final boolean sortByTitle, final boolean normalize) {
		ensureOpen();
		return new WiktionaryIterator<IWiktionarySense>() {

			protected IWiktionaryIterator<IWiktionaryEntry> allEntries
					= getAllEntries(sortByTitle, normalize);
			protected Iterator<? extends IWiktionarySense> senses;

			protected IWiktionarySense fetchNext() {
				do {
					if (senses == null || !senses.hasNext())
						if (fetchNextEntry() == null)
							return null;

					if (senses != null && senses.hasNext()) {
						IWiktionarySense result = senses.next();
						if (filter == null || filter.accept(result))
							return result;
					}
				} while (true);
			}

			protected IWiktionaryEntry fetchNextEntry() {
				if (!allEntries.hasNext())
					return null;

				IWiktionaryEntry result = allEntries.next();
				senses = result.getSenses().iterator();
				return result;
			}

			protected void doClose() {
				allEntries.close();
			}

		};
	}

	// -- Close --

	/** Disconnects from the database. This is necessary to ensure the
	 *  consistency of the data. No retrieval methods can be called after
	 *  closing the connection, so this should be done prior to terminating
	 *  the application. Nothing happens on calling the method more than
	 *  once. */
	public void close() {
		if (isClosed)
			return;

		doClose();
		isClosed = true;
	}

	/** Returns if the connection has already been closed. If so, no
	 *  retrieval method can be called anymore. To close an open
	 *  connection, use the {@link #close()} method. */
	public boolean isClosed() {
		return isClosed;
	}

	protected abstract void doClose();

	/** @throws IllegalStateException if the connection has already been
	 * 		closed. This method is to be called from each retrieval method.  */
	protected void ensureOpen() {
		if (isClosed)
			throw new IllegalStateException("Wiktionary was already closed.");
	}

}

redpajama_set_name: RedPajamaGithub


text:
package me.zhengjie.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.domain.QiniuConfig;
import me.zhengjie.domain.QiniuContent;
import me.zhengjie.service.dto.QiniuQueryCriteria;
import me.zhengjie.service.QiNiuService;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送邮件
 * @author 郑杰
 * @date 2018/09/28 6:55:53
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/qiNiuContent")
@Api(tags = "工具:七牛云存储管理")
public class QiniuController {

    private final QiNiuService qiNiuService;

    @GetMapping(value = "/config")
    public ResponseEntity<Object> queryQiNiuConfig(){
        return new ResponseEntity<>(qiNiuService.find(), HttpStatus.OK);
    }

    @Log("配置七牛云存储")
    @ApiOperation("配置七牛云存储")
    @PutMapping(value = "/config")
    public ResponseEntity<Object> updateQiNiuConfig(@Validated @RequestBody QiniuConfig qiniuConfig){
        qiNiuService.config(qiniuConfig);
        qiNiuService.update(qiniuConfig.getType());
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    public void exportQiNiu(HttpServletResponse response, QiniuQueryCriteria criteria) throws IOException {
        qiNiuService.downloadList(qiNiuService.queryAll(criteria), response);
    }

    @ApiOperation("查询文件")
    @GetMapping
    public ResponseEntity<Object> queryQiNiu(QiniuQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(qiNiuService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @Log("上传文件")
    @ApiOperation("上传文件")
    @PostMapping
    public ResponseEntity<Object> uploadQiNiu(@RequestParam MultipartFile file){
        QiniuContent qiniuContent = qiNiuService.upload(file,qiNiuService.find());
        Map<String,Object> map = new HashMap<>(3);
        map.put("id",qiniuContent.getId());
        map.put("errno",0);
        map.put("data",new String[]{qiniuContent.getUrl()});
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

    @Log("同步七牛云数据")
    @ApiOperation("同步七牛云数据")
    @PostMapping(value = "/synchronize")
    public ResponseEntity<Object> synchronizeQiNiu(){
        qiNiuService.synchronize(qiNiuService.find());
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("下载文件")
    @ApiOperation("下载文件")
    @GetMapping(value = "/download/{id}")
    public ResponseEntity<Object> downloadQiNiu(@PathVariable Long id){
        Map<String,Object> map = new HashMap<>(1);
        map.put("url", qiNiuService.download(qiNiuService.findByContentId(id),qiNiuService.find()));
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

    @Log("删除文件")
    @ApiOperation("删除文件")
    @DeleteMapping(value = "/{id}")
    public ResponseEntity<Object> deleteQiNiu(@PathVariable Long id){
        qiNiuService.delete(qiNiuService.findByContentId(id),qiNiuService.find());
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("删除多张图片")
    @ApiOperation("删除多张图片")
    @DeleteMapping
    public ResponseEntity<Object> deleteAllQiNiu(@RequestBody Long[] ids) {
        qiNiuService.deleteAll(ids, qiNiuService.find());
        return new ResponseEntity<>(HttpStatus.OK);
    }
}


text:
import { expect } from 'chai';
import { Page } from 'puppeteer';
import {
  addEventListenersToPuppeteerPage,
  loadCachedTestBed,
  takeScreenshot,
  TestBed,
} from '../../../puppeteer-tests/util';
import { DiffPageSkPO } from './diff-page-sk_po';

describe('diff-page-sk', () => {
  let testBed: TestBed;

  before(async () => {
    testBed = await loadCachedTestBed();
  });

  // The demo page pushes a "default" query string to the URL when no query string is provided. All
  // parameters in the below query string are different from said defaults. This allows this test
  // to verify that the page correctly parses out the query parameters.
  const baseParams = '?left=99c58c7002073346ff55f446d47d6311&right=6246b773851984c726cb2e1cb13510c2'
    + '&grouping=name%3DMy%2520test%2520has%2520spaces%26source_type%3Dinfra';

  it('should render the demo page', async () => {
    await navigateTo(testBed.page, testBed.baseUrl, baseParams);
    // Smoke test.
    expect(await testBed.page.$$('diff-page-sk')).to.have.length(1);
  });

  describe('screenshots', () => {
    it('should show the default page', async () => {
      await navigateTo(testBed.page, testBed.baseUrl, baseParams);
      await testBed.page.setViewport({
        width: 1300,
        height: 700,
      });
      await takeScreenshot(testBed.page, 'gold', 'diff-page-sk');
    });
  });

  describe('url params', () => {
    it('correctly extracts the grouping, left and right digest', async () => {
      const diffPageSkPO = await navigateTo(testBed.page, testBed.baseUrl, baseParams);

      expect(await diffPageSkPO.digestDetailsSkPO.getTestName())
        .to.equal('Test: My test has spaces');
      expect(await diffPageSkPO.digestDetailsSkPO.getLeftDigest())
        .to.equal('Left: 99c58c7002073346ff55f446d47d6311');
      expect(await diffPageSkPO.digestDetailsSkPO.getRightDigest())
        .to.equal('Right: 6246b773851984c726cb2e1cb13510c2');

      // This link should not have a changelist ID or CRS.
      expect(await diffPageSkPO.digestDetailsSkPO.getDiffPageLink()).to.equal(
        '/diff?grouping=name%3DMy%2520test%2520has%2520spaces%26source_type%3Dinfra'
          + '&left=99c58c7002073346ff55f446d47d6311&right=6246b773851984c726cb2e1cb13510c2',
      );
    });

    it('correctly extracts the changelist ID and CRS if provided', async () => {
      const diffPageSkPO = await navigateTo(
        testBed.page, testBed.baseUrl, `${baseParams}&changelist_id=65432&crs=gerrit`,
      );

      expect(await diffPageSkPO.digestDetailsSkPO.getTestName())
        .to.equal('Test: My test has spaces');
      expect(await diffPageSkPO.digestDetailsSkPO.getLeftDigest())
        .to.equal('Left: 99c58c7002073346ff55f446d47d6311');
      expect(await diffPageSkPO.digestDetailsSkPO.getRightDigest())
        .to.equal('Right: 6246b773851984c726cb2e1cb13510c2');

      // The changelist ID and CRS should be reflected in this link.
      expect(await diffPageSkPO.digestDetailsSkPO.getDiffPageLink()).to.equal(
        '/diff?grouping=name%3DMy%2520test%2520has%2520spaces%26source_type%3Dinfra'
          + '&left=99c58c7002073346ff55f446d47d6311&right=6246b773851984c726cb2e1cb13510c2'
          + '&changelist_id=65432&crs=gerrit',
      );
    });
  });
});

async function navigateTo(page: Page, base: string, queryParams = ''): Promise<DiffPageSkPO> {
  const eventPromise = await addEventListenersToPuppeteerPage(page, ['busy-end']);
  const loaded = eventPromise('busy-end'); // Emitted from gold-scaffold when page is loaded.
  await page.goto(`${base}${queryParams}`);
  await loaded;
  return new DiffPageSkPO(page.$('diff-page-sk'));
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Ivony.Html.Web.Binding
{

  public class BindingExpression
  {

    private static readonly Regex bindingExpressionRegex = new Regex( "^" + Regulars.BindingExpressionPattern + "$", RegexOptions.IgnoreCase | RegexOptions.Compiled );

    public static IDictionary<string, string> ParseExpression( IHtmlAttribute attribute )
    {
      var expression = attribute.Value();

      if ( expression == null )
        return null;

      var match = bindingExpressionRegex.Match( expression );
      if ( match == null || !match.Success )
        return null;

      return ParseExpression( match );
    }

    private static IDictionary<string, string> ParseExpression( Match match )
    {
      var args = new Dictionary<string, string>( StringComparer.OrdinalIgnoreCase );

      foreach ( Capture capture in match.Groups["args"].Captures )
      {
        var name = capture.FindCaptures( match.Groups["name"] ).FirstOrDefault().Value;
        var value = capture.FindCaptures( match.Groups["value"] ).FirstOrDefault().Value;

        args[name] = value;
      }

      return args;

    }
  }
}


text:
module Cigale::Wrapper
  def translate_job_log_logger_wrapper (xml, wdef)
    xml.suppressEmpty wdef["suppress-empty"]
  end
end


text:
module Analytical
  module Modules
    class Console
      include Analytical::Modules::Base

      def initialize(options={})
        super
        @tracking_command_location = :body_append
      end

      def init_javascript(location)
        init_location(location) do
          js = <<-HTML
          <!-- Analytical Init: Console -->
          <script type="text/javascript">
            if (typeof(console) !== 'undefined' && console != null) {
              console.log('Analytical Init: Console');
            }
          </script>
          HTML
          js
        end
      end

      def identify(*args) # id, options
        <<-JS.gsub(/^ {10}/, '')
          if (typeof(console) !== 'undefined' && console != null) {
            console.log('Analytical identify', arguments)
          }
        JS
      end

      def track(*args) # event, properties, callback
        <<-JS.gsub(/^ {10}/, '')
          if (typeof(console) !== 'undefined' && console != null) {
            console.log('Analytical track', arguments)
          }
        JS
      end

      def event(*args) # name, options
        <<-JS.gsub(/^ {10}/, '')
          if (typeof(console) !== 'undefined' && console != null) {
            console.log('Analytical event', arguments)
          }
        JS
      end

      def set(*args) # properties
        <<-JS.gsub(/^ {10}/, '')
          if (typeof(console) !== 'undefined' && console != null) {
            console.log('Analytical set', arguments)
          }
        JS
      end

      def alias_identity(*args) # old_identity, new_identity
        <<-JS.gsub(/^ {10}/, '')
          if (typeof(console) !== 'undefined' && console != null) {
            console.log('Analytical alias_identity', arguments)
          }
        JS
      end

    end
  end
end


text:
namespace Neat::Win
{
	//
	// Structured exception wrapper
	//

	StructuredException::StructuredException(uint32_t errorCode, size_t address, bool continuable) :
		Base("StructuredException", errorCode),
		m_address(address),
		m_continuable(continuable)
	{
	}

	StructuredException::~StructuredException()
	{
		if (!m_continuable)
		{
			// TODO: Add debug output here
			::ExitProcess(m_errorCode);
		}
	}

	const char* StructuredException::GetErrorMessage() const
	{
		snprintf(
			&m_message[0],
			m_message.size(),
			"0x%08X at 0x%08IX (%s)",
			m_errorCode,
			m_address,
			m_continuable ? "continuable" : "non-continuable");

		return &m_message[0];
	}

	static void SeTranslator(uint32_t errorCode, PEXCEPTION_POINTERS pointers)
	{
		size_t address = 0;
		bool continuable = true;
		if (pointers && pointers->ExceptionRecord)
		{
			address = (size_t)pointers->ExceptionRecord->ExceptionAddress;
			if (pointers->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE)
			{
				continuable = false;
			}
		}
		throw StructuredException(errorCode, address, continuable);
	}

	void StructuredException::EnableInThisThread()
	{
		_set_se_translator(SeTranslator);
	}

	//
	// Win32 error wrapper
	//

	Win32Exception::Win32Exception(uint32_t errorCode) :
		ExceptionWithCode("Win32Exception", errorCode)
	{
	}

	Win32Exception::Win32Exception(const char name[], uint32_t errorCode) :
		ExceptionWithCode(name, errorCode)
	{
	}

	const char* Win32Exception::GetErrorMessage() const
	{
		DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM;
		ModuleHandle source;

		// WinInet errors
		if (12000 <= m_errorCode && m_errorCode < 13000)
		{
			flags = FORMAT_MESSAGE_FROM_HMODULE;
			source = ::LoadLibraryA("wininet.dll");
		}

		const auto end = ::FormatMessageA(
			flags,
			source,
			m_errorCode,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			&m_message[0],
			(DWORD)m_message.size(),
			nullptr);

		if (0 == end)
			return ExceptionWithCode::GetErrorMessage();

		for (auto& ch : m_message)
		{
			if (ch == '\0')
				break;
			if (ch == '\r' || ch == '\n')
				ch = '\0';
		}

		return &m_message[0];
	}

	//
	// Last error wrapper
	//

	LastErrorException::LastErrorException() :
		Win32Exception(::GetLastError())
	{
	}
}


text:
var fs = require('fs');

var loggingToFile = Boolean(process.env.WEBPACK_TASK_LOGGING);

function logLine(message) {
  fs.appendFileSync('log/webpack-task.log', new Date()+' -- '+message+'\n');
}

function log(message) {
  if (loggingToFile) logLine(message);
}

function logErr(err) {
  logLine(err.toString()+' -- '+JSON.stringify(err.stack));
}

log.error = logErr;

module.exports = log;


text:
IPTABLES="`which iptables`" || exit 1
IP="`which ip`" || exit 1

#change this parameters :
#EXTIF=eth0
EXTIF="`LC_ALL=C $IP -4 route | grep 'default' | sed -e 's/.*dev[[:space:]]*//' -e 's/[[:space:]].*//'`" || exit 1
EXTIP="`LC_ALL=C $IP -4 addr show $EXTIF | awk '/inet/ { print $2 }' | cut -d "/" -f 1`"

echo "External IP = $EXTIP"

#adding the MINIUPNPD chain for nat
$IPTABLES -t nat -N MINIUPNPD
#adding the rule to MINIUPNPD
#$IPTABLES -t nat -A PREROUTING -d $EXTIP -i $EXTIF -j MINIUPNPD
$IPTABLES -t nat -A PREROUTING -i $EXTIF -j MINIUPNPD

#adding the MINIUPNPD chain for mangle
$IPTABLES -t mangle -N MINIUPNPD
$IPTABLES -t mangle -A PREROUTING -i $EXTIF -j MINIUPNPD

#adding the MINIUPNPD chain for filter
$IPTABLES -t filter -N MINIUPNPD
#adding the rule to MINIUPNPD
$IPTABLES -t filter -A FORWARD -i $EXTIF ! -o $EXTIF -j MINIUPNPD

#adding the MINIUPNPD chain for nat
$IPTABLES -t nat -N MINIUPNPD-PCP-PEER
$IPTABLES -t nat -A POSTROUTING -o $EXTIF -j MINIUPNPD-PCP-PEER


text:
layout: page
title: VeriS
subtitle: Verified Software Group at CyLab, Carnegie Mellon University
use-site-title: true
---

* ISSTAC


text:
<?xml version="1.0" encoding="UTF-8"?>
<monster name="Manta Ray" nameDescription="a manta ray" race="blood" experience="125" speed="200" manacost="0">
	<health now="680" max="680"/>
	<look type="449" corpse="15276"/>
	<targetchange interval="4000" chance="10"/>
	<flags>
		<flag summonable="0"/>
		<flag attackable="1"/>
		<flag hostile="1"/>
		<flag illusionable="0"/>
		<flag convinceable="0"/>
		<flag pushable="1"/>
		<flag canpushitems="0"/>
		<flag canpushcreatures="1"/>
		<flag targetdistance="0"/>
		<flag runonhealth="0"/>
	</flags>
	<attacks>
		<attack name="melee" interval="2000" skill="34" attack="45" poison="120"/>
		<attack name="energy" interval="2000" chance="10" range="7" min="-15" max="-75">
			<attribute key="shootEffect" value="energy"/>
			<attribute key="areaEffect" value="energy"/>
		</attack>
		<attack name="energy" interval="2000" chance="10" length="4" spread="0" target="0">
			<attribute key="areaEffect" value="energy"/>
		</attack>
	</attacks>
	<defenses armor="15" defense="15"/>
	<immunities>
		<immunity earth="1"/>
		<immunity fire="1"/>
		<immunity invisible="1"/>
		<immunity drown="1"/>
	</immunities>
	<voices interval="5000" chance="10">
		<voice sentence="Flap flap flap!"/>
	</voices>
	<elements>
		<element icePercent="-1"/>
		<element physicalPercent="-1"/>
		<element energyPercent="1"/>
	</elements>
	<loot>
		<item id="2148" countmax="38" chance="50000"/><!-- gold coin -->
	</loot>
</monster>


text:
'use strict';

var mongoose = require('mongoose'),
    Thing = mongoose.model('Thing');

/**
 * Get awesome things
 */
exports.awesomeThings = function(req, res) {
  // find 'things' with status = true
  // sort by date (desc)
  return Thing.find( { status: true } ).sort('-dateTime').exec(function (err, things) {
    if (!err) {
      return res.json(things);
    } else {
      return res.send(err);
    }
  });
};

/**
 * Create an awesome thing
 */
exports.create = function(req, res, next) {
  // insert
  var newThing = new Thing({
    name: req.body.name,
    info: req.body.info,
    dateTime: req.body.dateTime,
    status: req.body.status
  });
  newThing.save(function(err, thing) {
    if (!err) {
      return res.send(200);
    } else {
      return res.send(err);
    }
  });
};


text:
__author__ = "bt3"

''' Find the mth-to-last element of a linked list.
    One option is having two pointers, separated by m. P1 start at the roots
    (p1 = self.root) and p2 is m-behinf pointer, which is created when p1 is at m.
    When p1 reach the end, p2 is the node. '''

from linked_list_fifo import LinkedListFIFO
from node import Node

class LinkedListFIFO_find_kth(LinkedListFIFO):

    def find_kth_to_last(self, k):
        p1, p2 = self.head, self.head
        i = 0
        while p1:
            if i > k:
                try:
                    p2 = p2.pointer
                except:
                    break
            p1 = p1.pointer
            i += 1
        return p2.value

if __name__ == '__main__':
    ll = LinkedListFIFO_find_kth()
    for i in range(1, 11):
        ll.addNode(i)
    print('The Linked List:')
    print(ll._printList())
    k = 3
    k_from_last = ll.find_kth_to_last(k)
    print("The %dth element to the last of the LL of size %d is %d" %(k, ll.length, k_from_last))


text:
$(document).ready(function () {

    /* Esta função salva os registros no banco */
    $('#btn_salvar').click(function () {

        var id = '';

        if ($('#id').val() !== '') {
            id = $('#id').val();
        }

        if (valida()) {

            $.post('http://localhost/aniversariantes/index.php/cadastroaniversariantes_control/salvar', {
                id: id,
                nome: $('#id_nome').val(),
                dt_nasc: $('#id_dt_nasc').val(),
                convenio: $('#id_convenio').val()

            }, function (data, status) {

                if (data) {
                    alert("Registro inserido com sucesso!!");
                    window.location.reload();
                } else {
                    alert("Ocorreu um erro ao inserir o registro!!");
                }

            });
        }

    });

    /* Esta função deleta os registros no banco */
    $('#btn_remover').click(function () {

        var id = '';

        if ($('#id').val() !== '') {
            id = $('#id').val();
        }

        if (valida()) {

            $.post('http://localhost/aniversariantes/index.php/cadastroaniversariantes_control/remover', {
                id: id,
                nome: $('#id_nome').val(),
                dt_nasc: $('#id_dt_nasc').val(),
                convenio: $('#id_convenio').val()
            }, function (data, status) {
                if (data) {
                    alert("Registro exluido com sucesso!!");
                    window.location.reload();
                } else {
                    alert("Não foi possível exluir o registro!!");
                }
            });
        }
    });

});

/* Ao clicar no botão a tabela será atualizada */
$('#btn_atualiza').click(function () {
    atualizaTabela();
});

/* Edita o campo da tabela selecionado */
$('#tabelaClientes tbody tr').each(function () {

    $(this).click(function () {

        $("td").removeClass("addCor");
        $(this).each(function () {
            $(this).children("*").addClass("addCor");

            var id = $(this).find('td[id=id]').text();

            $.post('http://localhost/aniversariantes/index.php/cadastroaniversariantes_control/editar', {
                id: id
            }, function (data, status) {

                if (status === "success") {
                    preencheCampos(data);
                } else {
                    mensagem();
                }
            }, 'json');
        });
    });
});

/* Popula tabela com aniversariantes do mes */
$('#btn_buscar').click(function () {

    var mes = $('#select option:selected').val();
    //alert('Pagina Inicial: ' + mes);

    console.log(mes);

    var url = 'http://localhost/aniversariantes/index.php/cadastroaniversariantes_control/relatorio';

    $.post(url, {
        mes: mes
    }, function (data, status) {
        //alert(status);

        var dados = JSON.parse(data);
        console.log(data);
        console.log(dados);
        var html_td = "";

        if (dados !== 'vazio') {
            $.each(dados, function (i, item) {
                html_td = html_td + "
" + item.id + "	";
                html_td = html_td + "" + item.nome + "	";
                html_td = html_td + "" + item.dt_nasc + "	";
                html_td = html_td + "" + item.convenio + "
";
            });

            $('#lista_aniver').html(html_td);
            console.log(html_td);

        } else {
            window.location.reload();
            alert("Não existe aniversariante para este mes especifico!");
        }
    });
});

/* COLORE A TABELA DE ACORDO COM O MOUSE */
$('#tabelaClientes tbody tr').hover(
        function () {
            $(this).addClass("destaque");
        },
        function () {
            $(this).removeClass("destaque");
        }
);

/* Função que preenche os campos da tabela */
function preencheCampos(data) {

    $('#id').val(data.id);
    $('#id_nome').val(data.nome);
    $('#id_dt_nasc').val(data.dt_nasc);
    $('#id_convenio').val(data.convenio);
}

function atualizaTabela() {
    window.location.reload();
}

/* Esta função fz as validações dos campos input, caso estejam vazio não será feito o submit do formulario
 * até que todos os campos estejam preenchidos */
function valida() {

    var verificaInput = 'verificar';
    var inputs = $('#form_cadastro').find('input[class*="' + verificaInput + '"]');

    var erros = [];

    erros.length = 0;

    $("#div_error").hide();

    $.each(inputs, function (i, value) {
        if (inputs[i].value === "") {
            erros[i] = $(inputs[i]).attr("itemid") + " deve ser preenchido!";
        }
    });

    if (erros.length > 0) {

        var texto = "";

        $.each(erros, function (i, value) {
            if (erros[i]) {
                texto = texto + erros[i] + "
";
            }
        });

        $("#div_error").html(texto).addClass("alert alert-danger").show();

        return false;
    }
    return true;
}

function mensagem(status) {

    var sucesso = $("

").addClass("alert alert-success").text("Cadastro realizado com sucesso!").fadeIn(2000);

    var erro = $("

").addClass("alert alert-danger").text("Operação não realizada!");

    if (status === "success") {
        $('.div_panel').before(sucesso);

        sucesso.fadeOut(3000);

    } else {
        $('.div_panel').before(erro);
    }

}

/* Esta função limpa os campos da formulario */
function limparCampos() {
    $("#form_cadastro").each(function () {
        this.reset();
    });
}

/***************************************************************************************************/

//$('#mensagem').find('p').css({
//    "margin-top": "50px"
//}).fadeOut(5000);
/* Cadastro de Clientes */

//function piscar(selector) {
//
//    $(selector).addClass("testando alert alert-success");
//
//    $(selector).fadeOut('slow', function () {
//        $(this).fadeIn('slow', function () {
//            piscar(this);
//        });
//    });
//}

/* Arrastando elementos */

//function drag(ev) {
//    ev.dataTransfer.setData("text", ev.target.id);
//}
//
//function allowDrop(ev) {
//    ev.preventDefault();
//}
//
//function drop(ev) {
//    ev.preventDefault();
//    var data = ev.dataTransfer.getData("text");
//    ev.target.appendChild(document.getElementById(data));
//}

/* Busca por cep
 $('#btn_buscar').click(function () {

 var cep = $('#cep').val();

 var url = 'http://cep.republicavirtual.com.br/web_cep.php?cep=' + cep + '&formato=json';

 $.get(url, function (data, status) {
 if (data.resultado !== '') {

 $('.painelCep').show();
 $('#resultado_txt').html(data.resultado_txt);
 $('#tipoLogradouro').html(data.tipo_logradouro);
 $('#logradouro').html(data.logradouro);
 $('#bairro').html(data.bairro);
 $('#cidade').html(data.cidade);
 $('#uf').html(data.uf);

 } else {
 alert(status);
 }
 });
 });
 */
/* fim busca por cep */

/* Cadastro de Clientes */
//atualizaTabela();

// piscar('.div_layout');

///*Testando drag and drop */
//$("#drag").draggable();
//$("#drop").droppable({
//    drop: function (event, ui) {
//        $(this).addClass("ui-state-highlight").find("p").html("Colocado!!!");
//    }
//});
//
//
///* Carrinho de compras com drag and drop */
//$("#catalogo li").draggable({
//    helper: "clone"
//});
//$("#carrinho ul").droppable({
//    drop: function (event, ui) {
//        $(this).append($("
").addClass("list-group-item").text(ui.draggable.text()));
//        $(this).find(".mensagem").remove();
//    }
//});
//
///* Selecionando elementos */
//$("#selectable").selectable();
//

/* Ordena elementos */
$("#sortable").sortable();


text:
1. Static code analysis should be performed. That is why you should use TypeScript, if you use JavaScript.
2. At least a couple of tests should run, at each build. They should ensure that:
    1. everything is wired correctly.
    2. the integration is able to run.
    3. no required libraries are missing.
    4. the [lookup](text-lookup.md) of issues within the original text works properly.
3. The tests of the [Test Sidebar](test-sidebar.md) must pass.
4. Use the [request validator](https://docs.acrolinx.com/kb/en/how-to-use-the-request-validator-13730818.html) (`<ACROLINX_SERVER:PORT>/request-validator/`)
   to verify what is sent to the Acrolinx Platform and that all information is filled out properly.
Manual testing is required for the cases that aren't covered by automated tests.

## Static Code Analysis

A linter helps identify possible bugs, and looking for potential problems like:

* unused code,
* complicated code,
* redundant code,
* code smells, and
* bad practices.

### JavaScript

Running a linting tool like:

* *JSHint*,
* *JSLint*, or
* *ESLint* at build time is mandatory.

### C\#

* Assertions or, better yet,
* contracts should be used.

### Java

* Use:
    + Annotations or,
    + assertions or,
    + Google Preconditions.

### C++

* Boost
* Use a memory leak detector.

### Objective-C

* Use [static analyzer and leak detection in XCode](https://help.apple.com/xcode/mac/8.0/#/devb7babe820).
* [OCLint](http://oclint.org/).

## Automated Unit / Integration Testing

### JavaScript

* Mocha
* Chai
* Karma

### C++

* Boost

### C\#

* Visual Studio Unit Testing Framework / MSTest
* Moq

### Java

* JUnit
* Mockito
* Hamcrest

### Objective-C

* XCTest / XCode


text:
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/sirupsen/logrus"

	"k8s.io/test-infra/prow/config"
	"k8s.io/test-infra/prow/metrics"
	"k8s.io/test-infra/prow/pjutil/pprof"

	"k8s.io/test-infra/pkg/flagutil"
	prowflagutil "k8s.io/test-infra/prow/flagutil"
	configflagutil "k8s.io/test-infra/prow/flagutil/config"
	"k8s.io/test-infra/prow/gerrit/adapter"
	"k8s.io/test-infra/prow/interrupts"
	"k8s.io/test-infra/prow/logrusutil"
)

type options struct {
	cookiefilePath    string
	tokenPathOverride string
	config            configflagutil.ConfigOptions
	// lastSyncFallback is the path to sync the latest timestamp
	// Can be /local/path, gs://path/to/object or s3://path/to/object.
	lastSyncFallback       string
	dryRun                 bool
	kubernetes             prowflagutil.KubernetesOptions
	storage                prowflagutil.StorageClientOptions
	instrumentationOptions prowflagutil.InstrumentationOptions
	changeWorkerPoolSize   int
}

func (o *options) validate() error {
	if o.cookiefilePath != "" && o.tokenPathOverride != "" {
		return fmt.Errorf("only one of --cookiefile=%q --token-path=%q allowed, not both", o.cookiefilePath, o.tokenPathOverride)
	}
	if o.cookiefilePath == "" && o.tokenPathOverride == "" {
		logrus.Info("--cookiefile is not set, using anonymous authentication")
	}

	if err := o.config.Validate(o.dryRun); err != nil {
		return err
	}

	if o.lastSyncFallback == "" {
		return errors.New("--last-sync-fallback must be set")
	}

	if strings.HasPrefix(o.lastSyncFallback, "gs://") && !o.storage.HasGCSCredentials() {
		logrus.WithField("last-sync-fallback", o.lastSyncFallback).Info("--gcs-credentials-file unset, will try and access with a default service account")
	}
	if strings.HasPrefix(o.lastSyncFallback, "s3://") && !o.storage.HasS3Credentials() {
		logrus.WithField("last-sync-fallback", o.lastSyncFallback).Info("--s3-credentials-file unset, will try and access with auto-discovered credentials")
	}
	if o.changeWorkerPoolSize < 1 {
		return errors.New("change-worker-pool-size must be at least 1")
	}
	return nil
}

func gatherOptions(fs *flag.FlagSet, args ...string) options {
	var o options
	fs.StringVar(&o.cookiefilePath, "cookiefile", "", "Path to git http.cookiefile, leave empty for anonymous")
	fs.StringVar(&o.lastSyncFallback, "last-sync-fallback", "", "The /local/path, gs://path/to/object or s3://path/to/object to sync the latest timestamp")
	fs.BoolVar(&o.dryRun, "dry-run", false, "Run in dry-run mode, performing no modifying actions.")
	fs.StringVar(&o.tokenPathOverride, "token-path", "", "Force the use of the token in this path, use with gcloud auth print-access-token")
	fs.IntVar(&o.changeWorkerPoolSize, "change-worker-pool-size", 1, "Number of workers processing changes for each instance.")
	for _, group := range []flagutil.OptionGroup{&o.kubernetes, &o.storage, &o.instrumentationOptions, &o.config} {
		group.AddFlags(fs)
	}
	fs.Parse(args)
	return o
}

func main() {
	logrusutil.ComponentInit()

	o := gatherOptions(flag.NewFlagSet(os.Args[0], flag.ExitOnError), os.Args[1:]...)
	if err := o.validate(); err != nil {
		logrus.Fatalf("Invalid options: %v", err)
	}

	pprof.Instrument(o.instrumentationOptions)

	ca, err := o.config.ConfigAgent()
	if err != nil {
		logrus.WithError(err).Fatal("Error starting config agent.")
	}
	cfg := ca.Config

	// Expose Prometheus metrics
	metrics.ExposeMetrics("gerrit", cfg().PushGateway, o.instrumentationOptions.MetricsPort)

	prowJobClient, err := o.kubernetes.ProwJobClient(cfg().ProwJobNamespace, o.dryRun)
	if err != nil {
		logrus.WithError(err).Fatal("Error getting kube client.")
	}

	ctx := context.Background() // TODO(fejta): use something better
	op, err := o.storage.StorageClient(ctx)
	if err != nil {
		logrus.WithError(err).Fatal("Error creating opener")
	}

	gitClient, err := (&prowflagutil.GitHubOptions{}).GitClientFactory(o.cookiefilePath, &o.config.InRepoConfigCacheDirBase, o.dryRun)
	if err != nil {
		logrus.WithError(err).Fatal("Error creating git client.")
	}
	cacheGetter, err := config.NewInRepoConfigCacheHandler(o.config.InRepoConfigCacheSize, ca, gitClient, o.config.InRepoConfigCacheCopies)
	if err != nil {
		logrus.WithError(err).Fatal("Error creating InRepoConfigCacheGetter.")
	}
	c := adapter.NewController(ctx, prowJobClient, op, ca, o.cookiefilePath, o.tokenPathOverride, o.lastSyncFallback, o.changeWorkerPoolSize, cacheGetter)

	logrus.Infof("Starting gerrit fetcher")

	defer interrupts.WaitForGracefulShutdown()
	interrupts.Tick(func() {
		c.Sync()
	}, func() time.Duration {
		return cfg().Gerrit.TickInterval.Duration
	})
}


text:
"""
Test suite for the UHPPOTE RFID controller board module.

.. moduleauthor:: Andrew Vaughan <hello@andrewvaughan.io>
"""

import unittest

if __name__ == '__main__':
    testsuite = unittest.TestLoader().discover('.')
    unittest.TextTestRunner(verbosity=1).run(testsuite)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>MTB CAT1 Peripheral driver library: cy_stc_dmac_channel_config_t Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

MTB CAT1 Peripheral driver library

Data Fields

cy_stc_dmac_channel_config_t Struct Reference
DMAC         (Direct Memory Access Controller) » Data Structures

Description

This structure holds the initialization values for the DMAC channel.

Data Fields

cy_stc_dmac_descriptor_t * 	descriptor

 	The DMAC descriptor associated with the channel being initialized.  More...

uint32_t 	priority

 	This parameter specifies the channel's priority.  More...

bool 	enable

 	This parameter specifies if the channel is enabled after initializing.  More...

bool 	bufferable

 	This parameter specifies whether a write transaction can complete.  More...

Field Documentation

◆ descriptor

          cy_stc_dmac_descriptor_t* cy_stc_dmac_channel_config_t::descriptor

The DMAC descriptor associated with the channel being initialized.

◆ priority

          uint32_t cy_stc_dmac_channel_config_t::priority

This parameter specifies the channel's priority.

◆ enable

          bool cy_stc_dmac_channel_config_t::enable

This parameter specifies if the channel is enabled after initializing.

◆ bufferable

          bool cy_stc_dmac_channel_config_t::bufferable

This parameter specifies whether a write transaction can complete.

without waiting for the destination to accept the write transaction data.


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Smith Quiz</title>
        <link rel="stylesheet" href="/shared/smith-quiz/index.min.css">


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('content', '0086_auto_20190116_1955'),
    ]

    operations = [
        migrations.AlterField(
            model_name='greenfund',
            name='revolving_fund',
            field=models.CharField(choices=[(b'Yes', b'Yes'), (b'No', b'No')], help_text=b'Indicate "Yes" if this is a revolving loan fund (i.e.,\n        the fund makes loans that are eventually repaid back into the fund).', max_length=3, verbose_name=b'Revolving Loan Fund'),
        ),
    ]


text:
var config = require('./webpack.config');
var webpack = require('webpack');

config.plugins = config.plugins.filter(function removeDefinePlugin(plugin) {
    return !(plugin instanceof webpack.DefinePlugin);
});

config.plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
        warnings: false,
    },
    mangle: {
        except: ['$super', '$', 'exports', 'require', 'angular', 'window'],
    },
}));

config.plugins.push(new webpack.optimize.DedupePlugin());
config.plugins.push(new webpack.optimize.OccurenceOrderPlugin());
config.plugins.push(new webpack.DefinePlugin({DEBUG: false}));

// Die on errors
config.bail = true;

config.eslint.failOnError = true;
delete config.eslint.formatter;

config.devtool = 'source-map';

module.exports = config;


text:
CGRect WMFConvertAndNormalizeCGRectUsingSize(CGRect rect, CGSize size) {
    CGAffineTransform normalizeAndConvertTransform =
        CGAffineTransformConcat(WMFAffineCoreGraphicsToUIKitTransformMake(size),
                                WMFAffineNormalizeTransformMake(size));
    return CGRectApplyAffineTransform(rect, normalizeAndConvertTransform);
}

#pragma mark - Normalization

CGRect WMFNormalizeRectUsingSize(CGRect rect, CGSize size) {
    if (CGSizeEqualToSize(size, CGSizeZero) || CGRectIsEmpty(rect)) {
        return CGRectZero;
    }
    return CGRectApplyAffineTransform(rect, WMFAffineNormalizeTransformMake(size));
}

CGRect WMFDenormalizeRectUsingSize(CGRect rect, CGSize size) {
    if (CGSizeEqualToSize(size, CGSizeZero) || CGRectIsEmpty(rect)) {
        return CGRectZero;
    }
    return CGRectApplyAffineTransform(rect, WMFAffineDenormalizeTransformMake(size));
}

#pragma mark - Normalization Transforms

CGAffineTransform WMFAffineNormalizeTransformMake(CGSize size) {
    if (CGSizeEqualToSize(size, CGSizeZero)) {
        return CGAffineTransformIdentity;
    }
    return CGAffineTransformMakeScale(1.0f / size.width, 1.0f / size.height);
}

CGAffineTransform WMFAffineDenormalizeTransformMake(CGSize size) {
    return CGAffineTransformInvert(WMFAffineNormalizeTransformMake(size));
}

#pragma mark - Coordinate System Conversions

CGRect WMFConvertCGCoordinateRectToUICoordinateRectUsingSize(CGRect cgRect, CGSize size) {
    return CGRectApplyAffineTransform(cgRect, WMFAffineCoreGraphicsToUIKitTransformMake(size));
}

CGRect WMFConvertUICoordinateRectToCGCoordinateRectUsingSize(CGRect uiRect, CGSize size) {
    return CGRectApplyAffineTransform(uiRect, WMFAffineUIKitToCoreGraphicsTransformMake(size));
}

#pragma mark - Coordinate System Conversion Transforms

CGAffineTransform WMFAffineCoreGraphicsToUIKitTransformMake(CGSize size) {
    if (CGSizeEqualToSize(size, CGSizeZero)) {
        return CGAffineTransformIdentity;
    }
    CGAffineTransform transform = CGAffineTransformMakeScale(1, -1);
    return CGAffineTransformTranslate(transform, 0, -size.height);
}

CGAffineTransform WMFAffineUIKitToCoreGraphicsTransformMake(CGSize size) {
    return CGAffineTransformInvert(WMFAffineCoreGraphicsToUIKitTransformMake(size));
}


text:
dataState = {}

function dataState:enter()
  dataBG = nImg("images/databg.png")
  Timer.tween(1, fader, { alpha = 0})
  gameEnv.data.sums = loadSummaries()
  gameEnv.data.dataMenu = makeDataMenu(gameEnv.data.sums)
end

function dataState:update(dt)
  Timer.update(dt)
  updateMenus(dt)
  basicUpdateCursor()
end

function dataState:draw()
  resetColor()
  gDraw(dataBG, 0, 0)
  drawMenus()
  sColor(0, 0, 0, fader.alpha)
  rekt("fill", 0, 0, winWidth, winHeight)
  resetColor()
end

function dataState:mousereleased()
  checkClick()
end

function dataState:leave()
  gameEnv.data.sums = nil
  gameEnv.data.dataMenu = nil
end

-- Loads the "summary" data for all savefiles
function loadSummaries()
  local summArray = {}
  for i=1, 3 do
    summArray[i] = {}
    local s = summArray[i]
    if love.filesystem.exists( "SUMMARY" .. i ) then
      local loadedSumm = love.filesystem.load( "SUMMARY" .. i )
      loadedSumm = loadedSumm()
      s.chname = loadedSumm.chname
      s.chportrait = loadedSumm.chportrait
      s.roomname = loadedSumm.roomname
      s.file = true
      if s.chportrait then
        s.pImg = nImg(PORTRAITS .. s.chportrait .. ".png")
      end
    else
      s.chname = "Empty Slot"
      s.file = false
    end
  end
  return summArray
end

-- Makes the menu for data
function makeDataMenu(data)
  local menuWidth = winWidth * 0.5
  if winHeight <= 480 then menuWidth = winWidth * 0.75 end
  local menuMargin = (winWidth - menuWidth)/2
  local menu = newMenu(menuMargin, winHeight * 0.05, menuWidth, "filled", "Data Selection", nil, nil, true, winHeight * 0.90)
  local submenus = {}
  for i=1, 3 do
    submenus[i] = menu:addSubMenu(0, (i-1)*(winHeight/4), true, menu.w - 16, winHeight/3.8)
    local submenu = submenus[i]
    submenu:addText("Slot " .. i .. ":", false, menu.contentW, 16, "left", 0, 0)
    if winHeight <= 480 then
      local slotStr = data[i].chname
      if data[i].roomname then slotStr = slotStr .. " : " .. data[i].roomname end
      submenu:addText(slotStr, false, menu.contentW - 2, 16, "left", 2, 30)
      if data[i].pImg then submenu:addPicture(data[i].pImg, false, submenu.contentW - 60, 4, 0.5) end
    else
      submenu:addText(data[i].chname, false, menu.contentW - 16, 16, "left", 16, 30)
      if data[i].roomname then submenu:addText(data[i].roomname, false, menu.contentW - 16, 16, "left", 16, 60) end
      if data[i].pImg then submenu:addPicture(data[i].pImg, false, submenu.contentW - 100, 0) end
    end
    if data[i].file == true then
      submenu:addTextButt({btnLoadGame, i}, "Load", nil, submenu.contentW/2-16, nil, 0, submenu.contentH - 32)
      submenu:addTextButt({btnDeleteGame, i}, "Delete", nil, submenu.contentW/2-16, nil, submenu.contentW/2, submenu.contentH - 32)
    else
      submenu:addTextButt({btnNewGame, i}, "New Game", nil, submenu.contentW-16, nil, 0, submenu.contentH - 32)
    end
  end
  menu:addTextButt({btnConfirmQuit}, "Exit to OS", nil, menu.contentW-32, nil, 16, menu.contentH - 32)
  return menu
end


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Eft.Interpreter
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls hist. -nat. Mus. natn. hung. 8: 8 (1910)

#### Original name
Cercospora nigellae Hollós, 1910

### Remarks
null


text:
<?php
/**
 * Model property
 *
 * @author Frederic BAYLE <contact (at) made-in-softland (dot) com>
 * @version 2017-05-01
 */

namespace EDP\Models;

use EDP\EDPObject;

/**
 * Model property
 *
 * @property string $DbField Name of a database field to bind with the model property
 * @property bool   $DbKey   Flag that indicates whether the property is a primary key of a database table
 * @property string $Type    Property type
 */
class ModelProperty extends EDPObject
{
    /**
     * Name of a database field to bind with the model property
     *
     * @var string
     */
    protected $_DbField = '';

    /**
     * Flag that indicates whether the property is a primary key of a database table
     *
     * @var bool
     */
    protected $_DbKey = false;

    /**
     * Property type
     *
     * @var string
     */
    protected $_Type = 'string';

    /**
     * Gets the name of a database field to bind with the model property
     *
     * @return string Name of a database field to bind with the model property
     */
    protected function &GetDbField()
    {
        return $this->_DbField;
    }

    /**
     * Gets a flag that indicates whether the property is a primary key of a database table
     *
     * @return bool Flag that indicates whether the property is a primary key of a database table
     */
    protected function &GetDbKey()
    {
        return $this->_DbKey;
    }

    /**
     * Gets the property type
     *
     * @return string Property type
     */
    protected function &GetType()
    {
        return $this->_Type;
    }

    /**
     * Sets the name of a database field to bind with the model property
     *
     * @param string $pValue Name of a database field to bind with the model property
     */
    protected function SetDbField($pValue)
    {
        $this->_DbField = $pValue;
    }

    /**
     * Sets a flag that indicates whether the property is a primary key of a database table
     *
     * @param bool $pValue Flag that indicates whether the property is a primary key of a database table
     */
    protected function SetDbKey($pValue)
    {
        $this->_DbKey = $pValue;
    }

    /**
     * Sets the property type
     *
     * @param string $pValue Property type
     */
    protected function SetType($pValue)
    {
        $this->_Type = $pValue;
    }
}


text:
package keyStorages

import (
	"errors"
	log "github.com/Sirupsen/logrus"
)

var (
	// ErrStorageKeyNotFound - returned when value is not fould in storage (source or fallback cache)
	ErrStorageKeyNotFound = errors.New("Storage: Key not found")

	// ErrStorageConnectionFailed - returned when there was connection error to storage (source or fallback cache)
	ErrStorageConnectionFailed = errors.New("Storage: Connection failed")
)

type fallbackCache interface {
	Get(key string) (string, error)
	Set(key, value string) error
	Remove(key string) error
}

type source interface {
	Get(key string) (string, error)
}

// Proxy - key storage fallback proxy.
// 	Always deal with source key storage first, and sync values with fallback cache storage
//      If source key storage is unavailable fallback to cache storage
type Proxy struct {
	fallbackCache fallbackCache
	source        source
}

// Get - fetch value from key storage
func (c *Proxy) Get(name string) (value string, err error) {
	logger := log.WithFields(log.Fields{"class": "Proxy", "method": "Get"})

	logger.Debugf("Backend lookup %v", name)

	value, err = c.lookupIn(c.source, name)

	switch err {
	case nil:
		logger.Debugf("Backend found %v", name)
		c.saveTo(c.fallbackCache, name, value)
		return

	case ErrStorageKeyNotFound:
		c.removeFrom(c.fallbackCache, name)
		return

	default:
		logger.Debug("Backend failed")
		logger.Debug("Fallback to cache")
		value, err = c.fallbackCache.Get(name)
		return
	}
}

func (c *Proxy) lookupIn(storage source, name string) (string, error) {
	return storage.Get(name)
}

func (c *Proxy) saveTo(storage fallbackCache, name, value string) error {
	logger := log.WithFields(log.Fields{"class": "Proxy", "method": "saveTo"})
	logger.Debugf("Saving to cache %v: %v", name, value)
	return storage.Set(name, value)
}

func (c *Proxy) removeFrom(storage fallbackCache, name string) error {
	logger := log.WithFields(log.Fields{"class": "Proxy", "method": "removeFrom"})
	logger.Debugf("Remove %v from cache", name)
	return storage.Remove(name)
}

// NewProxy - constructor to create Proxy object
func NewProxy(source source, fallbackCache fallbackCache) *Proxy {
	return &Proxy{source: source, fallbackCache: fallbackCache}
}


text:
		新增{{currentView.name}}
		编辑{{currentView.name}}

    <form class="form-horizontal" role="form" name="editForm">

             标记的项目不能为空

            {{field.title}}

                    <input class="form-control" name="{{field.name}}" type="text" ng-model="entity[field.name]"
                           ng-required="!!field.required">

            {{field.title}}

                <input class="form-control" type="text" ng-model="entity[field.name]" ng-required="!!field.required">

                <button ng-disabled="editForm.$error.required" ng-click="create(entity)" class="btn btn-primary btn-lg"
                        ng-if="!entity.id"> 创建
                </button>
                <button ng-disabled="editForm.$invalid" ng-click="update(entity)" class="btn btn-primary btn-lg"
                        ng-if="!!entity.id"> 保存
                </button>
                <button ng-click="cancelEdit()" class="btn btn-warning btn-lg"> 取消
                </button>

    </form>

        <button type="button" class="close" ng-click="closeCreate()">×</button>

新建用户

        <form ng-model="entity">
            <fieldset>

                    用户名

                        <input class="input-xlarge span5 focused" ng-model="entity.username" id="username" type="text" required>

                    <button type="button" class="close" data-dismiss="alert">×</button>

警告!

{{errorDetail}}

            </fieldset>
        </form>

        关闭
        修改密码


text:
#pragma once
#include <aws/waf-regional/WAFRegional_EXPORTS.h>
#include <aws/waf-regional/WAFRegionalRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace WAFRegional
{
namespace Model
{

  /**
   */
  class AWS_WAFREGIONAL_API GetChangeTokenStatusRequest : public WAFRegionalRequest
  {
  public:
    GetChangeTokenStatusRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetChangeTokenStatus"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The change token for which you want to get the status. This change token was
     * previously returned in the GetChangeToken response.

     */
    inline const Aws::String& GetChangeToken() const{ return m_changeToken; }

    /**
     *
The change token for which you want to get the status. This change token was
     * previously returned in the GetChangeToken response.

     */
    inline bool ChangeTokenHasBeenSet() const { return m_changeTokenHasBeenSet; }

    /**
     *
The change token for which you want to get the status. This change token was
     * previously returned in the GetChangeToken response.

     */
    inline void SetChangeToken(const Aws::String& value) { m_changeTokenHasBeenSet = true; m_changeToken = value; }

    /**
     *
The change token for which you want to get the status. This change token was
     * previously returned in the GetChangeToken response.

     */
    inline void SetChangeToken(Aws::String&& value) { m_changeTokenHasBeenSet = true; m_changeToken = std::move(value); }

    /**
     *
The change token for which you want to get the status. This change token was
     * previously returned in the GetChangeToken response.

     */
    inline void SetChangeToken(const char* value) { m_changeTokenHasBeenSet = true; m_changeToken.assign(value); }

    /**
     *
The change token for which you want to get the status. This change token was
     * previously returned in the GetChangeToken response.

     */
    inline GetChangeTokenStatusRequest& WithChangeToken(const Aws::String& value) { SetChangeToken(value); return *this;}

    /**
     *
The change token for which you want to get the status. This change token was
     * previously returned in the GetChangeToken response.

     */
    inline GetChangeTokenStatusRequest& WithChangeToken(Aws::String&& value) { SetChangeToken(std::move(value)); return *this;}

    /**
     *
The change token for which you want to get the status. This change token was
     * previously returned in the GetChangeToken response.

     */
    inline GetChangeTokenStatusRequest& WithChangeToken(const char* value) { SetChangeToken(value); return *this;}

  private:

    Aws::String m_changeToken;
    bool m_changeTokenHasBeenSet = false;
  };

} // namespace Model
} // namespace WAFRegional
} // namespace Aws


text:
<?php

/**
 * Git Stream Wrapper for PHP
 *
 * @category   TQ
 * @package    TQ_VCS
 * @subpackage SVN
 * @copyright  Copyright (C) 2018 by TEQneers GmbH & Co. KG
 */

namespace TQ\Svn\StreamWrapper\FileBuffer\Factory;
use TQ\Vcs\Repository\RepositoryInterface;
use TQ\Vcs\StreamWrapper\FileBuffer\Factory\AbstractLogFactory;

/**
 * Factory to create a log buffer
 *
 * @author     Stefan Gehrig <gehrigteqneers.de>
 * @category   TQ
 * @package    TQ_VCS
 * @subpackage SVN
 * @copyright  Copyright (C) 2018 by TEQneers GmbH & Co. KG
 */
class LogFactory extends AbstractLogFactory
{
    /**
     * Creates the log string to be fed into the string buffer
     *
     * @param   RepositoryInterface     $repository The repository
     * @param   integer|null            $limit      The maximum number of log entries returned
     * @param   integer|null            $skip       Number of log entries that are skipped from the beginning
     * @return  string
     */
    protected function createLogString(RepositoryInterface $repository, $limit, $skip)
    {
        return implode(
            str_repeat(PHP_EOL, 3),
            array_map(
                function(array $log) {
                    return sprintf('r%d | %s | %s:'.PHP_EOL.'%s', $log[0], $log[2], $log[1], $log[3]);
                },
                $repository->getLog($limit, $skip)
            )
        );
    }
}


text:
Is
==

A better way to write JavaScript conditional statements and still have pretty code.

This library was inspired by the Maybe Monad pattern and libraries like Jasmine.js and JQuery. It allows you to write conditional statements without nested if statements or null checking.

###Installation

Just include the minified script in your project. It's really tiny (1kb minified and zipped)
```
<script src="is.min.js"></script>
```
Or, if you're using TypeScript (and why aren't you using TyepScript?), include the definition file in your main class.
```
/// <reference path="is.d.ts" />
```
For use with Node.js.
```
var Is = require('Is');
```
###How Does It Work?
  Typically, a lot of checks go into working with variables, especially when the values are returned by ajax calls or user input. This results in a lot of nested if statements that check for values to be defined, but also to pass various validation checks. For instance, see this code:

  ```
  var foo="bar";
  if(foo){
    if(foo.length>0){
      if(foo == "bar2"){
         throw new Error("bad foo");
      }else if(foo!="bar"){
         throw new Error("bad foo");
      }
    }else{
      throw new Error("bad foo");
    }
  }else{
      throw new Error("bad foo");
  }
  ```

A better way to handle this is to write the code in such a way that when any single step fails, the chain is broken and none of the other steps are executed. A single `catch` function can handle the failure. So using Is, the preceding code can be rewritten as:
  ```

  var foo="bar";
  Is(foo)
    .longerThan(0)
    .equalTo("bar")
    .not.equalTo("bar2")
    .then(()=>{
      console.log("success")
    })
    .catch(()=>{
      throw new Error("bad foo");
    });
```

This allows the code to read almost like spoken words, which hopefully leads to more maintainable code.

There are several methods available for checking the input value. If a validation method is successful, Is returns an instance of Is with the value, otherwise it returns one with nothing in it, which stops the chain.

```
  var foo="bar";
  Is(foo)
  .longerThan(number) // checks the length of a string for minimum length
  .shorterThan(number) // checks the length of a string for maximum length
  .equalTo("bar") // checks for exact value
  .not // inverts the next validation
  .equalTo("baz")

  Is(1000)
  .numeric() // returns true if the value is a number
  .lessThan(10000) // checks for maximum value
  .greaterThan(0) // checks for minimum value

  Is(100)
    .any("<101",">1000") // you can use a shorthand and check for any of these things to be true
    .is("<101", ">99") // or check that all validations are true

  Is("foo")
      .is("length>1") // check for string length

  Is([1,2,3])
    .not.emptyArray() //check if array is empty
    .contains(2) //check if array has a specific value in it

  var validEmail = function (val:string) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(val);
  };

  Is("john.doe@fakeemail.com")
    .is(validEmail) //you can use a function as an argument which returns true of false

  Is("john.doe@fakeemail.com")
    .is(validEmail)
    .then(()=>{
      consolde.log("valid email") //if the chain succeeds, you can run a callback using "then"
    });

  Is("john.doefakeemail.com")
    .is(validEmail)
    .catch(()=>{
      consolde.log("bad email") //if the chain fails, you can run a callback using "catch"
    });

  Is("john.doefakeemail.com")
    .is(validEmail)
    .catch(()=>{
      //bad email
    }).finally(()=>{
      //using this method, you can run a callback using "finally" no matter what happens
    });

```
####Dealing with `or` statements
One of the matchers above is the `matchingAny` method. This checks to see if any of the strings, or shorthand matchers are true. But you can also use the `or` method.
```
    Is({foo:3,bar:"baz"})
      .prop("foo").lessThan(2) // this is false, but with the _or_ method immedatiately following it...
      .or.prop("bar").longerThan(1) //this is true, so the whole chain is valid
      .then(()=> {
           //do something cool here
      });
```

####Checking for undefined variables
The best part of all this is that you no longer need to worry about undefined variable values at all. For instance, if you have a value like this:

```
var foo={bar:undefined};

 Is(foo.bar)
  .longerThan(3)
  .catch(()=>{
    console.log("no value") // this gets called no matter what the value of foo.bar is
  })
```

####Complex objects
You can even work with complex objects and work with their properties. So for instance, maybe working with form values:
```
 var validEmail = function (val:string) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(val);
        };
        var complexObject={
            arr:[1,2,3],
            str: "foo",
            num: 10,
            email:"joe.smith@fakeemail.com"
        }
        Is(complexObject)
         .prop("arr").not.emptyArray()
         .and.prop("arr").contains(3) // prop looks for property of complexObject named "arr"
         .and.prop("str").longerThan(2) //must be called prior to each validation check
         .and.prop("str").shorterThan(4) //"and" makes code more readable
         .and.prop("str").equalTo("foo")
         .and.prop("num").numeric()
         .and.prop("email").matching(validEmail)
         .then(()=> {
                // all of these things are true -- submit form?
         }).catch(()=> {
                //at least one of these things are not true
         });
 ```
You can also instantiate the chain by either using the `new` command or by using the `Facade`

```
Is("foo")
 .longerThan(2)
 .then(()=>{
   // callback
 });

 new jumpkick.Is("foo")
 .longerThan(2)
 .then(()=>{
   // callback
 });
```


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
using System.Reflection;
#endif

[System.AttributeUsage(System.AttributeTargets.Field)]
public class WebCamNameAttribute : PropertyAttribute
{
}

#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(WebCamNameAttribute))]
public class WebCamNameAttributePropertyDrawer : PropertyDrawer
{
	public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
	{
		var Attrib = (WebCamNameAttribute)attribute;
		var TargetObject = property.serializedObject.targetObject;

		var WebCamName = property.stringValue;

		EditorGUI.BeginChangeCheck();

		var Options = new List<string>();
		var OtherIndex = Options.Count;
		var OtherLabel = "Custom...";
		Options.Add(OtherLabel);
		int SelectedIndex = OtherIndex;
		var Devices = WebCamTexture.devices;
		foreach (var Device in Devices)
		{
			if (WebCamName.Equals(Device.name))
				SelectedIndex = Options.Count;
			Options.Add(Device.name);
		}

		position.height = base.GetPropertyHeight(property, label);

		var WasMatch = (SelectedIndex != OtherIndex);
		SelectedIndex = EditorGUI.Popup(position, property.displayName, SelectedIndex, Options.ToArray());

		if (SelectedIndex == OtherIndex)
		{
			//	need to reset the label if it changed, otherwise it'll revert back to a selection again
			if ( WasMatch )
				WebCamName = "";
			position.y += position.height;
			WebCamName = EditorGUI.TextField(position, OtherLabel, WebCamName);
		}
		else
		{
			WebCamName = Options[SelectedIndex];
		}

		if (EditorGUI.EndChangeCheck())
		{
			property.stringValue = WebCamName;
		}

		property.serializedObject.ApplyModifiedProperties();
	}

	public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
	{
		var OrigHeight = base.GetPropertyHeight(property, label);
		return OrigHeight * 2;
	}
}
#endif


text:
@interface OrgApacheLuceneSearchTopTermsRewrite () {
 @public
  jint size_;
}

@end

inline id<JavaUtilComparator> OrgApacheLuceneSearchTopTermsRewrite_get_scoreTermSortByTermComp(void);
static id<JavaUtilComparator> OrgApacheLuceneSearchTopTermsRewrite_scoreTermSortByTermComp;
J2OBJC_STATIC_FIELD_OBJ_FINAL(OrgApacheLuceneSearchTopTermsRewrite, scoreTermSortByTermComp, id<JavaUtilComparator>)

@interface OrgApacheLuceneSearchTopTermsRewrite_1 : OrgApacheLuceneSearchTermCollectingRewrite_TermCollector {
 @public
  JavaUtilPriorityQueue *val$stQueue_;
  jint val$maxSize_;
  id<OrgApacheLuceneSearchMaxNonCompetitiveBoostAttribute> maxBoostAtt_;
  id<JavaUtilMap> visitedTerms_;
  OrgApacheLuceneIndexTermsEnum *termsEnum_;
  id<OrgApacheLuceneSearchBoostAttribute> boostAtt_;
  OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *st_;
  OrgApacheLuceneUtilBytesRefBuilder *lastTerm_;
}

- (instancetype)initWithJavaUtilPriorityQueue:(JavaUtilPriorityQueue *)capture$0
                                      withInt:(jint)capture$1;

- (void)setNextEnumWithOrgApacheLuceneIndexTermsEnum:(OrgApacheLuceneIndexTermsEnum *)termsEnum;

- (jboolean)compareToLastTermWithOrgApacheLuceneUtilBytesRef:(OrgApacheLuceneUtilBytesRef *)t;

- (jboolean)collectWithOrgApacheLuceneUtilBytesRef:(OrgApacheLuceneUtilBytesRef *)bytes;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneSearchTopTermsRewrite_1)

J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchTopTermsRewrite_1, maxBoostAtt_, id<OrgApacheLuceneSearchMaxNonCompetitiveBoostAttribute>)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchTopTermsRewrite_1, visitedTerms_, id<JavaUtilMap>)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchTopTermsRewrite_1, termsEnum_, OrgApacheLuceneIndexTermsEnum *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchTopTermsRewrite_1, boostAtt_, id<OrgApacheLuceneSearchBoostAttribute>)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchTopTermsRewrite_1, st_, OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchTopTermsRewrite_1, lastTerm_, OrgApacheLuceneUtilBytesRefBuilder *)

__attribute__((unused)) static void OrgApacheLuceneSearchTopTermsRewrite_1_initWithJavaUtilPriorityQueue_withInt_(OrgApacheLuceneSearchTopTermsRewrite_1 *self, JavaUtilPriorityQueue *capture$0, jint capture$1);

__attribute__((unused)) static OrgApacheLuceneSearchTopTermsRewrite_1 *new_OrgApacheLuceneSearchTopTermsRewrite_1_initWithJavaUtilPriorityQueue_withInt_(JavaUtilPriorityQueue *capture$0, jint capture$1) NS_RETURNS_RETAINED;

__attribute__((unused)) static OrgApacheLuceneSearchTopTermsRewrite_1 *create_OrgApacheLuceneSearchTopTermsRewrite_1_initWithJavaUtilPriorityQueue_withInt_(JavaUtilPriorityQueue *capture$0, jint capture$1);

__attribute__((unused)) static jboolean OrgApacheLuceneSearchTopTermsRewrite_1_compareToLastTermWithOrgApacheLuceneUtilBytesRef_(OrgApacheLuceneSearchTopTermsRewrite_1 *self, OrgApacheLuceneUtilBytesRef *t);

@interface OrgApacheLuceneSearchTopTermsRewrite_2 : NSObject < JavaUtilComparator >

- (instancetype)init;

- (jint)compareWithId:(OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *)st1
               withId:(OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *)st2;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneSearchTopTermsRewrite_2)

__attribute__((unused)) static void OrgApacheLuceneSearchTopTermsRewrite_2_init(OrgApacheLuceneSearchTopTermsRewrite_2 *self);

__attribute__((unused)) static OrgApacheLuceneSearchTopTermsRewrite_2 *new_OrgApacheLuceneSearchTopTermsRewrite_2_init(void) NS_RETURNS_RETAINED;

__attribute__((unused)) static OrgApacheLuceneSearchTopTermsRewrite_2 *create_OrgApacheLuceneSearchTopTermsRewrite_2_init(void);

J2OBJC_INITIALIZED_DEFN(OrgApacheLuceneSearchTopTermsRewrite)

@implementation OrgApacheLuceneSearchTopTermsRewrite

- (instancetype)initWithInt:(jint)size {
  OrgApacheLuceneSearchTopTermsRewrite_initWithInt_(self, size);
  return self;
}

- (jint)getSize {
  return size_;
}

- (jint)getMaxSize {
  // can't call an abstract method
  [self doesNotRecognizeSelector:_cmd];
  return 0;
}

- (OrgApacheLuceneSearchQuery *)rewriteWithOrgApacheLuceneIndexIndexReader:(OrgApacheLuceneIndexIndexReader *)reader
                                   withOrgApacheLuceneSearchMultiTermQuery:(OrgApacheLuceneSearchMultiTermQuery *)query {
  jint maxSize = JavaLangMath_minWithInt_withInt_(size_, [self getMaxSize]);
  JavaUtilPriorityQueue *stQueue = create_JavaUtilPriorityQueue_init();
  [self collectTermsWithOrgApacheLuceneIndexIndexReader:reader withOrgApacheLuceneSearchMultiTermQuery:query withOrgApacheLuceneSearchTermCollectingRewrite_TermCollector:create_OrgApacheLuceneSearchTopTermsRewrite_1_initWithJavaUtilPriorityQueue_withInt_(stQueue, maxSize)];
  id b = [self getTopLevelBuilder];
  IOSObjectArray *scoreTerms = [stQueue toArrayWithNSObjectArray:[IOSObjectArray arrayWithLength:[stQueue size] type:OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm_class_()]];
  OrgApacheLuceneUtilArrayUtil_timSortWithNSObjectArray_withJavaUtilComparator_(scoreTerms, OrgApacheLuceneSearchTopTermsRewrite_scoreTermSortByTermComp);
  {
    IOSObjectArray *a__ = scoreTerms;
    OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm * const *b__ = ((IOSObjectArray *) nil_chk(a__))->buffer_;
    OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm * const *e__ = b__ + a__->size_;
    while (b__ < e__) {
      OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *st = *b__++;
      OrgApacheLuceneIndexTerm *term = create_OrgApacheLuceneIndexTerm_initWithNSString_withOrgApacheLuceneUtilBytesRef_(((OrgApacheLuceneSearchMultiTermQuery *) nil_chk(query))->field_, [((OrgApacheLuceneUtilBytesRefBuilder *) nil_chk(((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(st))->bytes_)) toBytesRef]);
      [self addClauseWithId:b withOrgApacheLuceneIndexTerm:term withInt:[((OrgApacheLuceneIndexTermContext *) nil_chk(st->termState_)) docFreq] withFloat:[query getBoost] * st->boost_ withOrgApacheLuceneIndexTermContext:st->termState_];
    }
  }
  return [self buildWithId:b];
}

- (NSUInteger)hash {
  return 31 * size_;
}

- (jboolean)isEqual:(id)obj {
  if (JreObjectEqualsEquals(self, obj)) return true;
  if (obj == nil) return false;
  if (!JreObjectEqualsEquals([self java_getClass], [obj java_getClass])) return false;
  OrgApacheLuceneSearchTopTermsRewrite *other = (OrgApacheLuceneSearchTopTermsRewrite *) cast_chk(obj, [OrgApacheLuceneSearchTopTermsRewrite class]);
  if (size_ != other->size_) return false;
  return true;
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x1, -1, 0, -1, -1, -1, -1 },
    { NULL, "I", 0x1, -1, -1, -1, -1, -1, -1 },
    { NULL, "I", 0x404, -1, -1, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneSearchQuery;", 0x11, 1, 2, 3, -1, -1, -1 },
    { NULL, "I", 0x1, 4, -1, -1, -1, -1, -1 },
    { NULL, "Z", 0x1, 5, 6, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(initWithInt:);
  methods[1].selector = @selector(getSize);
  methods[2].selector = @selector(getMaxSize);
  methods[3].selector = @selector(rewriteWithOrgApacheLuceneIndexIndexReader:withOrgApacheLuceneSearchMultiTermQuery:);
  methods[4].selector = @selector(hash);
  methods[5].selector = @selector(isEqual:);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "size_", "I", .constantValue.asLong = 0, 0x12, -1, -1, -1, -1 },
    { "scoreTermSortByTermComp", "LJavaUtilComparator;", .constantValue.asLong = 0, 0x1a, -1, 7, 8, -1 },
  };
  static const void *ptrTable[] = { "I", "rewrite", "LOrgApacheLuceneIndexIndexReader;LOrgApacheLuceneSearchMultiTermQuery;", "LJavaIoIOException;", "hashCode", "equals", "LNSObject;", &OrgApacheLuceneSearchTopTermsRewrite_scoreTermSortByTermComp, "Ljava/util/Comparator<Lorg/apache/lucene/search/TopTermsRewrite$ScoreTerm;>;", "LOrgApacheLuceneSearchTopTermsRewrite_ScoreTerm;", "<B:Ljava/lang/Object;>Lorg/apache/lucene/search/TermCollectingRewrite<TB;>;" };
  static const J2ObjcClassInfo _OrgApacheLuceneSearchTopTermsRewrite = { "TopTermsRewrite", "org.apache.lucene.search", ptrTable, methods, fields, 7, 0x401, 6, 2, -1, 9, -1, 10, -1 };
  return &_OrgApacheLuceneSearchTopTermsRewrite;
}

+ (void)initialize {
  if (self == [OrgApacheLuceneSearchTopTermsRewrite class]) {
    JreStrongAssignAndConsume(&OrgApacheLuceneSearchTopTermsRewrite_scoreTermSortByTermComp, new_OrgApacheLuceneSearchTopTermsRewrite_2_init());
    J2OBJC_SET_INITIALIZED(OrgApacheLuceneSearchTopTermsRewrite)
  }
}

@end

void OrgApacheLuceneSearchTopTermsRewrite_initWithInt_(OrgApacheLuceneSearchTopTermsRewrite *self, jint size) {
  OrgApacheLuceneSearchTermCollectingRewrite_initPackagePrivate(self);
  self->size_ = size;
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneSearchTopTermsRewrite)

@implementation OrgApacheLuceneSearchTopTermsRewrite_1

- (instancetype)initWithJavaUtilPriorityQueue:(JavaUtilPriorityQueue *)capture$0
                                      withInt:(jint)capture$1 {
  OrgApacheLuceneSearchTopTermsRewrite_1_initWithJavaUtilPriorityQueue_withInt_(self, capture$0, capture$1);
  return self;
}

- (void)setNextEnumWithOrgApacheLuceneIndexTermsEnum:(OrgApacheLuceneIndexTermsEnum *)termsEnum {
  JreStrongAssign(&self->termsEnum_, termsEnum);
  JreAssert(OrgApacheLuceneSearchTopTermsRewrite_1_compareToLastTermWithOrgApacheLuceneUtilBytesRef_(self, nil), @"org/apache/lucene/search/TopTermsRewrite.java:81 condition failed: assert compareToLastTerm(null);");
  if (st_ == nil) JreStrongAssignAndConsume(&st_, new_OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm_initWithOrgApacheLuceneIndexTermContext_(create_OrgApacheLuceneIndexTermContext_initWithOrgApacheLuceneIndexIndexReaderContext_(topReaderContext_)));
  JreStrongAssign(&boostAtt_, [((OrgApacheLuceneUtilAttributeSource *) nil_chk([((OrgApacheLuceneIndexTermsEnum *) nil_chk(termsEnum)) attributes])) addAttributeWithIOSClass:OrgApacheLuceneSearchBoostAttribute_class_()]);
}

- (jboolean)compareToLastTermWithOrgApacheLuceneUtilBytesRef:(OrgApacheLuceneUtilBytesRef *)t {
  return OrgApacheLuceneSearchTopTermsRewrite_1_compareToLastTermWithOrgApacheLuceneUtilBytesRef_(self, t);
}

- (jboolean)collectWithOrgApacheLuceneUtilBytesRef:(OrgApacheLuceneUtilBytesRef *)bytes {
  jfloat boost = [((id<OrgApacheLuceneSearchBoostAttribute>) nil_chk(boostAtt_)) getBoost];
  JreAssert(OrgApacheLuceneSearchTopTermsRewrite_1_compareToLastTermWithOrgApacheLuceneUtilBytesRef_(self, bytes), @"org/apache/lucene/search/TopTermsRewrite.java:110 condition failed: assert compareToLastTerm(bytes);");
  if ([((JavaUtilPriorityQueue *) nil_chk(val$stQueue_)) size] == val$maxSize_) {
    OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *t = [val$stQueue_ peek];
    if (boost < ((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(t))->boost_) return true;
    if (boost == t->boost_ && [((OrgApacheLuceneUtilBytesRef *) nil_chk(bytes)) compareToWithId:[((OrgApacheLuceneUtilBytesRefBuilder *) nil_chk(t->bytes_)) get]] > 0) return true;
  }
  OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *t = JreRetainedLocalValue([((id<JavaUtilMap>) nil_chk(visitedTerms_)) getWithId:bytes]);
  OrgApacheLuceneIndexTermState *state = [((OrgApacheLuceneIndexTermsEnum *) nil_chk(termsEnum_)) termState];
  JreAssert(state != nil, @"org/apache/lucene/search/TopTermsRewrite.java:123 condition failed: assert state != null;");
  if (t != nil) {
    JreAssert(t->boost_ == boost, @"boost should be equal in all segment TermsEnums");
    [((OrgApacheLuceneIndexTermContext *) nil_chk(t->termState_)) register__WithOrgApacheLuceneIndexTermState:state withInt:((OrgApacheLuceneIndexLeafReaderContext *) nil_chk(readerContext_))->ord_ withInt:[((OrgApacheLuceneIndexTermsEnum *) nil_chk(termsEnum_)) docFreq] withLong:[((OrgApacheLuceneIndexTermsEnum *) nil_chk(termsEnum_)) totalTermFreq]];
  }
  else {
    [((OrgApacheLuceneUtilBytesRefBuilder *) nil_chk(((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(st_))->bytes_)) copyBytesWithOrgApacheLuceneUtilBytesRef:bytes];
    ((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(st_))->boost_ = boost;
    [visitedTerms_ putWithId:[st_->bytes_ get] withId:st_];
    JreAssert([((OrgApacheLuceneIndexTermContext *) nil_chk(((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(st_))->termState_)) docFreq] == 0, @"org/apache/lucene/search/TopTermsRewrite.java:133 condition failed: assert st.termState.docFreq() == 0;");
    [((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(st_))->termState_ register__WithOrgApacheLuceneIndexTermState:state withInt:((OrgApacheLuceneIndexLeafReaderContext *) nil_chk(readerContext_))->ord_ withInt:[((OrgApacheLuceneIndexTermsEnum *) nil_chk(termsEnum_)) docFreq] withLong:[((OrgApacheLuceneIndexTermsEnum *) nil_chk(termsEnum_)) totalTermFreq]];
    [val$stQueue_ offerWithId:st_];
    if ([val$stQueue_ size] > val$maxSize_) {
      JreStrongAssign(&st_, [val$stQueue_ poll]);
      [visitedTerms_ removeWithId:[((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(st_))->bytes_ get]];
      [((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(st_))->termState_ clear];
    }
    else {
      JreStrongAssignAndConsume(&st_, new_OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm_initWithOrgApacheLuceneIndexTermContext_(create_OrgApacheLuceneIndexTermContext_initWithOrgApacheLuceneIndexIndexReaderContext_(topReaderContext_)));
    }
    JreAssert([val$stQueue_ size] <= val$maxSize_, @"the PQ size must be limited to maxSize");
    if ([val$stQueue_ size] == val$maxSize_) {
      t = [val$stQueue_ peek];
      [((id<OrgApacheLuceneSearchMaxNonCompetitiveBoostAttribute>) nil_chk(maxBoostAtt_)) setMaxNonCompetitiveBoostWithFloat:((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(t))->boost_];
      [maxBoostAtt_ setCompetitiveTermWithOrgApacheLuceneUtilBytesRef:[t->bytes_ get]];
    }
  }
  return true;
}

- (void)dealloc {
  RELEASE_(val$stQueue_);
  RELEASE_(maxBoostAtt_);
  RELEASE_(visitedTerms_);
  RELEASE_(termsEnum_);
  RELEASE_(boostAtt_);
  RELEASE_(st_);
  RELEASE_(lastTerm_);
  [super dealloc];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x0, -1, 0, -1, -1, -1, -1 },
    { NULL, "V", 0x1, 1, 2, -1, -1, -1, -1 },
    { NULL, "Z", 0x2, 3, 4, -1, -1, -1, -1 },
    { NULL, "Z", 0x1, 5, 4, 6, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(initWithJavaUtilPriorityQueue:withInt:);
  methods[1].selector = @selector(setNextEnumWithOrgApacheLuceneIndexTermsEnum:);
  methods[2].selector = @selector(compareToLastTermWithOrgApacheLuceneUtilBytesRef:);
  methods[3].selector = @selector(collectWithOrgApacheLuceneUtilBytesRef:);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "val$stQueue_", "LJavaUtilPriorityQueue;", .constantValue.asLong = 0, 0x1012, -1, -1, 7, -1 },
    { "val$maxSize_", "I", .constantValue.asLong = 0, 0x1012, -1, -1, -1, -1 },
    { "maxBoostAtt_", "LOrgApacheLuceneSearchMaxNonCompetitiveBoostAttribute;", .constantValue.asLong = 0, 0x12, -1, -1, -1, -1 },
    { "visitedTerms_", "LJavaUtilMap;", .constantValue.asLong = 0, 0x12, -1, -1, 8, -1 },
    { "termsEnum_", "LOrgApacheLuceneIndexTermsEnum;", .constantValue.asLong = 0, 0x2, -1, -1, -1, -1 },
    { "boostAtt_", "LOrgApacheLuceneSearchBoostAttribute;", .constantValue.asLong = 0, 0x2, -1, -1, -1, -1 },
    { "st_", "LOrgApacheLuceneSearchTopTermsRewrite_ScoreTerm;", .constantValue.asLong = 0, 0x2, -1, -1, -1, -1 },
    { "lastTerm_", "LOrgApacheLuceneUtilBytesRefBuilder;", .constantValue.asLong = 0, 0x2, -1, -1, -1, -1 },
  };
  static const void *ptrTable[] = { "LJavaUtilPriorityQueue;I", "setNextEnum", "LOrgApacheLuceneIndexTermsEnum;", "compareToLastTerm", "LOrgApacheLuceneUtilBytesRef;", "collect", "LJavaIoIOException;", "Ljava/util/PriorityQueue<Lorg/apache/lucene/search/TopTermsRewrite$ScoreTerm;>;", "Ljava/util/Map<Lorg/apache/lucene/util/BytesRef;Lorg/apache/lucene/search/TopTermsRewrite$ScoreTerm;>;", "LOrgApacheLuceneSearchTopTermsRewrite;", "rewriteWithOrgApacheLuceneIndexIndexReader:withOrgApacheLuceneSearchMultiTermQuery:" };
  static const J2ObjcClassInfo _OrgApacheLuceneSearchTopTermsRewrite_1 = { "", "org.apache.lucene.search", ptrTable, methods, fields, 7, 0x8010, 4, 8, 9, -1, 10, -1, -1 };
  return &_OrgApacheLuceneSearchTopTermsRewrite_1;
}

@end

void OrgApacheLuceneSearchTopTermsRewrite_1_initWithJavaUtilPriorityQueue_withInt_(OrgApacheLuceneSearchTopTermsRewrite_1 *self, JavaUtilPriorityQueue *capture$0, jint capture$1) {
  JreStrongAssign(&self->val$stQueue_, capture$0);
  self->val$maxSize_ = capture$1;
  OrgApacheLuceneSearchTermCollectingRewrite_TermCollector_init(self);
  JreStrongAssign(&self->maxBoostAtt_, [((OrgApacheLuceneUtilAttributeSource *) nil_chk(self->attributes_)) addAttributeWithIOSClass:OrgApacheLuceneSearchMaxNonCompetitiveBoostAttribute_class_()]);
  JreStrongAssignAndConsume(&self->visitedTerms_, new_JavaUtilHashMap_init());
}

OrgApacheLuceneSearchTopTermsRewrite_1 *new_OrgApacheLuceneSearchTopTermsRewrite_1_initWithJavaUtilPriorityQueue_withInt_(JavaUtilPriorityQueue *capture$0, jint capture$1) {
  J2OBJC_NEW_IMPL(OrgApacheLuceneSearchTopTermsRewrite_1, initWithJavaUtilPriorityQueue_withInt_, capture$0, capture$1)
}

OrgApacheLuceneSearchTopTermsRewrite_1 *create_OrgApacheLuceneSearchTopTermsRewrite_1_initWithJavaUtilPriorityQueue_withInt_(JavaUtilPriorityQueue *capture$0, jint capture$1) {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneSearchTopTermsRewrite_1, initWithJavaUtilPriorityQueue_withInt_, capture$0, capture$1)
}

jboolean OrgApacheLuceneSearchTopTermsRewrite_1_compareToLastTermWithOrgApacheLuceneUtilBytesRef_(OrgApacheLuceneSearchTopTermsRewrite_1 *self, OrgApacheLuceneUtilBytesRef *t) {
  if (self->lastTerm_ == nil && t != nil) {
    JreStrongAssignAndConsume(&self->lastTerm_, new_OrgApacheLuceneUtilBytesRefBuilder_init());
    [self->lastTerm_ appendWithOrgApacheLuceneUtilBytesRef:t];
  }
  else if (t == nil) {
    JreStrongAssign(&self->lastTerm_, nil);
  }
  else {
    JreAssert([((OrgApacheLuceneUtilBytesRef *) nil_chk([((OrgApacheLuceneUtilBytesRefBuilder *) nil_chk(self->lastTerm_)) get])) compareToWithId:t] < 0, JreStrcat("$@$@", @"lastTerm=", self->lastTerm_, @" t=", t));
    [((OrgApacheLuceneUtilBytesRefBuilder *) nil_chk(self->lastTerm_)) copyBytesWithOrgApacheLuceneUtilBytesRef:t];
  }
  return true;
}

@implementation OrgApacheLuceneSearchTopTermsRewrite_2

J2OBJC_IGNORE_DESIGNATED_BEGIN
- (instancetype)init {
  OrgApacheLuceneSearchTopTermsRewrite_2_init(self);
  return self;
}
J2OBJC_IGNORE_DESIGNATED_END

- (jint)compareWithId:(OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *)st1
               withId:(OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *)st2 {
  return [((OrgApacheLuceneUtilBytesRef *) nil_chk([((OrgApacheLuceneUtilBytesRefBuilder *) nil_chk(((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(st1))->bytes_)) get])) compareToWithId:[((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(st2))->bytes_ get]];
}

- (id<JavaUtilComparator>)reversed {
  return JavaUtilComparator_reversed(self);
}

- (id<JavaUtilComparator>)thenComparingWithJavaUtilComparator:(id<JavaUtilComparator>)arg0 {
  return JavaUtilComparator_thenComparingWithJavaUtilComparator_(self, arg0);
}

- (id<JavaUtilComparator>)thenComparingWithJavaUtilFunctionFunction:(id<JavaUtilFunctionFunction>)arg0
                                             withJavaUtilComparator:(id<JavaUtilComparator>)arg1 {
  return JavaUtilComparator_thenComparingWithJavaUtilFunctionFunction_withJavaUtilComparator_(self, arg0, arg1);
}

- (id<JavaUtilComparator>)thenComparingWithJavaUtilFunctionFunction:(id<JavaUtilFunctionFunction>)arg0 {
  return JavaUtilComparator_thenComparingWithJavaUtilFunctionFunction_(self, arg0);
}

- (id<JavaUtilComparator>)thenComparingIntWithJavaUtilFunctionToIntFunction:(id<JavaUtilFunctionToIntFunction>)arg0 {
  return JavaUtilComparator_thenComparingIntWithJavaUtilFunctionToIntFunction_(self, arg0);
}

- (id<JavaUtilComparator>)thenComparingLongWithJavaUtilFunctionToLongFunction:(id<JavaUtilFunctionToLongFunction>)arg0 {
  return JavaUtilComparator_thenComparingLongWithJavaUtilFunctionToLongFunction_(self, arg0);
}

- (id<JavaUtilComparator>)thenComparingDoubleWithJavaUtilFunctionToDoubleFunction:(id<JavaUtilFunctionToDoubleFunction>)arg0 {
  return JavaUtilComparator_thenComparingDoubleWithJavaUtilFunctionToDoubleFunction_(self, arg0);
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x0, -1, -1, -1, -1, -1, -1 },
    { NULL, "I", 0x1, 0, 1, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(init);
  methods[1].selector = @selector(compareWithId:withId:);
  #pragma clang diagnostic pop
  static const void *ptrTable[] = { "compare", "LOrgApacheLuceneSearchTopTermsRewrite_ScoreTerm;LOrgApacheLuceneSearchTopTermsRewrite_ScoreTerm;", "LOrgApacheLuceneSearchTopTermsRewrite;", "Ljava/lang/Object;Ljava/util/Comparator<Lorg/apache/lucene/search/TopTermsRewrite$ScoreTerm;>;" };
  static const J2ObjcClassInfo _OrgApacheLuceneSearchTopTermsRewrite_2 = { "", "org.apache.lucene.search", ptrTable, methods, NULL, 7, 0x8018, 2, 0, 2, -1, -1, 3, -1 };
  return &_OrgApacheLuceneSearchTopTermsRewrite_2;
}

@end

void OrgApacheLuceneSearchTopTermsRewrite_2_init(OrgApacheLuceneSearchTopTermsRewrite_2 *self) {
  NSObject_init(self);
}

OrgApacheLuceneSearchTopTermsRewrite_2 *new_OrgApacheLuceneSearchTopTermsRewrite_2_init() {
  J2OBJC_NEW_IMPL(OrgApacheLuceneSearchTopTermsRewrite_2, init)
}

OrgApacheLuceneSearchTopTermsRewrite_2 *create_OrgApacheLuceneSearchTopTermsRewrite_2_init() {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneSearchTopTermsRewrite_2, init)
}

@implementation OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm

- (instancetype)initWithOrgApacheLuceneIndexTermContext:(OrgApacheLuceneIndexTermContext *)termState {
  OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm_initWithOrgApacheLuceneIndexTermContext_(self, termState);
  return self;
}

- (jint)compareToWithId:(OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *)other {
  cast_chk(other, [OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm class]);
  if (self->boost_ == ((OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *) nil_chk(other))->boost_) return [((OrgApacheLuceneUtilBytesRef *) nil_chk([((OrgApacheLuceneUtilBytesRefBuilder *) nil_chk(other->bytes_)) get])) compareToWithId:[self->bytes_ get]];
  else return JavaLangFloat_compareWithFloat_withFloat_(self->boost_, other->boost_);
}

- (void)dealloc {
  RELEASE_(bytes_);
  RELEASE_(termState_);
  [super dealloc];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x1, -1, 0, -1, -1, -1, -1 },
    { NULL, "I", 0x1, 1, 2, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(initWithOrgApacheLuceneIndexTermContext:);
  methods[1].selector = @selector(compareToWithId:);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "bytes_", "LOrgApacheLuceneUtilBytesRefBuilder;", .constantValue.asLong = 0, 0x11, -1, -1, -1, -1 },
    { "boost_", "F", .constantValue.asLong = 0, 0x1, -1, -1, -1, -1 },
    { "termState_", "LOrgApacheLuceneIndexTermContext;", .constantValue.asLong = 0, 0x11, -1, -1, -1, -1 },
  };
  static const void *ptrTable[] = { "LOrgApacheLuceneIndexTermContext;", "compareTo", "LOrgApacheLuceneSearchTopTermsRewrite_ScoreTerm;", "LOrgApacheLuceneSearchTopTermsRewrite;", "Ljava/lang/Object;Ljava/lang/Comparable<Lorg/apache/lucene/search/TopTermsRewrite$ScoreTerm;>;" };
  static const J2ObjcClassInfo _OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm = { "ScoreTerm", "org.apache.lucene.search", ptrTable, methods, fields, 7, 0x18, 2, 3, 3, -1, -1, 4, -1 };
  return &_OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm;
}

@end

void OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm_initWithOrgApacheLuceneIndexTermContext_(OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *self, OrgApacheLuceneIndexTermContext *termState) {
  NSObject_init(self);
  JreStrongAssignAndConsume(&self->bytes_, new_OrgApacheLuceneUtilBytesRefBuilder_init());
  JreStrongAssign(&self->termState_, termState);
}

OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *new_OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm_initWithOrgApacheLuceneIndexTermContext_(OrgApacheLuceneIndexTermContext *termState) {
  J2OBJC_NEW_IMPL(OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm, initWithOrgApacheLuceneIndexTermContext_, termState)
}

OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm *create_OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm_initWithOrgApacheLuceneIndexTermContext_(OrgApacheLuceneIndexTermContext *termState) {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm, initWithOrgApacheLuceneIndexTermContext_, termState)
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneSearchTopTermsRewrite_ScoreTerm)