text:
class RedirectPublisher
  def initialize(publishing_api = PUBLISHING_API)
    @publishing_api = publishing_api
  end

  def process(content_id:, old_path:, new_path:)
    data = {
      schema_name: "redirect",
      document_type: "redirect",
      base_path: old_path,
      update_type: "major",
      publishing_app: "service-manual-publisher",
      redirects: [
        {
          path: old_path,
          type: "exact",
          destination: new_path,
        },
      ],
    }
    @publishing_api.put_content(content_id, data)
    @publishing_api.publish(content_id)
  end
end


text:
@interface GPUImageTextureInput : GPUImageOutput
{
    CGSize textureSize;
}

// Initialization and teardown
- (id)initWithTexture:(GLuint)newInputTexture size:(CGSize)newTextureSize;

// Image rendering
- (void)processTextureWithFrameTime:(CMTime)frameTime;

@end

redpajama_set_name: RedPajamaGithub


text:
package org.gw4e.eclipse.wizard.convert;

import java.io.IOException;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.ui.IWorkbenchWindow;
import org.gw4e.eclipse.facade.GraphWalkerFacade;
import org.gw4e.eclipse.facade.TestResourceGeneration;

/**
 * Post processing for Java file
 *
 */
public class JavaTestBasedPostConversionImpl extends AbstractPostConversion {
	List<IFile> implementations =  null;

	/**
	 * @param context
	 */
	public JavaTestBasedPostConversionImpl(ResourceContext context) {
		super(context);
	}

	/* (non-Javadoc)
	 * @see org.gw4e.eclipse.wizard.convert.AbstractPostConversion#convert(org.eclipse.core.runtime.IProgressMonitor)
	 */
	public List<IFile> convert(IWorkbenchWindow ww,IProgressMonitor monitor) throws IOException, CoreException, InterruptedException   {
		TestResourceGeneration trg = new TestResourceGeneration(context);
		return GraphWalkerFacade.generateFromFile(ww,trg,monitor);
	}

	/* (non-Javadoc)
	 * @see org.gw4e.eclipse.wizard.convert.AbstractPostConversion#afterConversion(org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public void afterConversion(IProgressMonitor monitor) {
		SubMonitor subMonitor = SubMonitor.convert(monitor, 1);
		subMonitor.split(1);
		subMonitor.done();
	}

}


text:
export const SET_SIGNUP_AND_EVENT = 'editSignup/SET_SIGNUP_AND_EVENT';
export const SET_SIGNUP = 'editSignup/SET_SIGNUP';
export const SET_EVENT = 'editSignup/SET_EVENT';
export const SET_LOADING = 'editSignup/SET_LOADING';
export const SET_ERROR = 'editSignup/SET_ERROR';
export const SET_DELETED = 'editSignup/SET_DELETED';


text:
use debugger::Debugger;
use egui_glow::EguiGlow;
use glutin::{
    event::{ElementState, ModifiersState, VirtualKeyCode, WindowEvent},
    PossiblyCurrent, WindowedContext,
};
use pyrite::GbaHandle;

use crate::pyrite_window::PyriteWindow;

pub struct DebuggerWindow {
    context: Option<WindowedContext<PossiblyCurrent>>,
    gl: glow::Context,
    modifiers: ModifiersState,
    wants_close: bool,
    gui: EguiGlow,
    repaint: bool,
    debugger_state: Debugger,
    gba: GbaHandle,
}

impl DebuggerWindow {
    pub fn new(
        gba: GbaHandle,
        context: WindowedContext<PossiblyCurrent>,
    ) -> anyhow::Result<DebuggerWindow> {
        let gl = unsafe {
            glow::Context::from_loader_function(|s| context.get_proc_address(s) as *const _)
        };
        let gui = EguiGlow::new(context.window(), &gl);

        Ok(DebuggerWindow {
            context: Some(context),
            gl,
            modifiers: ModifiersState::default(),
            wants_close: false,
            gui,
            repaint: false,
            debugger_state: Debugger::default(),
            gba,
        })
    }

    fn on_keyboard_input(&mut self, input: glutin::event::KeyboardInput) {
        if let Some(VirtualKeyCode::Escape) = input.virtual_keycode {
            if input.state == ElementState::Pressed {
                self.wants_close = true
            }
        }
    }

    pub fn wants_close(&self) -> bool {
        self.wants_close
    }
}

impl Drop for DebuggerWindow {
    fn drop(&mut self) {
        self.debugger_state.destroy(&self.gba);
        if self.try_swap_context() {
            self.gui.destroy(&self.gl);
            log::debug!("destroyed debugger UI");
        } else {
            log::debug!("failed to swap to debugger window context for cleanup");
        }
    }
}

impl PyriteWindow for DebuggerWindow {
    fn on_window_event(&mut self, event: WindowEvent) {
        if self.gui.on_event(&event) {
            return;
        }

        match event {
            WindowEvent::KeyboardInput { input, .. } => self.on_keyboard_input(input),
            WindowEvent::Resized(..) => self.repaint = true,
            _ => (),
        }
    }

    fn render(&mut self) {
        let window = self.context.as_ref().expect("no context").window();
        if self.repaint {
            self.gui.paint(window, &self.gl);
            self.repaint = false;
        }
    }

    fn update(&mut self) -> bool {
        let window = self.context.as_ref().expect("no context").window();
        self.repaint = self.gui.run(window, |gui_context| {
            self.debugger_state.render(gui_context, &self.gba);
        });
        self.repaint
    }

    fn context_mut_opt(&mut self) -> &mut Option<glutin::WindowedContext<glutin::PossiblyCurrent>> {
        &mut self.context
    }

    fn context_opt(&self) -> &Option<glutin::WindowedContext<glutin::PossiblyCurrent>> {
        &self.context
    }

    fn modifiers_mut(&mut self) -> &mut ModifiersState {
        &mut self.modifiers
    }

    fn gl(&self) -> &glow::Context {
        &self.gl
    }
}


text:
module Grape
  module Exceptions
    class MissingGroupType < Base
      def initialize
        super(message: compose_message(:missing_group_type))
      end
    end
  end
end

Grape::Exceptions::MissingGroupTypeError = Class.new(Grape::Exceptions::MissingGroupType) do
  def initialize(*)
    super
    warn '[DEPRECATION] `Grape::Exceptions::MissingGroupTypeError` is deprecated. Use `Grape::Exceptions::MissingGroupType` instead.'
  end
end


text:
require 'spec_helper'

# these tests fail intermittently in evergreen
describe Mongo::Server::Connection do
  retry_test

  let(:address) do
    Mongo::Address.new(SpecConfig.instance.addresses.first)
  end

  let(:monitoring) do
    Mongo::Monitoring.new(monitoring: false)
  end

  let(:listeners) do
    Mongo::Event::Listeners.new
  end

  let(:app_metadata) do
    Mongo::Server::AppMetadata.new(SpecConfig.instance.test_options)
  end

  let(:cluster) do
    double('cluster').tap do |cl|
      allow(cl).to receive(:topology).and_return(topology)
      allow(cl).to receive(:app_metadata).and_return(app_metadata)
      allow(cl).to receive(:options).and_return({})
      allow(cl).to receive(:cluster_time).and_return(nil)
      allow(cl).to receive(:update_cluster_time)
      allow(cl).to receive(:run_sdam_flow)
      pool = double('pool')
      allow(pool).to receive(:disconnect!)
      allow(cl).to receive(:pool).and_return(pool)
    end
  end

  declare_topology_double

  let(:server) do
    register_server(
      Mongo::Server.new(address, cluster, monitoring, listeners,
        SpecConfig.instance.test_options.merge(monitoring_io: false))
    )
  end

  before(:all) do
    ClientRegistry.instance.close_all_clients
  end

  describe '#auth_mechanism' do
    require_no_external_user

    let(:connection) do
      described_class.new(server, server.options)
    end

    context 'when the hello response includes saslSupportedMechs' do
      min_server_fcv '4.0'

      let(:server_options) do
        SpecConfig.instance.test_options.merge(
          user: SpecConfig.instance.test_user.name,
          password: SpecConfig.instance.test_user.password,
          auth_source: 'admin',
        )
      end

      let(:app_metadata) do
        Mongo::Server::AppMetadata.new(server_options)
      end

      before do
        client = authorized_client.with(database: 'admin')
        info = client.database.users.info(SpecConfig.instance.test_user.name)
        expect(info.length).to eq(1)
        # this before block may have made 2 or 3 clients
        ClientRegistry.instance.close_all_clients
      end

      it 'uses scram256' do
        connection
        RSpec::Mocks.with_temporary_scope do
          pending_conn = nil
          Mongo::Server::PendingConnection.should receive(:new).and_wrap_original do |m, *args|
            pending_conn = m.call(*args)
          end
          connection.connect!
          expect(pending_conn.send(:default_mechanism)).to eq(:scram256)
        end
      end
    end

    context 'when the hello response indicates the auth mechanism is :scram' do
      require_no_external_user

      let(:features) do
        Mongo::Server::Description::Features.new(0..7)
      end

      it 'uses scram' do
        connection
        RSpec::Mocks.with_temporary_scope do
          expect(Mongo::Server::Description::Features).to receive(:new).and_return(features)

          pending_conn = nil
          Mongo::Server::PendingConnection.should receive(:new).and_wrap_original do |m, *args|
            pending_conn = m.call(*args)
          end
          connection.connect!
          expect(pending_conn.send(:default_mechanism)).to eq(:scram)
        end
      end
    end

    context 'when the hello response indicates the auth mechanism is :mongodb_cr' do
      let(:features) do
        Mongo::Server::Description::Features.new(0..2)
      end

      it 'uses mongodb_cr' do
        connection
        RSpec::Mocks.with_temporary_scope do
          expect(Mongo::Server::Description::Features).to receive(:new).and_return(features)

          pending_conn = nil
          Mongo::Server::PendingConnection.should receive(:new).and_wrap_original do |m, *args|
            pending_conn = m.call(*args)
          end
          connection.connect!
          expect(pending_conn.send(:default_mechanism)).to eq(:mongodb_cr)
        end
      end
    end
  end
end


text:
#pragma once

#include <stdint.h>

#include "py/obj.h"
#include "cyw43.h"

typedef struct {
    mp_obj_base_t base;
    mp_obj_t results;
    bool done;
} wifi_scannednetworks_obj_t;

void wifi_scannednetworks_deinit(wifi_scannednetworks_obj_t *self);
void wifi_scannednetworks_start_scan(wifi_scannednetworks_obj_t *self);


text:
package org.springframework.cloud.kubernetes.fabric8.configmap.polling.reload;

import java.io.InputStream;
import java.time.Duration;
import java.util.Map;
import java.util.Objects;

import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.networking.v1.Ingress;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.k3s.K3sContainer;
import reactor.netty.http.client.HttpClient;
import reactor.util.retry.Retry;
import reactor.util.retry.RetryBackoffSpec;

import org.springframework.cloud.kubernetes.integration.tests.commons.Commons;
import org.springframework.cloud.kubernetes.integration.tests.commons.Fabric8Utils;
import org.springframework.cloud.kubernetes.integration.tests.commons.K8SUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;

import static org.awaitility.Awaitility.await;

/**
 * @author wind57
 */
class ConfigMapPollingReloadIT {

	private static final String IMAGE_NAME = "spring-cloud-kubernetes-fabric8-client-configmap-polling-reload";

	private static final String NAMESPACE = "default";

	private static KubernetesClient client;

	private static String deploymentName;

	private static String serviceName;

	private static String ingressName;

	private static String configMapName;

	private static final K3sContainer K3S = Commons.container();

	@BeforeAll
	static void beforeAll() throws Exception {
		K3S.start();
		Commons.validateImage(IMAGE_NAME, K3S);
		Commons.loadSpringCloudKubernetesImage(IMAGE_NAME, K3S);
		Config config = Config.fromKubeconfig(K3S.getKubeConfigYaml());
		client = new DefaultKubernetesClient(config);
		Fabric8Utils.setUp(client, NAMESPACE);
		deployManifests();
	}

	@AfterAll
	static void after() throws Exception {
		deleteManifests();
		Commons.cleanUp(IMAGE_NAME, K3S);
	}

	@SuppressWarnings({ "raw", "unchecked" })
	@Test
	void test() {
		WebClient webClient = builder().baseUrl("localhost/key").build();
		String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec())
				.block();

		// we first read the initial value from the configmap
		Assertions.assertEquals("initial", result);

		// then deploy a new version of configmap
		// since we poll and have reload in place, the new property must be visible
		ConfigMap map = new ConfigMapBuilder()
				.withMetadata(new ObjectMetaBuilder().withNamespace("default").withName("poll-reload").build())
				.withData(Map.of("application.properties", "from.properties.key=after-change")).build();

		// the weird cast comes from :
		// https://github.com/fabric8io/kubernetes-client/issues/2445
		((HasMetadataOperation) client.configMaps().inNamespace("default").withName("poll-reload"))
				.createOrReplace(map);

		await().timeout(Duration.ofSeconds(30)).until(() -> webClient.method(HttpMethod.GET).retrieve()
				.bodyToMono(String.class).retryWhen(retrySpec()).block().equals("after-change"));

	}

	private static void deleteManifests() {

		try {

			client.configMaps().inNamespace(NAMESPACE).withName(configMapName).delete();
			client.apps().deployments().inNamespace(NAMESPACE).withName(deploymentName).delete();
			client.services().inNamespace(NAMESPACE).withName(serviceName).delete();
			client.network().v1().ingresses().inNamespace(NAMESPACE).withName(ingressName).delete();

		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	private static void deployManifests() {

		try {

			ConfigMap configMap = client.configMaps().load(getConfigMap()).get();
			configMapName = configMap.getMetadata().getName();
			client.configMaps().create(configMap);

			Deployment deployment = client.apps().deployments().load(getDeployment()).get();

			String version = K8SUtils.getPomVersion();
			String currentImage = deployment.getSpec().getTemplate().getSpec().getContainers().get(0).getImage();
			deployment.getSpec().getTemplate().getSpec().getContainers().get(0).setImage(currentImage + ":" + version);

			client.apps().deployments().inNamespace(NAMESPACE).create(deployment);
			deploymentName = deployment.getMetadata().getName();

			Service service = client.services().load(getService()).get();
			serviceName = service.getMetadata().getName();
			client.services().inNamespace(NAMESPACE).create(service);

			Ingress ingress = client.network().v1().ingresses().load(getIngress()).get();
			ingressName = ingress.getMetadata().getName();
			client.network().v1().ingresses().inNamespace(NAMESPACE).create(ingress);

			Fabric8Utils.waitForDeployment(client,
					"spring-cloud-kubernetes-fabric8-client-configmap-deployment-polling-reload", NAMESPACE, 2, 600);

		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	private static InputStream getService() {
		return Fabric8Utils.inputStream("service.yaml");
	}

	private static InputStream getDeployment() {
		return Fabric8Utils.inputStream("deployment.yaml");
	}

	private static InputStream getIngress() {
		return Fabric8Utils.inputStream("ingress.yaml");
	}

	private static InputStream getConfigMap() {
		return Fabric8Utils.inputStream("configmap.yaml");
	}

	private WebClient.Builder builder() {
		return WebClient.builder().clientConnector(new ReactorClientHttpConnector(HttpClient.create()));
	}

	private RetryBackoffSpec retrySpec() {
		return Retry.fixedDelay(15, Duration.ofSeconds(1)).filter(Objects::nonNull);
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ivy-module version="2.0" xmlns:m="http://ant.apache.org/ivy/maven">
  <info organisation="${ivy.artifact.group}" module="${ivy.artifact.id}" revision="${project.revision}" />

  <configurations>
    <conf name="default" />
    <conf name="zip" />
    <conf name="test" visibility="private" />
    <conf name="provided" />
    <conf name="client" />
    <conf name="pmr" />
  </configurations>

  <publications>
    <artifact name="${ivy.artifact.id}" type="jar" conf="default" />
    <artifact name="${package.id}" type="zip" conf="zip" />
  </publications>

  <dependencies defaultconf="default->default">
    <dependency conf="provided->default" org="pentaho" name="pentaho-hadoop-shims-api" rev="${project.revision}" changing="true"/>
    <dependency conf="provided->default" org="pentaho-kettle" name="kettle-core" rev="${dependency.kettle.revision}" changing="true"/>
    <dependency conf="provided->default" org="pentaho-kettle" name="kettle-engine" rev="${dependency.kettle.revision}" changing="true"/>

    <dependency org="pentaho" name="pentaho-hdfs-vfs" rev="${dependency.pentaho-hdfs-vfs.revision}" transitive="false" changing="true"/>
    <dependency org="pentaho" name="pentaho-hadoop-snappy" rev="${dependency.pentaho-hadoop-snappy.revision}" changing="true"/>

    <dependency conf="provided->default" org="com.thoughtworks.xstream" name="xstream" rev="${dependency.xstream.revision}" transitive="false"/>
    <dependency conf="provided->default" org="log4j" name="log4j" rev="1.2.14" />
    <dependency conf="provided->default" org="commons-lang" name="commons-lang" rev="${dependency.commons-lang.revision}" transitive="false"/>

    <dependency conf="test->default" org="junit" name="junit" rev="4.5"/>
    <dependency conf="test->default" org="org.safehaus.jug" name="jug-lgpl" rev="2.0.0" />
    <dependency conf="test->default" org="pentaho" name="pentaho-hadoop-shims-api-test" rev="${project.revision}" changing="true"/>

    <dependency conf="client->default" org="net.java.dev.jets3t" name="jets3t" rev="${dependency.jets3t.revision}" transitive="false" />
    <dependency conf="client->default" org="commons-net" name="commons-net" rev="${dependency.commons-net.revision}" transitive="false" />

    <dependency conf="client->default" org="org.apache.hadoop" name="hadoop-core" rev="${dependency.hadoop.revision}" >
      <exclude name="hadoop-core" />
      <exclude name="a.*" matcher="regexp" />
      <exclude name="commons-beanutils.*" matcher="regexp" />
      <exclude name="commons-collections" />
      <exclude name="commons-digester" />
      <exclude name="commons-io" />
      <exclude name="commons-lang" />
      <exclude name="commons-math" />
      <exclude name="core" />
      <exclude name="ja.*" matcher="regexp" />
      <exclude name="jersey.*" matcher="regexp" />
      <exclude name="jettison" />
      <exclude name="jetty.*" matcher="regexp" />
      <exclude name="js.*" matcher="regexp" />
      <exclude name="junit" />
      <exclude name="s.*" matcher="regexp" />
    </dependency>

    <!-- Resolving HDP Pig is messy, the core JAR is provided, some other Pig dependencies need to be added or excluded -->
    <dependency conf="pmr->default" org="org.apache.pig" name="pig" rev="${dependency.pig.revision}" transitive="true">
      <exclude org="com.google.guava" />
      <exclude org="jline" />
      <exclude org="org.apache.pig" />
      <exclude org="org.codehaus.jackson" />
      <exclude org="org.slf4j" />
    </dependency>
    <dependency conf="pmr->default" org="com.google.protobuf" name="protobuf-java" rev="${protobuf-java.version}" transitive="false" />

    <dependency org="org.apache.thrift" name="libthrift" rev="${dependency.thrift.revision}" transitive="false" />
    <dependency org="org.apache.thrift" name="libfb303" rev="${dependency.thrift.revision}" transitive="false" />

    <!-- Exclude log4j from default libraries - it's brought in transitively through many of the Hadoop dependencies and should not be included -->
    <exclude org="log4j" module="log4j" conf="default" />
    <!-- Exclude antlr. Hive brings in a version that's not compatible with Pig. -->
    <exclude org="org.antlr" conf="default" />

    <exclude org="junit" conf="default,zip,client,provided,pmr"/>
  </dependencies>
</ivy-module>


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-team-list',
  templateUrl: './team-list.component.html',
  styleUrls: ['./team-list.component.css']
})
export class TeamListComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
package org.projectfloodlight.openflow.protocol.ver10;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
import java.util.Arrays;

class OFPacketInVer10 implements OFPacketIn {
    private static final Logger logger = LoggerFactory.getLogger(OFPacketInVer10.class);
    // version: 1.0
    final static byte WIRE_VERSION = 1;
    final static int MINIMUM_LENGTH = 18;

        private final static long DEFAULT_XID = 0x0L;
        private final static OFBufferId DEFAULT_BUFFER_ID = OFBufferId.NO_BUFFER;
        private final static int DEFAULT_TOTAL_LEN = 0x0;
        private final static OFPort DEFAULT_IN_PORT = OFPort.ANY;
        private final static byte[] DEFAULT_DATA = new byte[0];

    // OF message fields
    private final long xid;
    private final OFBufferId bufferId;
    private final int totalLen;
    private final OFPort inPort;
    private final OFPacketInReason reason;
    private final byte[] data;
//

    // package private constructor - used by readers, builders, and factory
    OFPacketInVer10(long xid, OFBufferId bufferId, int totalLen, OFPort inPort, OFPacketInReason reason, byte[] data) {
        if(bufferId == null) {
            throw new NullPointerException("OFPacketInVer10: property bufferId cannot be null");
        }
        if(inPort == null) {
            throw new NullPointerException("OFPacketInVer10: property inPort cannot be null");
        }
        if(reason == null) {
            throw new NullPointerException("OFPacketInVer10: property reason cannot be null");
        }
        if(data == null) {
            throw new NullPointerException("OFPacketInVer10: property data cannot be null");
        }
        this.xid = xid;
        this.bufferId = bufferId;
        this.totalLen = totalLen;
        this.inPort = inPort;
        this.reason = reason;
        this.data = data;
    }

    // Accessors for OF message fields
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_10;
    }

    @Override
    public OFType getType() {
        return OFType.PACKET_IN;
    }

    @Override
    public long getXid() {
        return xid;
    }

    @Override
    public OFBufferId getBufferId() {
        return bufferId;
    }

    @Override
    public int getTotalLen() {
        return totalLen;
    }

    @Override
    public OFPacketInReason getReason() {
        return reason;
    }

    @Override
    public TableId getTableId()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property tableId not supported in version 1.0");
    }

    @Override
    public U64 getCookie()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property cookie not supported in version 1.0");
    }

    @Override
    public Match getMatch()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property match not supported in version 1.0");
    }

    @Override
    public byte[] getData() {
        return data;
    }

    @Override
    public OFPort getInPort() {
        return inPort;
    }

    @Override
    public OFPort getInPhyPort()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property inPhyPort not supported in version 1.0");
    }

    public OFPacketIn.Builder createBuilder() {
        return new BuilderWithParent(this);
    }

    static class BuilderWithParent implements OFPacketIn.Builder {
        final OFPacketInVer10 parentMessage;

        // OF message fields
        private boolean xidSet;
        private long xid;
        private boolean bufferIdSet;
        private OFBufferId bufferId;
        private boolean totalLenSet;
        private int totalLen;
        private boolean inPortSet;
        private OFPort inPort;
        private boolean reasonSet;
        private OFPacketInReason reason;
        private boolean dataSet;
        private byte[] data;

        BuilderWithParent(OFPacketInVer10 parentMessage) {
            this.parentMessage = parentMessage;
        }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_10;
    }

    @Override
    public OFType getType() {
        return OFType.PACKET_IN;
    }

    @Override
    public long getXid() {
        return xid;
    }

    @Override
    public OFPacketIn.Builder setXid(long xid) {
        this.xid = xid;
        this.xidSet = true;
        return this;
    }
    @Override
    public OFBufferId getBufferId() {
        return bufferId;
    }

    @Override
    public OFPacketIn.Builder setBufferId(OFBufferId bufferId) {
        this.bufferId = bufferId;
        this.bufferIdSet = true;
        return this;
    }
    @Override
    public int getTotalLen() {
        return totalLen;
    }

    @Override
    public OFPacketIn.Builder setTotalLen(int totalLen) {
        this.totalLen = totalLen;
        this.totalLenSet = true;
        return this;
    }
    @Override
    public OFPacketInReason getReason() {
        return reason;
    }

    @Override
    public OFPacketIn.Builder setReason(OFPacketInReason reason) {
        this.reason = reason;
        this.reasonSet = true;
        return this;
    }
    @Override
    public TableId getTableId()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property tableId not supported in version 1.0");
    }

    @Override
    public OFPacketIn.Builder setTableId(TableId tableId) throws UnsupportedOperationException {
            throw new UnsupportedOperationException("Property tableId not supported in version 1.0");
    }
    @Override
    public U64 getCookie()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property cookie not supported in version 1.0");
    }

    @Override
    public OFPacketIn.Builder setCookie(U64 cookie) throws UnsupportedOperationException {
            throw new UnsupportedOperationException("Property cookie not supported in version 1.0");
    }
    @Override
    public Match getMatch()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property match not supported in version 1.0");
    }

    @Override
    public OFPacketIn.Builder setMatch(Match match) throws UnsupportedOperationException {
            throw new UnsupportedOperationException("Property match not supported in version 1.0");
    }
    @Override
    public byte[] getData() {
        return data;
    }

    @Override
    public OFPacketIn.Builder setData(byte[] data) {
        this.data = data;
        this.dataSet = true;
        return this;
    }
    @Override
    public OFPort getInPort() {
        return inPort;
    }

    @Override
    public OFPacketIn.Builder setInPort(OFPort inPort) {
        this.inPort = inPort;
        this.inPortSet = true;
        return this;
    }
    @Override
    public OFPort getInPhyPort()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property inPhyPort not supported in version 1.0");
    }

    @Override
    public OFPacketIn.Builder setInPhyPort(OFPort inPhyPort) throws UnsupportedOperationException {
            throw new UnsupportedOperationException("Property inPhyPort not supported in version 1.0");
    }

        @Override
        public OFPacketIn build() {
                long xid = this.xidSet ? this.xid : parentMessage.xid;
                OFBufferId bufferId = this.bufferIdSet ? this.bufferId : parentMessage.bufferId;
                if(bufferId == null)
                    throw new NullPointerException("Property bufferId must not be null");
                int totalLen = this.totalLenSet ? this.totalLen : parentMessage.totalLen;
                OFPort inPort = this.inPortSet ? this.inPort : parentMessage.inPort;
                if(inPort == null)
                    throw new NullPointerException("Property inPort must not be null");
                OFPacketInReason reason = this.reasonSet ? this.reason : parentMessage.reason;
                if(reason == null)
                    throw new NullPointerException("Property reason must not be null");
                byte[] data = this.dataSet ? this.data : parentMessage.data;
                if(data == null)
                    throw new NullPointerException("Property data must not be null");

                //
                return new OFPacketInVer10(
                    xid,
                    bufferId,
                    totalLen,
                    inPort,
                    reason,
                    data
                );
        }

    }

    static class Builder implements OFPacketIn.Builder {
        // OF message fields
        private boolean xidSet;
        private long xid;
        private boolean bufferIdSet;
        private OFBufferId bufferId;
        private boolean totalLenSet;
        private int totalLen;
        private boolean inPortSet;
        private OFPort inPort;
        private boolean reasonSet;
        private OFPacketInReason reason;
        private boolean dataSet;
        private byte[] data;

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_10;
    }

    @Override
    public OFType getType() {
        return OFType.PACKET_IN;
    }

    @Override
    public long getXid() {
        return xid;
    }

    @Override
    public OFPacketIn.Builder setXid(long xid) {
        this.xid = xid;
        this.xidSet = true;
        return this;
    }
    @Override
    public OFBufferId getBufferId() {
        return bufferId;
    }

    @Override
    public OFPacketIn.Builder setBufferId(OFBufferId bufferId) {
        this.bufferId = bufferId;
        this.bufferIdSet = true;
        return this;
    }
    @Override
    public int getTotalLen() {
        return totalLen;
    }

    @Override
    public OFPacketIn.Builder setTotalLen(int totalLen) {
        this.totalLen = totalLen;
        this.totalLenSet = true;
        return this;
    }
    @Override
    public OFPacketInReason getReason() {
        return reason;
    }

    @Override
    public OFPacketIn.Builder setReason(OFPacketInReason reason) {
        this.reason = reason;
        this.reasonSet = true;
        return this;
    }
    @Override
    public TableId getTableId()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property tableId not supported in version 1.0");
    }

    @Override
    public OFPacketIn.Builder setTableId(TableId tableId) throws UnsupportedOperationException {
            throw new UnsupportedOperationException("Property tableId not supported in version 1.0");
    }
    @Override
    public U64 getCookie()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property cookie not supported in version 1.0");
    }

    @Override
    public OFPacketIn.Builder setCookie(U64 cookie) throws UnsupportedOperationException {
            throw new UnsupportedOperationException("Property cookie not supported in version 1.0");
    }
    @Override
    public Match getMatch()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property match not supported in version 1.0");
    }

    @Override
    public OFPacketIn.Builder setMatch(Match match) throws UnsupportedOperationException {
            throw new UnsupportedOperationException("Property match not supported in version 1.0");
    }
    @Override
    public byte[] getData() {
        return data;
    }

    @Override
    public OFPacketIn.Builder setData(byte[] data) {
        this.data = data;
        this.dataSet = true;
        return this;
    }
    @Override
    public OFPort getInPort() {
        return inPort;
    }

    @Override
    public OFPacketIn.Builder setInPort(OFPort inPort) {
        this.inPort = inPort;
        this.inPortSet = true;
        return this;
    }
    @Override
    public OFPort getInPhyPort()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property inPhyPort not supported in version 1.0");
    }

    @Override
    public OFPacketIn.Builder setInPhyPort(OFPort inPhyPort) throws UnsupportedOperationException {
            throw new UnsupportedOperationException("Property inPhyPort not supported in version 1.0");
    }
//
        @Override
        public OFPacketIn build() {
            long xid = this.xidSet ? this.xid : DEFAULT_XID;
            OFBufferId bufferId = this.bufferIdSet ? this.bufferId : DEFAULT_BUFFER_ID;
            if(bufferId == null)
                throw new NullPointerException("Property bufferId must not be null");
            int totalLen = this.totalLenSet ? this.totalLen : DEFAULT_TOTAL_LEN;
            OFPort inPort = this.inPortSet ? this.inPort : DEFAULT_IN_PORT;
            if(inPort == null)
                throw new NullPointerException("Property inPort must not be null");
            if(!this.reasonSet)
                throw new IllegalStateException("Property reason doesn't have default value -- must be set");
            if(reason == null)
                throw new NullPointerException("Property reason must not be null");
            byte[] data = this.dataSet ? this.data : DEFAULT_DATA;
            if(data == null)
                throw new NullPointerException("Property data must not be null");

            return new OFPacketInVer10(
                    xid,
                    bufferId,
                    totalLen,
                    inPort,
                    reason,
                    data
                );
        }

    }

    final static Reader READER = new Reader();
    static class Reader implements OFMessageReader<OFPacketIn> {
        @Override
        public OFPacketIn readFrom(ByteBuf bb) throws OFParseError {
            int start = bb.readerIndex();
            // fixed value property version == 1
            byte version = bb.readByte();
            if(version != (byte) 0x1)
                throw new OFParseError("Wrong version: Expected=OFVersion.OF_10(1), got="+version);
            // fixed value property type == 10
            byte type = bb.readByte();
            if(type != (byte) 0xa)
                throw new OFParseError("Wrong type: Expected=OFType.PACKET_IN(10), got="+type);
            int length = U16.f(bb.readShort());
            if(length < MINIMUM_LENGTH)
                throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length);
            if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
                // Buffer does not have all data yet
                bb.readerIndex(start);
                return null;
            }
            if(logger.isTraceEnabled())
                logger.trace("readFrom - length={}", length);
            long xid = U32.f(bb.readInt());
            OFBufferId bufferId = OFBufferId.of(bb.readInt());
            int totalLen = U16.f(bb.readShort());
            OFPort inPort = OFPort.read2Bytes(bb);
            OFPacketInReason reason = OFPacketInReasonSerializerVer10.readFrom(bb);
            // pad: 1 bytes
            bb.skipBytes(1);
            byte[] data = ChannelUtils.readBytes(bb, length - (bb.readerIndex() - start));

            OFPacketInVer10 packetInVer10 = new OFPacketInVer10(
                    xid,
                      bufferId,
                      totalLen,
                      inPort,
                      reason,
                      data
                    );
            if(logger.isTraceEnabled())
                logger.trace("readFrom - read={}", packetInVer10);
            return packetInVer10;
        }
    }

    public void putTo(PrimitiveSink sink) {
        FUNNEL.funnel(this, sink);
    }

    final static OFPacketInVer10Funnel FUNNEL = new OFPacketInVer10Funnel();
    static class OFPacketInVer10Funnel implements Funnel<OFPacketInVer10> {
        private static final long serialVersionUID = 1L;
        @Override
        public void funnel(OFPacketInVer10 message, PrimitiveSink sink) {
            // fixed value property version = 1
            sink.putByte((byte) 0x1);
            // fixed value property type = 10
            sink.putByte((byte) 0xa);
            // FIXME: skip funnel of length
            sink.putLong(message.xid);
            message.bufferId.putTo(sink);
            sink.putInt(message.totalLen);
            message.inPort.putTo(sink);
            OFPacketInReasonSerializerVer10.putTo(message.reason, sink);
            // skip pad (1 bytes)
            sink.putBytes(message.data);
        }
    }

    public void writeTo(ByteBuf bb) {
        WRITER.write(bb, this);
    }

    final static Writer WRITER = new Writer();
    static class Writer implements OFMessageWriter<OFPacketInVer10> {
        @Override
        public void write(ByteBuf bb, OFPacketInVer10 message) {
            int startIndex = bb.writerIndex();
            // fixed value property version = 1
            bb.writeByte((byte) 0x1);
            // fixed value property type = 10
            bb.writeByte((byte) 0xa);
            // length is length of variable message, will be updated at the end
            int lengthIndex = bb.writerIndex();
            bb.writeShort(U16.t(0));

            bb.writeInt(U32.t(message.xid));
            bb.writeInt(message.bufferId.getInt());
            bb.writeShort(U16.t(message.totalLen));
            message.inPort.write2Bytes(bb);
            OFPacketInReasonSerializerVer10.writeTo(bb, message.reason);
            // pad: 1 bytes
            bb.writeZero(1);
            bb.writeBytes(message.data);

            // update length field
            int length = bb.writerIndex() - startIndex;
            bb.setShort(lengthIndex, length);

        }
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFPacketInVer10(");
        b.append("xid=").append(xid);
        b.append(", ");
        b.append("bufferId=").append(bufferId);
        b.append(", ");
        b.append("totalLen=").append(totalLen);
        b.append(", ");
        b.append("inPort=").append(inPort);
        b.append(", ");
        b.append("reason=").append(reason);
        b.append(", ");
        b.append("data=").append(Arrays.toString(data));
        b.append(")");
        return b.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        OFPacketInVer10 other = (OFPacketInVer10) obj;

        if( xid != other.xid)
            return false;
        if (bufferId == null) {
            if (other.bufferId != null)
                return false;
        } else if (!bufferId.equals(other.bufferId))
            return false;
        if( totalLen != other.totalLen)
            return false;
        if (inPort == null) {
            if (other.inPort != null)
                return false;
        } else if (!inPort.equals(other.inPort))
            return false;
        if (reason == null) {
            if (other.reason != null)
                return false;
        } else if (!reason.equals(other.reason))
            return false;
        if (!Arrays.equals(data, other.data))
                return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;

        result = prime *  (int) (xid ^ (xid >>> 32));
        result = prime * result + ((bufferId == null) ? 0 : bufferId.hashCode());
        result = prime * result + totalLen;
        result = prime * result + ((inPort == null) ? 0 : inPort.hashCode());
        result = prime * result + ((reason == null) ? 0 : reason.hashCode());
        result = prime * result + Arrays.hashCode(data);
        return result;
    }

}


text:
@implementation JJJSONDataModel

+ (id)modelByContent:(NSDictionary *)content_ error:(NSError **)error_
{
    JJJSONDataModel *model = [[JJJSONDataModel alloc] init];
    model.jsonData = content_;

    return model;
}

@end


text:
namespace ClrPlus.Core.Sgml {
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Xml;

    /// <summary>
    ///     This class models an XML node, an array of elements in scope is maintained while parsing
    ///     for validation purposes, and these Node objects are reused to reduce object allocation,
    ///     hence the reset method.
    /// </summary>
    internal class Node {
        internal XmlNodeType NodeType;
        internal string Value;
        internal XmlSpace Space;
        internal string XmlLang;
        internal bool IsEmpty;
        internal string Name;
        internal ElementDecl DtdType; // the DTD type found via validation
        internal State CurrentState;
        internal bool Simulated; // tag was injected into result stream.
        private HWStack attributes = new HWStack(10);

        /// <summary>
        ///     Attribute objects are reused during parsing to reduce memory allocations,
        ///     hence the Reset method.
        /// </summary>
        public void Reset(string name, XmlNodeType nt, string value) {
            this.Value = value;
            this.Name = name;
            this.NodeType = nt;
            this.Space = XmlSpace.None;
            this.XmlLang = null;
            this.IsEmpty = true;
            this.attributes.Count = 0;
            this.DtdType = null;
        }

        public Attribute AddAttribute(string name, string value, char quotechar, bool caseInsensitive) {
            Attribute a;
            // check for duplicates!
            for (int i = 0, n = this.attributes.Count; i < n; i++) {
                a = (Attribute)this.attributes[i];
                if (string.Equals(a.Name, name, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) {
                    return null;
                }
            }
            // This code makes use of the high water mark for attribute objects,
            // and reuses exisint Attribute objects to avoid memory allocation.
            a = (Attribute)this.attributes.Push();
            if (a == null) {
                a = new Attribute();
                this.attributes[this.attributes.Count - 1] = a;
            }
            a.Reset(name, value, quotechar);
            return a;
        }

        [SuppressMessage("Microsoft.Performance", "CA1811", Justification = "Kept for potential future usage.")]
        public void RemoveAttribute(string name) {
            for (int i = 0, n = this.attributes.Count; i < n; i++) {
                var a = (Attribute)this.attributes[i];
                if (string.Equals(a.Name, name, StringComparison.OrdinalIgnoreCase)) {
                    this.attributes.RemoveAt(i);
                    return;
                }
            }
        }

        public void CopyAttributes(Node n) {
            for (int i = 0, len = n.attributes.Count; i < len; i++) {
                var a = (Attribute)n.attributes[i];
                var na = this.AddAttribute(a.Name, a.Value, a.QuoteChar, false);
                na.DtdType = a.DtdType;
            }
        }

        public int AttributeCount {
            get {
                return this.attributes.Count;
            }
        }

        public int GetAttribute(string name) {
            for (int i = 0, n = this.attributes.Count; i < n; i++) {
                var a = (Attribute)this.attributes[i];
                if (string.Equals(a.Name, name, StringComparison.OrdinalIgnoreCase)) {
                    return i;
                }
            }
            return -1;
        }

        public Attribute GetAttribute(int i) {
            if (i >= 0 && i < this.attributes.Count) {
                var a = (Attribute)this.attributes[i];
                return a;
            }
            return null;
        }
    }
}


text:
package com.smpa.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.smpa.common.DaoCtrl;
import com.smpa.constants.SmpaConstatants;
import com.smpa.model.Category;
import com.smpa.model.CategoryLebel;
import com.smpa.model.Chart;
import com.smpa.model.Graph;
import com.smpa.model.GraphResult;
import com.smpa.model.PredictionCriteria;
import com.smpa.model.Share;
import com.smpa.transformer.ShareTransformer;

public class PredictionService {

	private Connection con;

	public Graph getOrignalData(PredictionCriteria criteria) throws ClassNotFoundException, SQLException {
		Graph graph = new Graph();
		graph.setShowvalues(0);
		graph.setSeriesname("Orignal");
		graph.setRenderas("line");
		List<Share> currentShareData = getCurrentShareData(criteria);
		graph.setData(ShareTransformer.getGraphResult(currentShareData));
		return graph;
	}

	private List<Share> getCurrentShareData(PredictionCriteria criteria) throws ClassNotFoundException, SQLException {
		String sql = "SELECT * FROM SMPA.share WHERE companyId = "+criteria.getCompanyId()+" ORDER BY ts DESC "
				+ " LIMIT "+ criteria.getDayCount() + " ";
		con = DaoCtrl.getConnection();
		ResultSet rs = DaoCtrl.executeQuery(sql, con);
		List<Share> shareList = ShareTransformer.getShare(rs);
		rs.close();
		DaoCtrl.closeConnection(con);
		return shareList;
	}

	private List<Share> getHistoricalShareData(PredictionCriteria criteria) throws ClassNotFoundException, SQLException {
		String sql = "SELECT * FROM SMPA.share WHERE companyId = "+criteria.getCompanyId()+" ORDER BY ts DESC"
				+ " LIMIT "+(criteria.getDayCount() + SmpaConstatants.MOVING_AVG) + " ";
		con = DaoCtrl.getConnection();
		ResultSet rs = DaoCtrl.executeQuery(sql, con);
		List<Share> shareList = ShareTransformer.getShare(rs);
		rs.close();
		DaoCtrl.closeConnection(con);
		return shareList;
	}

	public Graph getPredictionData(PredictionCriteria criteria) throws ClassNotFoundException, SQLException {
		List<Share> historicalData = getHistoricalShareData(criteria);
		List<Share> currentData = getCurrentShareData(criteria);

		List<GraphResult> graphResultList = ShareTransformer.getGraphResult(historicalData, currentData);
		Graph graph = new Graph();
		graph.setShowvalues(0);
		graph.setSeriesname("Prediction");
		graph.setRenderas("line");
		graph.setData(graphResultList);
		return graph;
	}

	public List<Category> getCategoryList(PredictionCriteria criteria) {
		List<Category> categoryList = new ArrayList<Category>(1);
		List<CategoryLebel> categoryLebel = new ArrayList<CategoryLebel>(criteria.getDayCount());
		Category category = new Category();
		CategoryLebel lebel;
		for(int i=0; i<criteria.getDayCount(); i++) {
			lebel = new CategoryLebel();
			lebel.setLabel("Day "+Integer.toString(i+1));
			categoryLebel.add(lebel);
		}

		category.setCategory(categoryLebel);
		categoryList.add(category);
		return categoryList;
	}

	public Chart getChartDetails(PredictionCriteria criteria) {
		Chart chart = new Chart();
		chart.setCaption(criteria.getCompanyName() + " Actual & Targeted Shere Price");
		chart.setSubcaption("For "+criteria.getDayCount()+ " Days");
		chart.setNumberprefix("INR ");
		chart.setTheme("Carbon");
		chart.setXaxisname("Days");
		chart.setXaxisname("Amount in INR");
		return chart;
	}

	public List<Share> getShareDetailsList(PredictionCriteria criteria) throws ClassNotFoundException, SQLException {
		con = DaoCtrl.getConnection();
		String sql = "SELECT * FROM SMPA.SHARE WHERE companyId = "+criteria.getCompanyId()+" ORDER BY ts DESC LIMIT "+criteria.getDayCount();
		ResultSet rs = DaoCtrl.executeQuery(sql, con);
		List<Share> shareList = ShareTransformer.getShare(rs);
		rs.close();
		DaoCtrl.closeConnection(con);
		return shareList;
	}

}


text:
class CertValidator
  class NullOcspValidator
    attr_reader :certificate
    attr_reader :ca

    def initialize(_cert, _ca)
    end

    def available?
      false
    end

    def valid?
      raise OcspNotAvailableError.new
    end
  end
end


text:
package org.apache.flink.runtime.state;

import org.apache.flink.api.common.typeutils.CompatibilityResult;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerConfigSnapshot;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.runtime.state.heap.HeapPriorityQueueElement;
import org.apache.flink.util.CloseableIterator;
import org.apache.flink.util.MathUtils;
import org.apache.flink.util.TestLogger;

import org.junit.Assert;
import org.junit.Test;

import javax.annotation.Nonnull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Testbase for implementations of {@link InternalPriorityQueue}.
 */
public abstract class InternalPriorityQueueTestBase extends TestLogger {

	protected static final KeyGroupRange KEY_GROUP_RANGE = new KeyGroupRange(0, 2);
	protected static final KeyExtractorFunction<TestElement> KEY_EXTRACTOR_FUNCTION = TestElement::getKey;
	protected static final PriorityComparator<TestElement> TEST_ELEMENT_PRIORITY_COMPARATOR =
		(left, right) -> Long.compare(left.getPriority(), right.getPriority());
	protected static final Comparator<TestElement> TEST_ELEMENT_COMPARATOR = (o1, o2) -> {
		int priorityCmp = TEST_ELEMENT_PRIORITY_COMPARATOR.comparePriority(o1, o2);
		if (priorityCmp != 0) {
			return priorityCmp;
		}
		// to fully comply with compareTo/equals contract.
		return Long.compare(o1.getKey(), o2.getKey());
	};

	protected static void insertRandomElements(
		@Nonnull InternalPriorityQueue<TestElement> priorityQueue,
		@Nonnull Set<TestElement> checkSet,
		int count) {

		ThreadLocalRandom localRandom = ThreadLocalRandom.current();

		final int numUniqueKeys = Math.max(count / 4, 64);

		long duplicatePriority = Long.MIN_VALUE;

		final boolean checkEndSizes = priorityQueue.isEmpty();

		for (int i = 0; i < count; ++i) {
			TestElement element;
			do {
				long elementPriority;
				if (duplicatePriority == Long.MIN_VALUE) {
					elementPriority = localRandom.nextLong();
				} else {
					elementPriority = duplicatePriority;
					duplicatePriority = Long.MIN_VALUE;
				}
				element = new TestElement(localRandom.nextInt(numUniqueKeys), elementPriority);
			} while (!checkSet.add(element));

			if (localRandom.nextInt(10) == 0) {
				duplicatePriority = element.getPriority();
			}

			final boolean headChangedIndicated = priorityQueue.add(element);
			if (element.equals(priorityQueue.peek())) {
				Assert.assertTrue(headChangedIndicated);
			}
		}

		if (checkEndSizes) {
			Assert.assertEquals(count, priorityQueue.size());
		}
	}

	@Test
	public void testPeekPollOrder() {
		final int initialCapacity = 4;
		final int testSize = 1000;
		InternalPriorityQueue<TestElement> priorityQueue =
			newPriorityQueue(initialCapacity);
		HashSet<TestElement> checkSet = new HashSet<>(testSize);

		insertRandomElements(priorityQueue, checkSet, testSize);

		long lastPriorityValue = Long.MIN_VALUE;
		int lastSize = priorityQueue.size();
		Assert.assertEquals(testSize, lastSize);
		TestElement testElement;
		while ((testElement = priorityQueue.peek()) != null) {
			Assert.assertFalse(priorityQueue.isEmpty());
			Assert.assertEquals(lastSize, priorityQueue.size());
			Assert.assertEquals(testElement, priorityQueue.poll());
			Assert.assertTrue(checkSet.remove(testElement));
			Assert.assertTrue(testElement.getPriority() >= lastPriorityValue);
			lastPriorityValue = testElement.getPriority();
			--lastSize;
		}

		Assert.assertTrue(priorityQueue.isEmpty());
		Assert.assertEquals(0, priorityQueue.size());
		Assert.assertEquals(0, checkSet.size());
	}

	@Test
	public void testRemoveInsertMixKeepsOrder() {

		InternalPriorityQueue<TestElement> priorityQueue = newPriorityQueue(3);

		final ThreadLocalRandom random = ThreadLocalRandom.current();
		final int testSize = 300;
		final int addCounterMax = testSize / 4;
		int iterationsTillNextAdds = random.nextInt(addCounterMax);
		HashSet<TestElement> checkSet = new HashSet<>(testSize);

		insertRandomElements(priorityQueue, checkSet, testSize);

		// check that the whole set is still in order
		while (!checkSet.isEmpty()) {

			Iterator<TestElement> iterator = checkSet.iterator();
			TestElement element = iterator.next();
			iterator.remove();

			final boolean removesHead = element.equals(priorityQueue.peek());

			if (removesHead) {
				Assert.assertTrue(priorityQueue.remove(element));
			} else {
				priorityQueue.remove(element);
			}

			long lastPriorityValue = removesHead ? element.getPriority() : Long.MIN_VALUE;

			while ((element = priorityQueue.poll()) != null) {
				Assert.assertTrue(element.getPriority() >= lastPriorityValue);
				lastPriorityValue = element.getPriority();
				if (--iterationsTillNextAdds == 0) {
					// some random adds
					iterationsTillNextAdds = random.nextInt(addCounterMax);
					insertRandomElements(priorityQueue, new HashSet<>(checkSet), 1 + random.nextInt(3));
					lastPriorityValue = priorityQueue.peek().getPriority();
				}
			}

			Assert.assertTrue(priorityQueue.isEmpty());

			priorityQueue.addAll(checkSet);
		}
	}

	@Test
	public void testPoll() {
		InternalPriorityQueue<TestElement> priorityQueue = newPriorityQueue(3);

		Assert.assertNull(priorityQueue.poll());

		final int testSize = 345;
		HashSet<TestElement> checkSet = new HashSet<>(testSize);
		insertRandomElements(priorityQueue, checkSet, testSize);

		long lastPriorityValue = Long.MIN_VALUE;
		while (!priorityQueue.isEmpty()) {
			TestElement removed = priorityQueue.poll();
			Assert.assertNotNull(removed);
			Assert.assertTrue(checkSet.remove(removed));
			Assert.assertTrue(removed.getPriority() >= lastPriorityValue);
			lastPriorityValue = removed.getPriority();
		}
		Assert.assertTrue(checkSet.isEmpty());

		Assert.assertNull(priorityQueue.poll());
	}

	@Test
	public void testIsEmpty() {
		InternalPriorityQueue<TestElement> priorityQueue =
			newPriorityQueue(1);

		Assert.assertTrue(priorityQueue.isEmpty());

		Assert.assertTrue(priorityQueue.add(new TestElement(4711L, 42L)));
		Assert.assertFalse(priorityQueue.isEmpty());

		priorityQueue.poll();
		Assert.assertTrue(priorityQueue.isEmpty());
	}

	@Test
	public void testBulkAddRestoredElements() throws Exception {
		final int testSize = 10;
		HashSet<TestElement> elementSet = new HashSet<>(testSize);
		for (int i = 0; i < testSize; ++i) {
			elementSet.add(new TestElement(i, i));
		}

		List<TestElement> twoTimesElementSet = new ArrayList<>(elementSet.size() * 2);

		for (TestElement testElement : elementSet) {
			twoTimesElementSet.add(testElement.deepCopy());
			twoTimesElementSet.add(testElement.deepCopy());
		}

		InternalPriorityQueue<TestElement> priorityQueue =
			newPriorityQueue(1);

		priorityQueue.addAll(twoTimesElementSet);
		priorityQueue.addAll(elementSet);

		final int expectedSize = testSetSemanticsAgainstDuplicateElements() ? elementSet.size() : 3 * elementSet.size();

		Assert.assertEquals(expectedSize, priorityQueue.size());
		try (final CloseableIterator<TestElement> iterator = priorityQueue.iterator()) {
			while (iterator.hasNext()) {
				if (testSetSemanticsAgainstDuplicateElements()) {
					Assert.assertTrue(elementSet.remove(iterator.next()));
				} else {
					Assert.assertTrue(elementSet.contains(iterator.next()));
				}
			}
		}
		if (testSetSemanticsAgainstDuplicateElements()) {
			Assert.assertTrue(elementSet.isEmpty());
		}
	}

	@Test
	public void testIterator() throws Exception {
		InternalPriorityQueue<TestElement> priorityQueue =
			newPriorityQueue(1);

		// test empty iterator
		try (CloseableIterator<TestElement> iterator = priorityQueue.iterator()) {
			Assert.assertFalse(iterator.hasNext());
			try {
				iterator.next();
				Assert.fail();
			} catch (NoSuchElementException ignore) {
			}
		}

		// iterate some data
		final int testSize = 10;
		HashSet<TestElement> checkSet = new HashSet<>(testSize);
		insertRandomElements(priorityQueue, checkSet, testSize);
		try (CloseableIterator<TestElement> iterator = priorityQueue.iterator()) {
			while (iterator.hasNext()) {
				Assert.assertTrue(checkSet.remove(iterator.next()));
			}
			Assert.assertTrue(checkSet.isEmpty());
		}
	}

	@Test
	public void testAdd() {
		InternalPriorityQueue<TestElement> priorityQueue =
			newPriorityQueue(1);

		TestElement lowPrioElement = new TestElement(4711L, 42L);
		TestElement highPrioElement = new TestElement(815L, 23L);
		Assert.assertTrue(priorityQueue.add(lowPrioElement));
		if (testSetSemanticsAgainstDuplicateElements()) {
			priorityQueue.add(lowPrioElement.deepCopy());
		}
		Assert.assertEquals(1, priorityQueue.size());
		Assert.assertTrue(priorityQueue.add(highPrioElement));
		Assert.assertEquals(2, priorityQueue.size());
		Assert.assertEquals(highPrioElement, priorityQueue.poll());
		Assert.assertEquals(1, priorityQueue.size());
		Assert.assertEquals(lowPrioElement, priorityQueue.poll());
		Assert.assertEquals(0, priorityQueue.size());
	}

	@Test
	public void testRemove() {
		InternalPriorityQueue<TestElement> priorityQueue =
			newPriorityQueue(1);

		final long key = 4711L;
		final long priorityValue = 42L;
		final TestElement testElement = new TestElement(key, priorityValue);
		if (testSetSemanticsAgainstDuplicateElements()) {
			Assert.assertFalse(priorityQueue.remove(testElement));
		}
		Assert.assertTrue(priorityQueue.add(testElement));
		Assert.assertTrue(priorityQueue.remove(testElement));
		if (testSetSemanticsAgainstDuplicateElements()) {
			Assert.assertFalse(priorityQueue.remove(testElement));
		}
		Assert.assertTrue(priorityQueue.isEmpty());
	}

	protected abstract InternalPriorityQueue<TestElement> newPriorityQueue(int initialCapacity);

	protected abstract boolean testSetSemanticsAgainstDuplicateElements();

	/**
	 * Payload for usage in the test.
	 */
	protected static class TestElement implements HeapPriorityQueueElement {

		private final long key;
		private final long priority;
		private int internalIndex;

		public TestElement(long key, long priority) {
			this.key = key;
			this.priority = priority;
			this.internalIndex = NOT_CONTAINED;
		}

		public long getKey() {
			return key;
		}

		public long getPriority() {
			return priority;
		}

		@Override
		public int getInternalIndex() {
			return internalIndex;
		}

		@Override
		public void setInternalIndex(int newIndex) {
			internalIndex = newIndex;
		}

		@Override
		public boolean equals(Object o) {
			if (this == o) {
				return true;
			}
			if (o == null || getClass() != o.getClass()) {
				return false;
			}
			TestElement that = (TestElement) o;
			return getKey() == that.getKey() &&
				getPriority() == that.getPriority();
		}

		@Override
		public int hashCode() {
			return Objects.hash(getKey(), getPriority());
		}

		public TestElement deepCopy() {
			return new TestElement(key, priority);
		}
	}

	/**
	 * Serializer for {@link TestElement}. The serialization format produced by this serializer allows lexicographic
	 * ordering by {@link TestElement#getPriority}.
	 */
	protected static class TestElementSerializer extends TypeSerializer<TestElement> {

		public static final TestElementSerializer INSTANCE = new TestElementSerializer();

		private TestElementSerializer() {
		}

		@Override
		public boolean isImmutableType() {
			return true;
		}

		@Override
		public TypeSerializer<TestElement> duplicate() {
			return this;
		}

		@Override
		public TestElement createInstance() {
			throw new UnsupportedOperationException();
		}

		@Override
		public TestElement copy(TestElement from) {
			return new TestElement(from.key, from.priority);
		}

		@Override
		public TestElement copy(TestElement from, TestElement reuse) {
			return copy(from);
		}

		@Override
		public int getLength() {
			return 2 * Long.BYTES;
		}

		@Override
		public void serialize(TestElement record, DataOutputView target) throws IOException {
			// serialize priority first, so that we have correct order in RocksDB. We flip the sign bit for correct
			// lexicographic order.
			target.writeLong(MathUtils.flipSignBit(record.getPriority()));
			target.writeLong(record.getKey());
		}

		@Override
		public TestElement deserialize(DataInputView source) throws IOException {
			long prio = MathUtils.flipSignBit(source.readLong());
			long key = source.readLong();
			return new TestElement(key, prio);
		}

		@Override
		public TestElement deserialize(TestElement reuse, DataInputView source) throws IOException {
			return deserialize(source);
		}

		@Override
		public void copy(DataInputView source, DataOutputView target) throws IOException {
			serialize(deserialize(source), target);
		}

		@Override
		public boolean equals(Object obj) {
			return false;
		}

		@Override
		public boolean canEqual(Object obj) {
			return false;
		}

		@Override
		public int hashCode() {
			return 4711;
		}

		@Override
		public TypeSerializerConfigSnapshot snapshotConfiguration() {
			throw new UnsupportedOperationException();
		}

		@Override
		public CompatibilityResult<TestElement> ensureCompatibility(TypeSerializerConfigSnapshot configSnapshot) {
			throw new UnsupportedOperationException();
		}
	}
}


text:
class Domain < ActiveRecord::Base
  include Versions # version/domain_version.rb
  include Statuses
  has_paper_trail class_name: "DomainVersion", meta: { children: :children_log }

  attr_accessor :roles

  # TODO: whois requests ip whitelist for full info for own domains and partial info for other domains
  # TODO: most inputs should be trimmed before validatation, probably some global logic?

  belongs_to :registrar
  belongs_to :registrant
  # TODO: should we user validates_associated :registrant here?

  has_many :admin_domain_contacts
  accepts_nested_attributes_for :admin_domain_contacts,  allow_destroy: true, reject_if: :admin_change_prohibited?
  has_many :tech_domain_contacts
  accepts_nested_attributes_for :tech_domain_contacts, allow_destroy: true, reject_if: :tech_change_prohibited?

  def registrant_change_prohibited?
    statuses.include? DomainStatus::SERVER_REGISTRANT_CHANGE_PROHIBITED
  end

  # NB! contacts, admin_contacts, tech_contacts are empty for a new record
  has_many :domain_contacts, dependent: :destroy
  has_many :contacts, through: :domain_contacts, source: :contact
  has_many :admin_contacts, through: :admin_domain_contacts, source: :contact
  has_many :tech_contacts, through: :tech_domain_contacts, source: :contact
  has_many :nameservers, dependent: :destroy

  accepts_nested_attributes_for :nameservers, allow_destroy: true,
                                              reject_if: proc { |attrs| attrs[:hostname].blank? }

  has_many :domain_statuses, dependent: :destroy
  accepts_nested_attributes_for :domain_statuses, allow_destroy: true,
                                                  reject_if: proc { |attrs| attrs[:value].blank? }

  has_many :domain_transfers, dependent: :destroy

  has_many :dnskeys, dependent: :destroy

  has_many :keyrelays
  has_one :whois_record, dependent: :destroy

  accepts_nested_attributes_for :dnskeys, allow_destroy: true

  has_many :legal_documents, as: :documentable
  accepts_nested_attributes_for :legal_documents, reject_if: proc { |attrs| attrs[:body].blank? }

  delegate :name,    to: :registrant, prefix: true
  delegate :code,    to: :registrant, prefix: true
  delegate :ident,   to: :registrant, prefix: true
  delegate :email,   to: :registrant, prefix: true
  delegate :phone,   to: :registrant, prefix: true
  delegate :street,  to: :registrant, prefix: true
  delegate :city,    to: :registrant, prefix: true
  delegate :zip,     to: :registrant, prefix: true
  delegate :state,   to: :registrant, prefix: true
  delegate :country, to: :registrant, prefix: true

  delegate :name,   to: :registrar, prefix: true
  delegate :street, to: :registrar, prefix: true

  after_initialize do
    self.pending_json = {} if pending_json.blank?
    self.statuses = [] if statuses.nil?
    self.status_notes = {} if status_notes.nil?
  end

  before_create :generate_auth_info
  before_create :set_validity_dates
  before_create -> { self.reserved = in_reserved_list?; nil }

  before_save :manage_automatic_statuses
  before_save :touch_always_version
  def touch_always_version
    self.updated_at = Time.zone.now
  end

  before_update :manage_statuses
  def manage_statuses
    return unless registrant_id_changed? # rollback has not yet happened
    pending_update! if registrant_verification_asked?
    true
  end

  after_save :update_whois_record

  after_create :update_reserved_domains
  def update_reserved_domains
    return unless in_reserved_list?
    rd = ReservedDomain.first
    rd.names[name] = SecureRandom.hex
    rd.save
  end

  validates :name_dirty, domain_name: true, uniqueness: true
  validates :puny_label, length: { maximum: 63 }
  validates :period, numericality: { only_integer: true }
  validates :registrant, :registrar, presence: true

  validate :validate_period
  validate :validate_reservation
  def validate_reservation
    return if persisted? || !in_reserved_list?

    if reserved_pw.blank?
      errors.add(:base, :required_parameter_missing_reserved)
      return false
    end

    return if ReservedDomain.pw_for(name) == reserved_pw
    errors.add(:base, :invalid_auth_information_reserved)
  end

  validate :status_is_consistant
  def status_is_consistant
      has_error = (statuses.include?(DomainStatus::SERVER_HOLD) && statuses.include?(DomainStatus::SERVER_MANUAL_INZONE))
      unless has_error
        if (statuses & [DomainStatus::PENDING_DELETE_CONFIRMATION, DomainStatus::PENDING_DELETE, DomainStatus::FORCE_DELETE]).any?
          has_error = statuses.include? DomainStatus::SERVER_DELETE_PROHIBITED
        end
      end
      errors.add(:domains, I18n.t(:object_status_prohibits_operation)) if has_error
  end

  attr_accessor :is_admin

  validate :check_permissions, :unless => :is_admin
  def check_permissions
    return unless force_delete?
    errors.add(:base, I18n.t(:object_status_prohibits_operation))
    false
  end

  validates :nameservers, object_count: {
    min: -> { Setting.ns_min_count },
    max: -> { Setting.ns_max_count }
  }

  validates :dnskeys, object_count: {
    min: -> { Setting.dnskeys_min_count },
    max: -> { Setting.dnskeys_max_count }
  }

  validates :admin_domain_contacts, object_count: {
    min: -> { Setting.admin_contacts_min_count },
    max: -> { Setting.admin_contacts_max_count }
  }

  validates :tech_domain_contacts, object_count: {
    min: -> { Setting.tech_contacts_min_count },
    max: -> { Setting.tech_contacts_max_count }
  }

  validates :nameservers, uniqueness_multi: {
    attribute: 'hostname'
  }

  validates :tech_domain_contacts, uniqueness_multi: {
    attribute: 'contact_code_cache'
  }

  validates :admin_domain_contacts, uniqueness_multi: {
    attribute: 'contact_code_cache'
  }

  validates :domain_statuses, uniqueness_multi: {
    attribute: 'value'
  }

  validates :dnskeys, uniqueness_multi: {
    attribute: 'public_key'
  }

  validate :validate_nameserver_ips

  validate :statuses_uniqueness
  def statuses_uniqueness
    return if statuses.uniq == statuses
    errors.add(:statuses, :taken)
  end

  attr_accessor :registrant_typeahead, :update_me, :deliver_emails,
    :epp_pending_update, :epp_pending_delete, :reserved_pw

  def subordinate_nameservers
    nameservers.select { |x| x.hostname.end_with?(name) }
  end

  def delegated_nameservers
    nameservers.select { |x| !x.hostname.end_with?(name) }
  end

  def admin_change_prohibited?
    statuses.include? DomainStatus::SERVER_ADMIN_CHANGE_PROHIBITED
  end

  def tech_change_prohibited?
    statuses.include? DomainStatus::SERVER_TECH_CHANGE_PROHIBITED
  end

  class << self
    def convert_period_to_time(period, unit)
      return (period.to_i / 365).years if unit == 'd'
      return (period.to_i / 12).years  if unit == 'm'
      return period.to_i.years         if unit == 'y'
    end

    def included
      includes(
        :registrant,
        :registrar,
        :nameservers,
        :whois_record,
        { tech_contacts: :registrar },
        { admin_contacts: :registrar }
      )
    end

    # rubocop: disable Metrics/AbcSize
    # rubocop: disable Metrics/CyclomaticComplexity
    # rubocop: disable Metrics/PerceivedComplexity
    def clean_expired_pendings
      STDOUT << "#{Time.zone.now.utc} - Clean expired domain pendings\n" unless Rails.env.test?

      expire_at = Setting.expire_pending_confirmation.hours.ago
      count = 0
      expired_pending_domains = Domain.where('registrant_verification_asked_at <= ?', expire_at)
      expired_pending_domains.each do |domain|
        unless domain.pending_update? || domain.pending_delete? || domain.pending_delete_confirmation?
          msg = "#{Time.zone.now.utc} - ISSUE: DOMAIN #{domain.id}: #{domain.name} IS IN EXPIRED PENDING LIST, " \
                "but no pendingDelete/pendingUpdate state present!\n"
          STDOUT << msg unless Rails.env.test?
          next
        end
        count += 1
        if domain.pending_update?
          DomainMailer.pending_update_expired_notification_for_new_registrant(domain).deliver_now
        end
        if domain.pending_delete? || domain.pending_delete_confirmation?
          DomainMailer.pending_delete_expired_notification(domain).deliver_now
        end
        domain.clean_pendings!
        unless Rails.env.test?
          STDOUT << "#{Time.zone.now.utc} Domain.clean_expired_pendings: ##{domain.id} (#{domain.name})\n"
        end
      end
      STDOUT << "#{Time.zone.now.utc} - Successfully cancelled #{count} domain pendings\n" unless Rails.env.test?
      count
    end
    # rubocop: enable Metrics/PerceivedComplexity
    # rubocop: enable Metrics/AbcSize
    # rubocop: enable Metrics/CyclomaticComplexity

    # rubocop: disable Metrics/LineLength
    def start_expire_period
      STDOUT << "#{Time.zone.now.utc} - Expiring domains\n" unless Rails.env.test?

      domains = Domain.where('valid_to <= ?', Time.zone.now)
      domains.each do |domain|
        next unless domain.expirable?
        domain.set_graceful_expired
        STDOUT << "#{Time.zone.now.utc} Domain.start_expire_period: ##{domain.id} (#{domain.name}) #{domain.changes}\n" unless Rails.env.test?
        domain.save
      end

      STDOUT << "#{Time.zone.now.utc} - Successfully expired #{domains.count} domains\n" unless Rails.env.test?
    end

    def start_redemption_grace_period
      STDOUT << "#{Time.zone.now.utc} - Setting server_hold to domains\n" unless Rails.env.test?

      d = Domain.where('outzone_at <= ?', Time.zone.now)
      d.each do |domain|
        next unless domain.server_holdable?
        domain.statuses << DomainStatus::SERVER_HOLD
        STDOUT << "#{Time.zone.now.utc} Domain.start_redemption_grace_period: ##{domain.id} (#{domain.name}) #{domain.changes}\n" unless Rails.env.test?
        domain.save
      end

      STDOUT << "#{Time.zone.now.utc} - Successfully set server_hold to #{d.count} domains\n" unless Rails.env.test?
    end

    def start_delete_period
      STDOUT << "#{Time.zone.now.utc} - Setting delete_candidate to domains\n" unless Rails.env.test?

      d = Domain.where('delete_at <= ?', Time.zone.now)
      d.each do |domain|
        next unless domain.delete_candidateable?
        domain.statuses << DomainStatus::DELETE_CANDIDATE
        STDOUT << "#{Time.zone.now.utc} Domain.start_delete_period: ##{domain.id} (#{domain.name}) #{domain.changes}\n" unless Rails.env.test?
        domain.save
      end

      return if Rails.env.test?
      STDOUT << "#{Time.zone.now.utc} - Successfully set delete_candidate to #{d.count} domains\n"
    end

    # rubocop:disable Rails/FindEach
    # rubocop:disable Metrics/AbcSize
    def destroy_delete_candidates
      STDOUT << "#{Time.zone.now.utc} - Destroying domains\n" unless Rails.env.test?

      c = 0
      Domain.where("statuses @> '{deleteCandidate}'::varchar[]").each do |x|
        Whois::Record.where('domain_id = ?', x.id).try(':destroy')
        x.destroy
        STDOUT << "#{Time.zone.now.utc} Domain.destroy_delete_candidates: by deleteCandidate ##{x.id} (#{x.name})\n" unless Rails.env.test?
        c += 1
      end

      Domain.where('force_delete_at <= ?', Time.zone.now).each do |x|
        Whois::Record.where('domain_id = ?', x.id).try(':destroy')
        x.destroy
        STDOUT << "#{Time.zone.now.utc} Domain.destroy_delete_candidates: by force delete time ##{x.id} (#{x.name})\n" unless Rails.env.test?
        c += 1
      end

      STDOUT << "#{Time.zone.now.utc} - Successfully destroyed #{c} domains\n" unless Rails.env.test?
    end
    # rubocop: enable Metrics/AbcSize
    # rubocop:enable Rails/FindEach
    # rubocop: enable Metrics/LineLength
  end

  def name=(value)
    value.strip!
    value.downcase!
    self[:name] = SimpleIDN.to_unicode(value)
    self[:name_puny] = SimpleIDN.to_ascii(value)
    self[:name_dirty] = value
  end

  def roid
    "EIS-#{id}"
  end

  def puny_label
    name_puny.to_s.split('.').first
  end

  def registrant_typeahead
    @registrant_typeahead || registrant.try(:name) || nil
  end

  def in_reserved_list?
    ReservedDomain.pw_for(name).present?
  end

  def pending_transfer
    domain_transfers.find_by(status: DomainTransfer::PENDING)
  end

  def expirable?
    return false if valid_to > Time.zone.now

    if statuses.include?(DomainStatus::EXPIRED) && outzone_at.present? && delete_at.present?
      return false
    end

    true
  end

  def server_holdable?
    return false if statuses.include?(DomainStatus::SERVER_HOLD)
    return false if statuses.include?(DomainStatus::SERVER_MANUAL_INZONE)
    true
  end

  def delete_candidateable?
    return false if delete_at > Time.zone.now
    return false if statuses.include?(DomainStatus::DELETE_CANDIDATE)
    return false if statuses.include?(DomainStatus::SERVER_DELETE_PROHIBITED)
    true
  end

  def renewable?
    if Setting.days_to_renew_domain_before_expire != 0
      # if you can renew domain at days_to_renew before domain expiration
      if (valid_to.to_date - Date.today) + 1 > Setting.days_to_renew_domain_before_expire
        return false
      end
    end

    return false if statuses.include_any?(DomainStatus::DELETE_CANDIDATE, DomainStatus::SERVER_RENEW_PROHIBITED,
                                          DomainStatus::CLIENT_RENEW_PROHIBITED, DomainStatus::PENDING_RENEW,
                                          DomainStatus::PENDING_TRANSFER, DomainStatus::PENDING_DELETE,
                                          DomainStatus::PENDING_UPDATE, DomainStatus::PENDING_DELETE_CONFIRMATION)
    true
  end

  def poll_message!(message_key)
    registrar.messages.create!(
      body: "#{I18n.t(message_key)}: #{name}",
      attached_obj_id: id,
      attached_obj_type: self.class.to_s
    )
  end

  def preclean_pendings
    self.registrant_verification_token = nil
    self.registrant_verification_asked_at = nil
  end

  def clean_pendings!
    preclean_pendings
    self.pending_json = {}
    statuses.delete(DomainStatus::PENDING_DELETE_CONFIRMATION)
    statuses.delete(DomainStatus::PENDING_UPDATE)
    statuses.delete(DomainStatus::PENDING_DELETE)
    status_notes[DomainStatus::PENDING_UPDATE] = ''
    status_notes[DomainStatus::PENDING_DELETE] = ''
    save
  end

  def pending_update!
    return true if pending_update?
    self.epp_pending_update = true # for epp

    return true unless registrant_verification_asked?
    pending_json_cache = pending_json
    token = registrant_verification_token
    asked_at = registrant_verification_asked_at
    new_registrant_id    = registrant.id
    new_registrant_email = registrant.email
    new_registrant_name  = registrant.name

    DomainMailer.pending_update_request_for_old_registrant(self).deliver_now
    DomainMailer.pending_update_notification_for_new_registrant(self).deliver_now

    reload # revert back to original

    self.pending_json = pending_json_cache
    self.registrant_verification_token = token
    self.registrant_verification_asked_at = asked_at
    set_pending_update
    pending_json['new_registrant_id']    = new_registrant_id
    pending_json['new_registrant_email'] = new_registrant_email
    pending_json['new_registrant_name']  = new_registrant_name

    # This pending_update! method is triggered by before_update
    # Note, all before_save callbacks are excecuted before before_update,
    # thus automatic statuses has already excectued by this point
    # and we need to trigger automatic statuses manually (second time).
    manage_automatic_statuses
  end

  # rubocop: disable Metrics/CyclomaticComplexity
  def registrant_update_confirmable?(token)
    return false if (statuses & [DomainStatus::FORCE_DELETE, DomainStatus::DELETE_CANDIDATE]).any?
    return false unless pending_update?
    return false unless registrant_verification_asked?
    return false unless registrant_verification_token == token
    true
  end

  def registrant_delete_confirmable?(token)
    return false unless pending_delete?
    return false unless registrant_verification_asked?
    return false unless registrant_verification_token == token
    true
  end
  # rubocop: enable Metrics/CyclomaticComplexity

  def force_deletable?
    !statuses.include?(DomainStatus::FORCE_DELETE)
  end

  def registrant_verification_asked?
    registrant_verification_asked_at.present? && registrant_verification_token.present?
  end

  def registrant_verification_asked!(frame_str, current_user_id)
    pending_json['frame'] = frame_str
    pending_json['current_user_id'] = current_user_id
    self.registrant_verification_asked_at = Time.zone.now
    self.registrant_verification_token = SecureRandom.hex(42)
  end

  def pending_delete!
    return true if pending_delete?
    self.epp_pending_delete = true # for epp

    # TODO: if this were to ever return true, that would be wrong. EPP would report sucess pending
    return true unless registrant_verification_asked?
    pending_delete_confirmation!
    save(validate: false) # should check if this did succeed

    DomainMailer.pending_deleted(self).deliver_now
  end

  def pricelist(operation, period_i = nil, unit = nil)
    period_i ||= period
    unit ||= period_unit

    zone = name.split('.').drop(1).join('.')

    p = period_i / 365 if unit == 'd'
    p = period_i / 12 if unit == 'm'
    p = period_i if unit == 'y'

    if p > 1
      p = "#{p}years"
    else
      p = "#{p}year"
    end

    Pricelist.pricelist_for(zone, operation, p)
  end

  ### VALIDATIONS ###

  def validate_nameserver_ips
    nameservers.each do |ns|
      next unless ns.hostname.end_with?(name)
      next if ns.ipv4.present?
      errors.add(:nameservers, :invalid) if errors[:nameservers].blank?
      ns.errors.add(:ipv4, :blank)
    end
  end

  def validate_period
    return unless period.present?
    if period_unit == 'd'
      valid_values = %w(365 730 1095)
    elsif period_unit == 'm'
      valid_values = %w(12 24 36)
    else
      valid_values = %w(1 2 3)
    end

    errors.add(:period, :out_of_range) unless valid_values.include?(period.to_s)
  end

  # used for highlighting form tabs
  def parent_valid?
    assoc_errors = errors.keys.select { |x| x.match(/\./) }
    (errors.keys - assoc_errors).empty?
  end

  ## SHARED

  def name_in_wire_format
    res = ''
    parts = name.split('.')
    parts.each do |x|
      res += format('%02X', x.length) # length of label in hex
      res += x.each_byte.map { |b| format('%02X', b) }.join # label
    end

    res += '00'

    res
  end

  def to_s
    name
  end

  def pending_registrant
    return '' if pending_json.blank?
    return '' if pending_json['new_registrant_id'].blank?
    Registrant.find_by(id: pending_json['new_registrant_id'].last)
  end

  def generate_auth_info
    return if auth_info.present?
    generate_auth_info!
  end

  # rubocop:disable Lint/Loop
  def generate_auth_info!
    begin
      self.auth_info = SecureRandom.hex
    end while self.class.exists?(auth_info: auth_info)
  end
  # rubocop:enable Lint/Loop

  def set_validity_dates
    self.registered_at = Time.zone.now
    self.valid_from = Time.zone.now
    self.valid_to = valid_from + self.class.convert_period_to_time(period, period_unit)
  end

  # rubocop:disable Metrics/AbcSize
  # rubocop:disable Metrics/MethodLength
  def set_force_delete
    self.statuses_backup = statuses
    statuses.delete(DomainStatus::CLIENT_DELETE_PROHIBITED)
    statuses.delete(DomainStatus::SERVER_DELETE_PROHIBITED)
    statuses.delete(DomainStatus::PENDING_UPDATE)
    statuses.delete(DomainStatus::PENDING_TRANSFER)
    statuses.delete(DomainStatus::PENDING_RENEW)
    statuses.delete(DomainStatus::PENDING_CREATE)

    statuses.delete(DomainStatus::FORCE_DELETE)
    statuses.delete(DomainStatus::SERVER_RENEW_PROHIBITED)
    statuses.delete(DomainStatus::SERVER_TRANSFER_PROHIBITED)
    statuses.delete(DomainStatus::SERVER_UPDATE_PROHIBITED)
    statuses.delete(DomainStatus::SERVER_MANUAL_INZONE)
    statuses.delete(DomainStatus::PENDING_DELETE)

    statuses << DomainStatus::FORCE_DELETE
    statuses << DomainStatus::SERVER_RENEW_PROHIBITED
    statuses << DomainStatus::SERVER_TRANSFER_PROHIBITED
    statuses << DomainStatus::SERVER_UPDATE_PROHIBITED
    statuses << DomainStatus::PENDING_DELETE

    if (statuses & [DomainStatus::SERVER_HOLD, DomainStatus::CLIENT_HOLD]).empty?
      statuses << DomainStatus::SERVER_MANUAL_INZONE
    end

    self.force_delete_at = Time.zone.now + Setting.redemption_grace_period.days unless force_delete_at
    transaction do
      save!(validate: false)
      registrar.messages.create!(
        body: I18n.t('force_delete_set_on_domain', domain: name)
      )
      DomainMailer.force_delete(self).deliver_now
      return true
    end
    false
  end
  # rubocop: enable Metrics/MethodLength
  # rubocop:enable Metrics/AbcSize

  def unset_force_delete
    s = []
    s << DomainStatus::EXPIRED if statuses.include?(DomainStatus::EXPIRED)
    s << DomainStatus::SERVER_HOLD if statuses.include?(DomainStatus::SERVER_HOLD)
    s << DomainStatus::DELETE_CANDIDATE if statuses.include?(DomainStatus::DELETE_CANDIDATE)

    self.statuses = (statuses_backup + s).uniq

    self.force_delete_at = nil
    self.statuses_backup = []
    save(validate: false)
  end

  def set_graceful_expired
    self.outzone_at = valid_to + Setting.expire_warning_period.days
    self.delete_at = outzone_at + Setting.redemption_grace_period.days
    self.statuses |= [DomainStatus::EXPIRED]
  end

  def set_expired
    # TODO: currently valid_to attribute update logic is open
    # self.valid_to = valid_from + self.class.convert_period_to_time(period, period_unit)
    self.outzone_at = Time.zone.now + Setting.expire_warning_period.days
    self.delete_at  = Time.zone.now + Setting.redemption_grace_period.days
    statuses << DomainStatus::EXPIRED
  end

  def set_expired!
    set_expired
    save(validate: false)
  end

  def pending_update?
    statuses.include?(DomainStatus::PENDING_UPDATE) && !statuses.include?(DomainStatus::FORCE_DELETE)
  end

  # depricated not used, not valid
  def update_prohibited?
    pending_update_prohibited? && pending_delete_prohibited?
  end

  # public api
  def delete_prohibited?
    statuses.include?(DomainStatus::FORCE_DELETE)
  end

  def pending_update_prohibited?
    (statuses_was & [
        DomainStatus::PENDING_DELETE_CONFIRMATION,
      DomainStatus::CLIENT_UPDATE_PROHIBITED,
      DomainStatus::SERVER_UPDATE_PROHIBITED,
      DomainStatus::PENDING_CREATE,
      DomainStatus::PENDING_UPDATE,
      DomainStatus::PENDING_DELETE,
      DomainStatus::PENDING_RENEW,
      DomainStatus::PENDING_TRANSFER
    ]).present?
  end

  def set_pending_update
    if pending_update_prohibited?
      logger.info "DOMAIN STATUS UPDATE ISSUE ##{id}: PENDING_UPDATE not allowed to set. [#{statuses}]"
      return nil
    end
    statuses << DomainStatus::PENDING_UPDATE
  end

  def pending_delete?
    (statuses & [DomainStatus::PENDING_DELETE_CONFIRMATION, DomainStatus::PENDING_DELETE]).any?
  end

  def pending_delete_confirmation?
    statuses.include? DomainStatus::PENDING_DELETE_CONFIRMATION
  end

  def pending_delete_confirmation!
    statuses << DomainStatus::PENDING_DELETE_CONFIRMATION unless pending_delete_prohibited?
  end

  def pending_delete_prohibited?
    (statuses_was & [
      DomainStatus::CLIENT_DELETE_PROHIBITED,
      DomainStatus::SERVER_DELETE_PROHIBITED,
      DomainStatus::CLIENT_UPDATE_PROHIBITED,
      DomainStatus::SERVER_UPDATE_PROHIBITED,
      DomainStatus::PENDING_CREATE,
      DomainStatus::PENDING_RENEW,
      DomainStatus::PENDING_TRANSFER,
      DomainStatus::PENDING_UPDATE,
      DomainStatus::PENDING_DELETE
    ]).present?
  end

  # let's use positive method names
  def pending_deletable?
    !pending_delete_prohibited?
  end

  def set_pending_delete
    if pending_delete_prohibited?
      logger.info "DOMAIN STATUS UPDATE ISSUE ##{id}: PENDING_DELETE not allowed to set. [#{statuses}]"
      return nil
    end
    statuses << DomainStatus::PENDING_DELETE
  end

  def set_server_hold
    statuses << DomainStatus::SERVER_HOLD
  end

  # rubocop: disable Metrics/CyclomaticComplexity
  # rubocop: disable Metrics/PerceivedComplexity
  def manage_automatic_statuses
    if statuses.empty? && valid?
      statuses << DomainStatus::OK
    elsif statuses.length > 1 || !valid?
      statuses.delete(DomainStatus::OK)
    end

    p_d = statuses.include?(DomainStatus::PENDING_DELETE)
    s_h = (statuses & [DomainStatus::SERVER_MANUAL_INZONE, DomainStatus::SERVER_HOLD]).empty?
    statuses << DomainStatus::SERVER_HOLD if p_d && s_h
  end
  # rubocop: enable Metrics/CyclomaticComplexity
  # rubocop: enable Metrics/PerceivedComplexity

  def children_log
    log = HashWithIndifferentAccess.new
    log[:admin_contacts] = admin_contact_ids
    log[:tech_contacts]  = tech_contact_ids
    log[:nameservers]    = nameserver_ids
    log[:registrant]     = [registrant_id]
    log[:domain_statuses] = domain_status_ids
    log
  end

  def update_whois_record
    whois_record.blank? ? create_whois_record : whois_record.save
  end

  def status_notes_array=(notes)
    self.status_notes = {}
    notes ||= []
    statuses.each_with_index do |status, i|
      status_notes[status] = notes[i]
    end
  end
end
# rubocop: enable Metrics/ClassLength


text:
<component name="libraryTable">
  <library name="simpleconfiglib">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/libs/simpleconfiglib.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
if (typeof window.cordova !== undefined) {
  window.cordova = {};
}


text:
#ifndef _PICO_STDIO_H
#define _PICO_STDIO_H

/** \file stdio.h
*  \defgroup pico_stdio pico_stdio
* Customized stdio support allowing for input and output from UART, USB, semi-hosting etc.
*
* Note the API for adding additional input output devices is not yet considered stable
*/

#include "pico.h"

// PICO_CONFIG: PICO_STDOUT_MUTEX, Enable/disable mutex around stdout, type=bool, default=1, group=pico_stdio
#ifndef PICO_STDOUT_MUTEX
#define PICO_STDOUT_MUTEX 1
#endif

// PICO_CONFIG: PICO_STDIO_ENABLE_CRLF_SUPPORT, Enable/disable CR/LF output conversion support, type=bool, default=1, group=pico_stdio
#ifndef PICO_STDIO_ENABLE_CRLF_SUPPORT
#define PICO_STDIO_ENABLE_CRLF_SUPPORT 1
#endif

// PICO_CONFIG: PICO_STDIO_DEFAULT_CRLF, Default for CR/LF conversion enabled on all stdio outputs, type=bool, default=1, depends=PICO_STDIO_ENABLE_CRLF_SUPPORT, group=pico_stdio
#ifndef PICO_STDIO_DEFAULT_CRLF
#define PICO_STDIO_DEFAULT_CRLF 1
#endif

// PICO_CONFIG: PICO_STDIO_STACK_BUFFER_SIZE, Define printf buffer size (on stack)... this is just a working buffer not a max output size, min=0, max=512, default=128, group=pico_stdio
#ifndef PICO_STDIO_STACK_BUFFER_SIZE
#define PICO_STDIO_STACK_BUFFER_SIZE 128
#endif

#ifdef __cplusplus
extern "C" {
#endif

typedef struct stdio_driver stdio_driver_t;

/*! \brief Initialize all of the present standard stdio types that are linked into the binary.
 * \ingroup pico_stdio
 *
 * Call this method once you have set up your clocks to enable the stdio support for UART, USB
 * and semihosting based on the presence of the respective librariess in the binary.
 *
 * \see stdio_uart, stdio_usb, stdio_semihosting
 */
void stdio_init_all(void);

/*! \brief Initialize all of the present standard stdio types that are linked into the binary.
 * \ingroup pico_stdio
 *
 * Call this method once you have set up your clocks to enable the stdio support for UART, USB
 * and semihosting based on the presence of the respective librariess in the binary.
 *
 * \see stdio_uart, stdio_usb, stdio_semihosting
 */
void stdio_flush(void);

/*! \brief Return a character from stdin if there is one available within a timeout
 * \ingroup pico_stdio
 *
 * \param timeout_us the timeout in microseconds, or 0 to not wait for a character if none available.
 * \return the character from 0-255 or PICO_ERROR_TIMEOUT if timeout occurs
 */
int getchar_timeout_us(uint32_t timeout_us);

/*! \brief Adds or removes a driver from the list of active drivers used for input/output
 * \ingroup pico_stdio
 *
 * \note this method should always be called on an initialized driver
 * \param driver the driver
 * \param enabled true to add, false to remove
 */
void stdio_set_driver_enabled(stdio_driver_t *driver, bool enabled);

/*! \brief Control limiting of output to a single driver
 * \ingroup pico_stdio
 *
 * \note this method should always be called on an initialized driver
 *
 * \param driver if non-null then output only that driver will be used for input/output (assuming it is in the list of enabled drivers).
 *               if NULL then all enabled drivers will be used
 */
void stdio_filter_driver(stdio_driver_t *driver);

/*! \brief control conversion of line feeds to carriage return on transmissions
 * \ingroup pico_stdio
 *
 * \note this method should always be called on an initialized driver
 *
 * \param driver the driver
 * \param translate If true, convert line feeds to carriage return on transmissions
 */
void stdio_set_translate_crlf(stdio_driver_t *driver, bool translate);

#ifdef __cplusplus
}
#endif

#endif