text:
'''

Test Security Group for 1 VM with ingress rules and VM operations: shutdown, start, reboot and destroy. Will check if VM SG rules are still there, after vm operations.

@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.zstack_test.zstack_test_security_group as test_sg_header
import zstackwoodpecker.zstack_test.zstack_test_sg_vm as test_sg_vm_header
import apibinding.inventory as inventory
import zstacklib.utils.linux as linux

test_stub = test_lib.lib_get_test_stub()
Port = test_state.Port

test_obj_dict = test_state.TestStateDict()

def do_check(params):
    vm = params[0]
    special_str = params[1]
    if test_lib.lib_check_vm_sg_rule_exist_in_iptables(vm, special_string=special_str):
        test_util.test_logger('[vm:] %s SG INGRESS rules are not removed, after it is destroyed. Will try again.' % vm.uuid)
        return False
    return True

def test():
    '''
        Test image requirements:
            1. have nc to check the network port
            2. have "nc" to open any port
            3. it doesn't include a default firewall
        VR image is a good candiate to be the guest image.
    '''

    global test_obj_dict
    test_util.test_dsc("Create 2 VMs with vlan VR L3 network and using VR image.")
    vm1 = test_stub.create_sg_vm()
    test_obj_dict.add_vm(vm1)
    vm2 = test_stub.create_sg_vm()
    test_obj_dict.add_vm(vm2)
    vm1.check()
    vm2.check()

    test_util.test_dsc("Create security groups.")
    sg1 = test_stub.create_sg()
    test_obj_dict.add_sg(sg1.security_group.uuid)
    sg2 = test_stub.create_sg()
    test_obj_dict.add_sg(sg2.security_group.uuid)
    sg3 = test_stub.create_sg()
    test_obj_dict.add_sg(sg3.security_group.uuid)
    sg_vm = test_sg_vm_header.ZstackTestSgVm()
    sg_vm.check()

    nic_uuid = vm1.vm.vmNics[0].uuid
    vm_nics = (nic_uuid, vm1)
    l3_uuid = vm1.vm.vmNics[0].l3NetworkUuid
    vr_vm = test_lib.lib_find_vr_by_vm(vm1.vm)[0]
    vm2_ip = test_lib.lib_get_vm_nic_by_l3(vm2.vm, l3_uuid).ip

    rule1 = test_lib.lib_gen_sg_rule(Port.rule1_ports, inventory.TCP, inventory.INGRESS, vm2_ip)
    rule2 = test_lib.lib_gen_sg_rule(Port.rule2_ports, inventory.TCP, inventory.INGRESS, vm2_ip)
    rule3 = test_lib.lib_gen_sg_rule(Port.rule3_ports, inventory.TCP, inventory.INGRESS, vm2_ip)
    rule4 = test_lib.lib_gen_sg_rule(Port.rule4_ports, inventory.TCP, inventory.INGRESS, vm2_ip)
    rule5 = test_lib.lib_gen_sg_rule(Port.rule5_ports, inventory.TCP, inventory.INGRESS, vm2_ip)

    sg1.add_rule([rule1])
    sg2.add_rule([rule1, rule2, rule3])
    sg3.add_rule([rule3, rule4, rule5])
    sg_vm.check()

    sg_vm.add_stub_vm(l3_uuid, vm2)

    #test_util.test_dsc("Create SG rule6: allow connection from vr to port 0~65535")
    #rule6 = inventory.SecurityGroupRuleAO()
    #rule6.allowedCidr = '%s/32' % vr_internal_ip
    #rule6.protocol = inventory.TCP
    #rule6.startPort = 0
    #rule6.endPort = 65535
    #rule6.type = inventory.INGRESS

    #test_stub.lib_add_sg_rules(sg1.uuid, [rule1, rule6])

    #add sg1
    test_util.test_dsc("Attach security group 1 to [nic:] %s L3." % nic_uuid)
    test_util.test_dsc("Add nic to security group 1.")
    sg_vm.attach(sg1, [vm_nics])
    sg_vm.check()

    #add sg2
    test_util.test_dsc("Attach security group 2 to [nic:] %s L3." % nic_uuid)
    test_util.test_dsc("Add nic to security group 2.")
    sg_vm.attach(sg2, [vm_nics])
    sg_vm.check()

    #add sg3
    test_util.test_dsc("Attach security group 3 to [nic:] %s L3." % nic_uuid)
    test_util.test_dsc("Add nic to security group 3.")
    tmp_allowed_ports = test_stub.rule1_ports + test_stub.rule2_ports + test_stub.rule3_ports + test_stub.rule4_ports + test_stub.rule5_ports
    test_util.test_dsc("Allowed ports: %s" % tmp_allowed_ports)
    sg_vm.attach(sg3, [vm_nics])
    sg_vm.check()

    #shutdown vm1
    test_util.test_dsc("Shutdown VM1")
    vm1.stop()
    sg_vm.check()

    test_util.test_dsc("Start VM1")
    vm1.start()
    vm1.check()

    test_util.test_dsc("Allowed ports: %s" % tmp_allowed_ports)
    sg_vm.check()

    test_util.test_dsc("Restart VM1")
    vm1.reboot()
    vm1.check()

    test_util.test_dsc("Allowed ports: %s" % tmp_allowed_ports)
    sg_vm.check()

    test_util.test_dsc("Destroy VM1. All its SG rules should be removed.")
    vm_internalId = test_lib.lib_get_vm_internal_id(vm1.vm)
    vm1.destroy()
    test_obj_dict.rm_vm(vm1)
    if linux.wait_callback_success(do_check, (vm1.vm, "vnic%s.0-in" % vm_internalId), 5, 0.2):
        test_util.test_logger('[vm:] %s SG INGRESS rules are removed, after it is destroyed.' % vm1.vm.uuid)
    else:
        test_util.test_fail('[vm:] %s SG INGRESS rules are not removed, after it is destroyed 5 seconds. ' % vm1.vm.uuid)

    vm2.destroy()
    test_obj_dict.rm_vm(vm2)
    sg_vm.delete_sg(sg3)
    test_obj_dict.rm_sg(sg3.security_group.uuid)
    sg_vm.delete_sg(sg2)
    test_obj_dict.rm_sg(sg2.security_group.uuid)
    sg_vm.delete_sg(sg1)
    test_obj_dict.rm_sg(sg1.security_group.uuid)
    test_util.test_pass('Security Group Vlan VirtualRouter VM Start/Stop/Reboot/Destroy Test Success')

#Will be called only if exception happens in test().
def error_cleanup():
    global test_obj_dict
    test_lib.lib_error_cleanup(test_obj_dict)


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.n52.gep.enviroCar</groupId>
		<artifactId>enviroCar-gep-components</artifactId>
		<version>0.1.0-SNAPSHOT</version>
	</parent>

	<artifactId>commons</artifactId>
	<packaging>bundle</packaging>

	<properties>
		<org.n52.osgi.import-package></org.n52.osgi.import-package>
		<org.n52.osgi.export-package>org.n52.cario.gep.commons.json,
			org.n52.cario.gep.commons.inbound,
			org.n52.cario.gep.commons.annotations,
			org.n52.cario.gep.commons.definitions,
			org.n52.cario.gep.commons.processor,
		</org.n52.osgi.export-package>
		<org.n52.osgi.private-package></org.n52.osgi.private-package>
		<org.n52.osgi.ages-domain></org.n52.osgi.ages-domain>
	</properties>

	<build>
		<finalName>enviroCar-${project.artifactId}-${project.version}</finalName>
	</build>

	<dependencies>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.esri.geoevent.sdk</groupId>
			<artifactId>geoevent-sdk</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
		</dependency>
	</dependencies>

</project>

redpajama_set_name: RedPajamaGithub


text:
describe('lib/rules/validate-jsdoc/require-return-types', function () {
    var checker = global.checker({
        plugins: ['./lib/index']
    });

    describe('not configured', function() {

        it('should report with undefined', function() {
            global.expect(function() {
                checker.configure({requireReturnTypes: undefined});
            }).to.throws(/accepted value/i);
        });

        it('should report with an object', function() {
            global.expect(function() {
                checker.configure({requireReturnTypes: {}});
            }).to.throws(/accepted value/i);
        });

    });

    describe('with true', function() {
        checker.rules({requireReturnTypes: true});

        checker.cases([
            /* jshint ignore:start */
            {
                it: 'should not report',
                code: function() {
                    function yay(yey) {
                    }
                }
            }, {
                it: 'should report invalid @returns',
                errors: 1,
                code: function() {
                    var x = 1;
                    /**
                     * @return
                     */
                    function funcName() {
                        // dummy
                    }
                }
            }, {
                it: 'should not report valid jsdoc with object type in method',
                code: function() {
                    Cls.prototype = {
                        /**
                         * @return {{bar: number}}
                         */
                        run: function (xxx) {
                            return {};
                        }
                    };
                }
            }
            /* jshint ignore:end */
        ]);

    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:core="http://cxf.apache.org/core" xmlns:beans="http://cxf.apache.org/configuration/beans"
	xsi:schemaLocation="http://cxf.apache.org/configuration/beans http://cxf.apache.org/schemas/configuration/cxf-beans.xsd
		http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="BaseStaticLocator" name="BaseStaticLocator"
		class="org.socraticgrid.hl7.services.eps.internal.StaticTopicTree">
		<property name="rootTopic" ref="rootTopic" />
	</bean>

</beans>


text:
#ifndef _UNLOCK_INDICATOR_H
#define _UNLOCK_INDICATOR_H
#ifdef __cplusplus
extern "C" {
#endif

typedef enum {
    STATE_STARTED = 0,         /* default state */
    STATE_KEY_PRESSED = 1,     /* key was pressed, show unlock indicator */
    STATE_KEY_ACTIVE = 2,      /* a key was pressed recently, highlight part
                                   of the unlock indicator. */
    STATE_BACKSPACE_ACTIVE = 3 /* backspace was pressed recently, highlight
                                   part of the unlock indicator in red. */
} unlock_state_t;

typedef enum {
    STATE_AUTH_IDLE = 0,         /* no authenticator interaction at the moment */
    STATE_AUTH_VERIFY = 1,       /* currently verifying the password via authenticator */
    STATE_AUTH_LOCK = 2,         /* currently locking the screen */
    STATE_AUTH_WRONG = 3,        /* the password was wrong */
    STATE_I3LOCK_LOCK_FAILED = 4 /* i3lock failed to load */
} auth_state_t;

xcb_pixmap_t draw_image(uint32_t* resolution);
void redraw_screen(void);
void clear_indicator(void);

#ifdef __cplusplus
}
#endif
#endif


text:
run_spec(__dirname, ["babel", "flow", "typescript"], {
  jsxBracketSameLine: true,
});
run_spec(__dirname, ["babel", "flow", "typescript"], {
  jsxBracketSameLine: false,
});
run_spec(__dirname, ["babel", "flow", "typescript"], {
  jsxBracketSameLine: false,
  bracketSameLine: true,
});
run_spec(__dirname, ["babel", "flow", "typescript"], {
  jsxBracketSameLine: true,
  bracketSameLine: false,
});


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\MoneyBundle\Templating\Helper;

/**
 * @author Axel Vankrunkelsven <axel@digilabs.be>
 */
interface FormatMoneyHelperInterface
{
    /**
     * @param int $amount
     * @param string $currencyCode
     * @param string $localeCode
     *
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    public function formatAmount(int $amount, string $currencyCode, string $localeCode): string;
}


text:
package otelgrpc

import (
	"google.golang.org/grpc"
)

func ExampleStreamClientInterceptor() {
	_, _ = grpc.Dial("localhost", grpc.WithStreamInterceptor(StreamClientInterceptor()))
}

func ExampleUnaryClientInterceptor() {
	_, _ = grpc.Dial("localhost", grpc.WithUnaryInterceptor(UnaryClientInterceptor()))
}

func ExampleStreamServerInterceptor() {
	_ = grpc.NewServer(grpc.StreamInterceptor(StreamServerInterceptor()))
}

func ExampleUnaryServerInterceptor() {
	_ = grpc.NewServer(grpc.UnaryInterceptor(UnaryServerInterceptor()))
}


text:
package okreplay;

import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.NodeId;

class TapeConstructor extends Constructor {
  TapeConstructor() {
    yamlClassConstructors.put(NodeId.mapping, new ConstructTape());
  }

  private class ConstructTape extends ConstructMapping {
    @Override protected Object createEmptyJavaBean(MappingNode node) {
      if (YamlTape.class.equals(node.getType())) {
        return new YamlTape();
      } else {
        return super.createEmptyJavaBean(node);
      }
    }
  }
}


text:
"""pyCrypto Crypto-related routines for oauth2client."""

from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
from Crypto.Util.asn1 import DerSequence

from oauth2client._helpers import _parse_pem_key
from oauth2client._helpers import _to_bytes
from oauth2client._helpers import _urlsafe_b64decode

class PyCryptoVerifier(object):
    """Verifies the signature on a message."""

    def __init__(self, pubkey):
        """Constructor.

        Args:
            pubkey: OpenSSL.crypto.PKey (or equiv), The public key to verify
            with.
        """
        self._pubkey = pubkey

    def verify(self, message, signature):
        """Verifies a message against a signature.

        Args:
            message: string or bytes, The message to verify. If string, will be
                     encoded to bytes as utf-8.
            signature: string or bytes, The signature on the message.

        Returns:
            True if message was signed by the private key associated with the
            public key that this object was constructed with.
        """
        message = _to_bytes(message, encoding='utf-8')
        return PKCS1_v1_5.new(self._pubkey).verify(
            SHA256.new(message), signature)

    @staticmethod
    def from_string(key_pem, is_x509_cert):
        """Construct a Verified instance from a string.

        Args:
            key_pem: string, public key in PEM format.
            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
                          is expected to be an RSA key in PEM format.

        Returns:
            Verifier instance.
        """
        if is_x509_cert:
            key_pem = _to_bytes(key_pem)
            pemLines = key_pem.replace(b' ', b'').split()
            certDer = _urlsafe_b64decode(b''.join(pemLines[1:-1]))
            certSeq = DerSequence()
            certSeq.decode(certDer)
            tbsSeq = DerSequence()
            tbsSeq.decode(certSeq[0])
            pubkey = RSA.importKey(tbsSeq[6])
        else:
            pubkey = RSA.importKey(key_pem)
        return PyCryptoVerifier(pubkey)

class PyCryptoSigner(object):
    """Signs messages with a private key."""

    def __init__(self, pkey):
        """Constructor.

        Args:
            pkey, OpenSSL.crypto.PKey (or equiv), The private key to sign with.
        """
        self._key = pkey

    def sign(self, message):
        """Signs a message.

        Args:
            message: string, Message to be signed.

        Returns:
            string, The signature of the message for the given key.
        """
        message = _to_bytes(message, encoding='utf-8')
        return PKCS1_v1_5.new(self._key).sign(SHA256.new(message))

    @staticmethod
    def from_string(key, password='notasecret'):
        """Construct a Signer instance from a string.

        Args:
            key: string, private key in PEM format.
            password: string, password for private key file. Unused for PEM
                      files.

        Returns:
            Signer instance.

        Raises:
            NotImplementedError if the key isn't in PEM format.
        """
        parsed_pem_key = _parse_pem_key(key)
        if parsed_pem_key:
            pkey = RSA.importKey(parsed_pem_key)
        else:
            raise NotImplementedError(
                'PKCS12 format is not supported by the PyCrypto library. '
                'Try converting to a "PEM" '
                '(openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > '
                'privatekey.pem) '
                'or using PyOpenSSL if native code is an option.')
        return PyCryptoSigner(pkey)


text:
package org.kaazing.netx.ws.internal.ext;

import java.io.IOException;

import org.kaazing.netx.ws.internal.WsURLConnectionImpl;
import org.kaazing.netx.ws.internal.ext.flyweight.Frame;

/**
 * WebSocketContext provides the extensions the ability to participate in the message flow in both directions. WebSocketContext
 * exercises the registered hooks of all the negotiated extensions. It also provides extensions the ability to send WebSocket
 * frames from the registered hooks.
 *
 */
public abstract class WebSocketContext {
    protected final WsURLConnectionImpl connection;
    private String errorMessage;

    public WebSocketContext(WsURLConnectionImpl connection) {
        this.connection = connection;
    }

    public abstract WebSocketExtensionSpi nextExtension();

    public String getErrorMessage() {
        return errorMessage;
    }

    public void onError(String message) throws IOException {
        this.errorMessage = message;
        nextExtension().onError.accept(this);
    }

    /**
     * Exercises the onBinaryReceived hook of a negotiated extension.
     *
     * @param frame incoming BINARY frame
     * @throws IOException
     */
    public void onBinaryReceived(Frame frame) throws IOException {
        nextExtension().onBinaryReceived.accept(this, frame);
    }

    /**
     * Exercises the onCloseReceived hook of a negotiated extension.
     *
     * @param frame incoming CLOSE frame
     * @throws IOException
     */
    public void onCloseReceived(Frame frame) throws IOException {
        nextExtension().onCloseReceived.accept(this, frame);
    }

    /**
     * Exercises the onContinuationReceived hook of a negotiated extension.
     *
     * @param frame incoming CONTINUATION frame
     * @throws IOException
     */
    public void onContinuationReceived(Frame frame) throws IOException {
        nextExtension().onContinuationReceived.accept(this, frame);
    }

    /**
     * Exercises the onPingReceived hook of a negotiated extension.
     *
     * @param frame incoming PING frame
     * @throws IOException
     */
    public void onPingReceived(Frame frame) throws IOException {
        nextExtension().onPingReceived.accept(this, frame);
    }

    /**
     * Exercises the onPongReceived hook of a negotiated extension.
     *
     * @param frame incoming PONG frame
     * @throws IOException
     */
    public void onPongReceived(Frame frame) throws IOException {
        nextExtension().onPongReceived.accept(this, frame);
    }

    /**
     * Exercises the onTextReceived hook of a negotiated extension.
     *
     * @param frame incoming TEXT frame
     * @throws IOException
     */
    public void onTextReceived(Frame frame) throws IOException {
        nextExtension().onTextReceived.accept(this, frame);
    }

    /**
     * Exercises the onBinarySent hook of a negotiated extension.
     *
     * @param frame outgoing BINARY frame
     * @throws IOException
     */
    public void onBinarySent(Frame frame) throws IOException {
        nextExtension().onBinarySent.accept(this, frame);
    }

    /**
     * Exercises the onCloseSent hook of a negotiated extension.
     *
     * @param frame outgoing CLOSE frame
     * @throws IOException
     */
    public void onCloseSent(Frame frame) throws IOException {
        nextExtension().onCloseSent.accept(this, frame);
    }

    /**
     * Exercises the onContinuationSent hook of a negotiated extension.
     *
     * @param frame outgoing CONTINUATION frame
     * @throws IOException
     */
    public void onContinuationSent(Frame frame) throws IOException {
        nextExtension().onContinuationSent.accept(this, frame);
    }

    /**
     * Exercises the onPongSent hook of a negotiated extension.
     *
     * @param frame outgoing PONG frame
     * @throws IOException
     */
    public void onPongSent(Frame frame) throws IOException {
        nextExtension().onPongSent.accept(this, frame);
    }

    /**
     * Exercises the onTextSent hook of a negotiated extension.
     *
     * @param frame outgoing TEXT frame
     * @throws IOException
     */
    public void onTextSent(Frame frame) throws IOException {
        nextExtension().onTextSent.accept(this, frame);
    }

    /**
     * Writes out a BINARY frame on the wire.
     *
     * @param frame outgoing BINARY frame
     * @throws IOException
     */
    public void doSendBinary(Frame dataFrame) throws IOException {
        connection.processOutgoingFrame(dataFrame);
    }

    /**
     * Writes out a CLOSE frame on the wire.
     *
     * @param frame outgoing CLOSE frame
     * @throws IOException
     */
    public void doSendClose(Frame closeFrame) throws IOException {
        connection.processOutgoingFrame(closeFrame);
    }

    /**
     * Writes out a CONTINUATION frame on the wire.
     *
     * @param frame outgoing CONTINUATION frame
     * @throws IOException
     */
    public void doSendContinuation(Frame dataFrame) throws IOException {
        connection.processOutgoingFrame(dataFrame);
    }

    /**
     * Writes out a PONG frame on the wire.
     *
     * @param frame outgoing PONG frame
     * @throws IOException
     */
    public void doSendPong(Frame pongFrame) throws IOException {
        connection.processOutgoingFrame(pongFrame);
    }

    /**
     * Writes out a TEXT frame on the wire.
     *
     * @param frame outgoing TEXT frame
     * @throws IOException
     */
    public void doSendText(Frame dataFrame) throws IOException {
        connection.processOutgoingFrame(dataFrame);
    }
}


text:
//// Copyright (c) Source Tree Solutions, LLC. All rights reserved.
//// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
//// Author:                  Joe Audette
//// Created:                 2016-02-12
//// Last Modified:           2016-02-23
////

//namespace cloudscribe.SimpleContent.Web.ViewModels
//{
//    public class PostViewModel
//    {

//        public string Id { get; set; } = string.Empty;

//        public string Title { get; set; } = string.Empty;

//        public string Author { get; set; } = string.Empty;

//        public string Slug { get; set; } = string.Empty;

//        public string MetaDescription { get; set; } = string.Empty;

//        public string Content { get; set; } = string.Empty;

//        public bool IsPublished { get; set; } = false;

//        public string Categories { get; set; }

//        public string PubDate { get; set; } = string.Empty;

//    }
//}


text:
package org.para.distributed.slave;

import java.net.UnknownHostException;

import org.apache.log4j.Logger;
import org.para.distributed.dto.WorkerNode;
import org.para.distributed.util.SystemUtil;
import org.para.util.PropertiesUtil;

/**
 * 结点注册任务
 *
 * @author liuyan
 */
public class RegisterTask implements Runnable {

	private static Logger logger = Logger.getLogger(RegisterTask.class);

	RegisterMessageAction registerMessageAction = WorkerServer.WorkApplicationContext
			.getBean("RegisterMessageAction", RegisterMessageAction.class);

	// 等待发送注册指令的时间
	private static final long WATI_START_TIME = Long.parseLong(PropertiesUtil
			.getValue("worker.wait.heartbeat.time"));

	/**
	 * 执行结点注册逻辑
	 */
	public void execute() {

		try {

			// 先睡5秒钟
			Thread.sleep(WATI_START_TIME);
		} catch (InterruptedException e) {
			e.printStackTrace();
			logger.error("error", e);
		}

		// 获取结点硬件信息
		WorkerNode workerNode = null;
		try {
			workerNode = SystemUtil.getWorkerNode(true);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

		// 准备发送指令
		logger.info("prepare send register.....");

		// 发送注册指令
		logger.info("send register");
		registerMessageAction.sendJms(workerNode);
	}

	public void run() {

		execute();

	}
}


text:
module.exports = {
    "database": {
        "username": process.env.DB_USERNAME || "",
        "password": process.env.DB_PASSWORD || "",
        "port": process.env.DB_PORT || "27017",
        "uri": process.env.DB_URI || "localhost",
        "collection": process.env.DB_COLLECTION || "PokeData"
    },
    "shared_database": {
        "username": process.env.MLAB_USERNAME,
        "password": process.env.MLAB_PASSWORD,
        "uri": process.env.MLAB_URI,
        "collection": process.env.MLAB_COLLECTION
    },
    "twitter": {
        "consumer_key": process.env.CONSUMER_KEY,
        "consumer_secret": process.env.CONSUMER_SECRET,
        "token": process.env.ACCESS_TOKEN,
        "token_secret": process.env.ACCESS_TOKEN_SECRET
    },
    "pokemonDataSources": {
        "twitter": "TWITTER",
        "pokesniper": "POKESNIPER",
        "pokeRadar": "POKERADAR",
        "skiplagged": "SKIPLAGGED",
        "pokecrew": "POKECREW",
        "fastpokemap": "FASTPOKEMAP",
        "pokezz": "POKEZZ",
        "pokedexs": "POKEDEXS",
        "pokemap": "POKEMAP"
    },
    "sourceToFiller": {
        "twitter": "twitter",
        "rarePokemon": "rarePokemon",
        "pokeRadar": "mapService",
        "skiplagged": "mapService",
        "pokecrew": "mapService",
        "fastpokemap": "mapService",
        "pokezz": "webSocket",
        "pokedexs": "webSocket",
        "pokemap": "mapService",
        "hashPokemonGo": "hashPokemonGo",
    },
    "twitterKeyWords": 'caught #pokemongo,saw #pokemongo,found #pokemongo,appeared #pokemongo,attacked #pokemongo,pokemon catch,pokemon saw,pokemon attack,pokemon find,pokemon caught,pokemon attacked,pokemon found,pokemon appeared,#foundPokemon,#caughtPokemon,#pokemongo,a wild appeared until #pokemongo',
    "pokesniper": {
        "url": "https://pokesnipers.com/api/v1/pokemon.json?referrer=home",
        "listeningInterval": 600000 // 10 minutes in milliseconds
    },
    "pokemonSpawnTime" : 900000 ,// 15 minutes in milliseconds,
    "limit" : 1000,
    "token" : process.env.API_TOKEN || "I0TPIIpCLH8lR8iDrCMV", //please choose secret token and communicate it privately
    "server": {
        "port": "8080"
    },
    "pokeRadar": {
        "host": "www.pokeradar.io",
        "path": "/api/v1/submissions"
    },
    "skiplagged": {
        "host": "skiplagged.com",
        "path": "/api/pokemon.php"
    },
    "pokecrew": {
        "host": "api.pokecrew.com",
        "path": "/api/v1/seens"
    },
    "fastpokemap": {
        "host": "cache.fastpokemap.se",
        "path": "/"
    },
    "pokezz": {
        "host": "pokezz.com",
        "path": "/socket.io/?EIO=3&transport=websocket"
    },
    "pokedexs": {
        "host": "pokedexs.com",
        "path": "/socket.io/?EIO=3&transport=websocket"
    },
    "pokemap": {
        "host": "www.pokemap.net",
        "path": "/api/mewto.php"
    },
    "hashPokemonGoWebSocketPort": 3322
};


text:
namespace AnswerFactory
{
    using System.Collections.Generic;

    public class Aois
    {
        public string type { get; set; }
        public List<List<List<List<double>>>> coordinates { get; set; }
    }

    public class Project2
    {
        public string id { get; set; }
        public string owner { get; set; }
        public string name { get; set; }
        public string accountId { get; set; }
        public object idahoImages { get; set; }
        public List<string> aois { get; set; }
        public List<RecipeConfig> recipeConfigs { get; set; }
        public List<object> bestIdahoIds { get; set; }
        public object originalGeometries { get; set; }
        public object namedBuffers { get; set; }
        public long createDate { get; set; }
        public long updateDate { get; set; }
    }
}


text:
package com.es.service.index.core.reindexlog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.es.service.common.conf.Constants;
import com.es.service.common.type.IndexType;

/**
 *
 * 写文件的方式,如果多节点部署需要对文件挂载nfs
 *
 * @author hailin0@yeah.net
 * @createDate 2016年8月19日
 *
 */
public class IndexUpdateFileLogger implements IndexUpdateLogger {

    private static final Logger log = LoggerFactory.getLogger(IndexUpdateFileLogger.class);

    /**
     *
     */
    private final Logger LOGGER = LoggerFactory.getLogger(IndexUpdateFileLogger.class);

    /**
     * 记录索引更新信息的文件名
     */
    private final String INDEX_INFO_FILE = "index_update_%d.properties";

    /**
     * 索引最后更新时间
     */
    private final String KEY_LAST_INDEX_TIME = "lastIndexTime";

    /**
     * 索引最后更新的真实索引名
     */
    private final String KEY_LAST_INDEX_NAME = "lastindexname";

    /**
     * 索引信息文件存放目录
     */
    private final String INDEX_INFO_DIR = Constants.es_index_info_dir;

    @Override
    public Long getLastIndexTime(IndexType indexType, long specifiedTime) {
        if (specifiedTime > 0) {
            return specifiedTime;
        }
        Properties indexInfo = new Properties();
        FileInputStream in = null;
        try {
            String path = INDEX_INFO_DIR + String.format(INDEX_INFO_FILE, indexType.getIndexNo());
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            in = new FileInputStream(new File(path));
            indexInfo.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long lastIndexTime = Long.valueOf(indexInfo.getProperty(KEY_LAST_INDEX_TIME));
        if (lastIndexTime == 0) {
            throw new RuntimeException(String.format("第一次的索引更新还没有完成,索引名称:%s",
                    indexType.getIndexName()));
        }
        LOGGER.info("last index time: {}={}", KEY_LAST_INDEX_TIME + "_" + indexType.getIndexNo(),
                new Date(lastIndexTime));
        return lastIndexTime;
    }

    @Override
    public String getLastIndexName(IndexType indexType) {
        Properties indexInfo = new Properties();
        FileInputStream in = null;
        try {
            String path = INDEX_INFO_DIR + String.format(INDEX_INFO_FILE, indexType.getIndexNo());
            File file = new File(path);
            if (!file.exists()) {
                return null;
            }
            in = new FileInputStream(new File(path));
            indexInfo.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return indexInfo.getProperty(KEY_LAST_INDEX_NAME);
    }

    @Override
    public void log(IndexType indexType, String indexName, long indexTime) {
        Properties indexInfo = new Properties();
        FileOutputStream out = null;
        try {
            String path = INDEX_INFO_DIR + String.format(INDEX_INFO_FILE, indexType.getIndexNo());
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            out = new FileOutputStream(path);
            indexInfo.put(KEY_LAST_INDEX_TIME, String.valueOf(indexTime));
            indexInfo.put(KEY_LAST_INDEX_NAME, indexName);
            indexInfo.store(out, null);

            log.info("record index update log!.indexName:{},indexTime:{}", indexName, indexName);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("record index update log error!.indexName:{},indexTime:{}", indexName,
                    indexName);
        } finally {
            try {
                if(out != null){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


text:
package com.alibaba.dubbo.registry.common.domain;

import java.util.List;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;

/**
 * Route
 *
 * @author william.liangf
 */
public class Route extends Entity {

    private static final long serialVersionUID = -7630589008164140656L;

    public static final String ALL_METHOD = "*";

    // WHEN KEY

    public static final String KEY_METHOD = "method";

    public static final String KEY_CONSUMER_APPLICATION = "consumer.application";

    public static final String KEY_CONSUMER_GROUP = "consumer.cluster";

    public static final String KEY_CONSUMER_VERSION = "consumer.version";

    public static final String KEY_CONSUMER_HOST = "consumer.host";

    public static final String KEY_CONSUMER_METHODS = "consumer.methods";

    // THEN KEY

    public static final String KEY_PROVIDER_APPLICATION = "provider.application";

    public static final String KEY_PROVIDER_GROUP = "provider.cluster";

    public static final String KEY_PROVIDER_PROTOCOL = "provider.protocol";

    public static final String KEY_PROVIDER_VERSION = "provider.version";

    public static final String KEY_PROVIDER_HOST = "provider.host";

    public static final String KEY_PROVIDER_PORT = "provider.port";

    private long parentId; //默认为0

    private String name;

    private String service;

    private String rule;

    private String matchRule;

    private String filterRule;

    private int priority;

    private String username;

    private boolean enabled;

    private boolean force;

    private List<Route> children;

    public Route() {
    }

    public Route(Long id) {
        super(id);
    }

    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public long getParentId() {
        return parentId;
    }

    public void setParentId(long parentId) {
        this.parentId = parentId;
    }

    public List<Route> getChildren() {
        return children;
    }

    public void setChildren(List<Route> subRules) {
        this.children = subRules;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public boolean isForce() {
        return force;
    }

    public void setForce(boolean force) {
        this.force = force;
    }

    public String getService() {
        return service;
    }

    public void setService(String service) {
        this.service = service;
    }

    public String getRule() {
        return rule;
    }

    public void setRule(String rule) {
        this.rule = rule;
        String[] rules = rule.split(" => ");
        if (rules.length != 2) {
            throw new IllegalArgumentException("Illegal Route Condition Rule");
        }
        this.matchRule = rules[0];
        this.filterRule = rules[1];
    }

    public String getMatchRule() {
        return matchRule;
    }

    public void setMatchRule(String matchRule) {
        this.matchRule = matchRule;
    }

    public String getFilterRule() {
        return filterRule;
    }

    public void setFilterRule(String filterRule) {
        this.filterRule = filterRule;
    }

    @java.lang.Override
    public String toString() {
        return "Route [parentId=" + parentId + ", name=" + name
                + ", serviceName=" + service + ", matchRule=" + matchRule
                + ", filterRule=" + filterRule + ", priority=" + priority
                + ", username=" + username + ", enabled=" + enabled + "]";
    }

    public URL toUrl() {
        String group = null;
        String version = null;
        String path = service;
        int i = path.indexOf("/");
        if (i > 0) {
            group = path.substring(0, i);
            path = path.substring(i + 1);
        }
        i = path.lastIndexOf(":");
        if (i > 0) {
            version = path.substring(i + 1);
            path = path.substring(0, i);
        }
        return URL.valueOf(Constants.ROUTE_PROTOCOL + "://" + Constants.ANYHOST_VALUE + "/" + path
                + "?" + Constants.CATEGORY_KEY + "=" + Constants.ROUTERS_CATEGORY
                + "&router=condition&runtime=false&enabled=" + isEnabled() + "&priority=" + getPriority() + "&force=" + isForce() + "&dynamic=false"
                + "&name=" + getName() + "&" + Constants.RULE_KEY + "=" + URL.encode(getMatchRule() + " => " + getFilterRule())
                + (group == null ? "" : "&" + Constants.GROUP_KEY + "=" + group)
                + (version == null ? "" : "&" + Constants.VERSION_KEY + "=" + version));
    }

}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CountriesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('Countries', function(Blueprint $t) {
			$t->increments('id');
			$t->string('country');
			$t->string('Dial_nr');
			$t->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('Countries');
	}

}


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/app-storage/app-network-status-behavior.html">
<link rel="import" href="../../web-components/project-nice-script/modernizr.html">

<script>
  (function() {

  /** @polymerBehavior NICEV1.ProjectNiceUtilsBehavior */
    NICEV1.ProjectNiceUtilsBehaviorImpl = {
      properties: {
        version: {
          type: String,
          readOnly: true,
          value: function() { return this._version; }
        }
      },

      get _version() {
        return 'v1'
      },

      get _todayUTC() {
        return firebase ? firebase.database.ServerValue.TIMESTAMP : Date.now();
      },

      _forceZero: function(obj, zeroValue) {
        if (zeroValue === null || zeroValue === undefined) zeroValue = false;
        return typeof obj === 'object' && this._isEmpty(obj) ? zeroValue : obj;
      },

      _isEmpty: function(obj) {
        for(var prop in obj) {
          if(obj.hasOwnProperty(prop))
            return false;
        }
        return JSON.stringify(obj) === JSON.stringify({});
      },

      _trimText: function(text, length) {
        var l = length ? length : 35;
        if (typeof text === 'string') {
          return text.length >= l ? text.substring(0, l).trim() + '...' : text;
        }
      },

      _capitalizeFirstLetter: function(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
      },

      _renderDate: function(d) {
        var date = d;
        if (typeof d === 'object' && d.value) {
          date = d.value;
        }
        var nd = new Date(date);
        return nd.toLocaleDateString() + ' - ' + nd.toLocaleTimeString();
      },

      _returnArrayElement: function(array, index) {
        return array ? array[index] : null;
      },

      _returnArrayElementAttribute: function(array, index, key) {
        return array[index] ? array[index][key] : null;
      },

      _showMessage: function(message, err) {
        // if (this.$$('#toaster')) {
        //   this.$$('#toaster').show(message);
        // } else if (!err) {
        //   console.log(message);
        // }

        NICEV1.Elements.Template.$.toast.showMessage(message);

        if (err) {
          if (console.error) {
            console.error(message);
          } else {
            console.log(message);
          }
        }
      },

      _catchError: function(err) {
        if (window.Raven) {
          if (err.detail) {
            Raven.captureMessage("Error event", err.detail);
          } else {
            Raven.captureException(err);
          }
        }

        var error = err.detail ? err.detail : err;
        this._showMessage('Error: ' +  error.message, true);
      },

      _textToUrl: function(text) {
        return encodeURI(text);
      },

      _thisUrl: function() {
        return window.location.href;
      },

      _windowSize: function() {
        var width = 0;
        var height = 0;
        if (window && document) {
          if ( typeof window.innerWidth === 'number' ) {
            // Non-IE
            width = window.innerWidth;
            height = window.innerHeight;
          } else if ( document.documentElement && (
            document.documentElement.clientWidth ||
            document.documentElement.clientHeight )) {
            // IE 6+ in 'standards compliant mode'
            width = document.documentElement.clientWidth;
            height = document.documentElement.clientHeight;
          } else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            // IE 4 compatible
            width = document.body.clientWidth;
            height = document.body.clientHeight;
          }
        }

        return {width: width, height: height};
      },

      _heightNodeChanged: function(e, node) {
        var height;
        if (e.indexOf('vh')) {
          if (Modernizr && Modernizr.cssvhunit) {
            height = e;
          } else {
            height = ((parseFloat(e.replace(/vh/g, ''))/100) * this._windowSize().height) + 'px';
          }
        } else if (e.indexOf('px')) {
          height = e;
        } else {
          height = e + 'px';
        }

        console.log(height)

        node.style.height = height;
      },
    }

    NICEV1.ProjectNiceUtilsBehavior = [
      Polymer.AppNetworkStatusBehavior,
      NICEV1.ProjectNiceUtilsBehaviorImpl
    ]
  })();
</script>


text:
<?php
class GridFieldExportButtonTest extends SapphireTest {

	protected $list;

	protected $gridField;

	protected $form;

	protected static $fixture_file = 'GridFieldExportButtonTest.yml';

	protected $extraDataObjects = array(
		'GridFieldExportButtonTest_Team'
	);

	public function setUp() {
		parent::setUp();

		$this->list = new DataList('GridFieldExportButtonTest_Team');
		$this->list = $this->list->sort('Name');
		$config = GridFieldConfig::create()->addComponent(new GridFieldExportButton());
		$this->gridField = new GridField('testfield', 'testfield', $this->list, $config);
	}

	public function testGenerateFileDataBasicFields() {
		$button = new GridFieldExportButton();
		$button->setExportColumns(array('Name' => 'My Name'));

		$this->assertEquals(
			"\"My Name\"\n\"Test\"\n\"Test2\"\n",
			$button->generateExportFileData($this->gridField)
		);
	}

	public function testGenerateFileDataAnonymousFunctionField() {
		$button = new GridFieldExportButton();
		$button->setExportColumns(array(
			'Name' => 'Name',
			'City' => function($obj) {
				return $obj->getValue() . ' city';
			}
		));

		$this->assertEquals(
			"\"Name\",\"City\"\n\"Test\",\"City city\"\n\"Test2\",\"City2 city\"\n",
			$button->generateExportFileData($this->gridField)
		);
	}

	public function testBuiltInFunctionNameCanBeUsedAsHeader() {
		$button = new GridFieldExportButton();
		$button->setExportColumns(array(
			'Name' => 'Name',
			'City' => 'strtolower'
		));

		$this->assertEquals(
			"\"Name\",\"strtolower\"\n\"Test\",\"City\"\n\"Test2\",\"City2\"\n",
			$button->generateExportFileData($this->gridField)
		);
	}

	public function testNoCsvHeaders() {
		$button = new GridFieldExportButton();
		$button->setExportColumns(array(
			'Name' => 'Name',
			'City' => 'City'
		));
		$button->setCsvHasHeader(false);

		$this->assertEquals(
			"\"Test\",\"City\"\n\"Test2\",\"City2\"\n",
			$button->generateExportFileData($this->gridField)
		);
	}

}
class GridFieldExportButtonTest_Team extends DataObject implements TestOnly {

	private static $db = array(
		'Name' => 'Varchar',
		'City' => 'Varchar'
	);

	public function canView($member = null) {
		return true;
	}

}


text:
package org.hisp.dhis.datastatistics;

import org.hisp.dhis.analytics.SortOrder;

import org.hisp.dhis.chart.Chart;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.dashboard.Dashboard;
import org.hisp.dhis.datavalue.DataValueService;
import org.hisp.dhis.eventchart.EventChart;
import org.hisp.dhis.eventreport.EventReport;
import org.hisp.dhis.indicator.Indicator;
import org.hisp.dhis.reporttable.ReportTable;
import org.hisp.dhis.user.User;
import org.hisp.dhis.user.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Yrjan A. F. Fraschetti
 * @author Julie Hill Roa
 */
@Transactional
public class DefaultDataStatisticsService
    implements DataStatisticsService
{
    @Autowired
    private DataStatisticsStore dataStatisticsStore;

    @Autowired
    private DataStatisticsEventStore dataStatisticsEventStore;

    @Autowired
    private UserService userService;

    @Autowired
    private IdentifiableObjectManager idObjectManager;

    @Autowired
    private DataValueService dataValueService;

    // -------------------------------------------------------------------------
    // DataStatisticsService implementation
    // -------------------------------------------------------------------------

    @Override
    public int addEvent( DataStatisticsEvent event )
    {
        dataStatisticsEventStore.save( event );

        return event.getId();
    }

    @Override
    public List<AggregatedStatistics> getReports( Date startDate, Date endDate, EventInterval eventInterval )
    {
        return dataStatisticsStore.getSnapshotsInInterval( eventInterval, startDate, endDate );
    }

    @Override
    public DataStatistics getDataStatisticsSnapshot( Date day )
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime( day );
        cal.add( Calendar.DATE, -1 );
        Date startDate = cal.getTime();
        Date now = new Date();
        long diff = now.getTime() - startDate.getTime();
        int days = (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);

        double savedMaps = idObjectManager.getCountByCreated( org.hisp.dhis.mapping.Map.class, startDate );
        double savedCharts = idObjectManager.getCountByCreated( Chart.class, startDate );
        double savedReportTables = idObjectManager.getCountByCreated( ReportTable.class, startDate );
        double savedEventReports = idObjectManager.getCountByCreated( EventReport.class, startDate );
        double savedEventCharts = idObjectManager.getCountByCreated( EventChart.class, startDate );
        double savedDashboards = idObjectManager.getCountByCreated( Dashboard.class, startDate );
        double savedIndicators = idObjectManager.getCountByCreated( Indicator.class, startDate );
        double savedDataValues = dataValueService.getDataValueCount( days );
        int activeUsers = userService.getActiveUsersCount( 1 );
        int users = idObjectManager.getCount( User.class );

        Map<DataStatisticsEventType, Double> eventCountMap = dataStatisticsEventStore.getDataStatisticsEventCount( startDate, day );

        DataStatistics dataStatistics = new DataStatistics(
            eventCountMap.get( DataStatisticsEventType.MAP_VIEW ),
            eventCountMap.get( DataStatisticsEventType.CHART_VIEW ),
            eventCountMap.get( DataStatisticsEventType.REPORT_TABLE_VIEW ),
            eventCountMap.get( DataStatisticsEventType.EVENT_REPORT_VIEW ),
            eventCountMap.get( DataStatisticsEventType.EVENT_CHART_VIEW ),
            eventCountMap.get( DataStatisticsEventType.DASHBOARD_VIEW ),
            eventCountMap.get( DataStatisticsEventType.DATA_SET_REPORT_VIEW ),
            eventCountMap.get( DataStatisticsEventType.TOTAL_VIEW ),
            savedMaps, savedCharts, savedReportTables, savedEventReports,
            savedEventCharts, savedDashboards, savedIndicators, savedDataValues, activeUsers, users );

        return dataStatistics;
    }

    @Override
    public int saveDataStatistics( DataStatistics dataStatistics )
    {
        dataStatisticsStore.save( dataStatistics );

        return dataStatistics.getId();
    }

    @Override
    public int saveDataStatisticsSnapshot()
    {
        return saveDataStatistics( getDataStatisticsSnapshot( new Date() ) );
    }

    @Override
    public List<FavoriteStatistics> getTopFavorites( DataStatisticsEventType eventType, int pageSize, SortOrder sortOrder, String username )
    {
        return dataStatisticsEventStore.getFavoritesData( eventType, pageSize, sortOrder, username );
    }

    @Override
    public FavoriteStatistics getFavoriteStatistics( String uid )
    {
        return dataStatisticsEventStore.getFavoriteStatistics( uid );
    }
}


text:
  {% include "search.svg" %}
  <input class="c-field__input top-bar__search-input" type="search" name="q" placeholder="Поиск по сайту"/>
  {% render "@button", { label: "Найти на сайте", mods: ["secondary","small"], submit: true, customClassList: "top-bar__search-btn" } %}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gbif.dwc.record;

import org.gbif.dwc.terms.Term;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class StarRecordImpl implements StarRecord {

  private Record core;
  private final Map<Term, List<Record>> extensions;

  public StarRecordImpl(Collection<Term> extensions) {
    this.extensions = new HashMap<Term, List<Record>>();
    for (Term rowType : extensions) {
      this.extensions.put(rowType, new ArrayList<Record>());
    }
  }

  public void addRecord(Term rowType, Record record) {
    if (!extensions.containsKey(rowType)) {
      throw new IllegalArgumentException("RowType not supported");
    }
    extensions.get(rowType).add(record);
  }

  /**
   * @return the core record
   */
  @Override
  public Record core() {
    return core;
  }

  @Override
  public boolean hasExtension(Term rowType) {
    return extensions.containsKey(rowType) && !extensions.get(rowType).isEmpty();
  }

  /**
   * Retrieves all extension records of a specific extension.
   * If the requested extension is not mapped null will be returned.
   *
   * @param rowType the Term representing the rowType
   *
   * @return possibly empty list of extension record or null if extension is not mapped at all
   */
  @Override
  public List<Record> extension(Term rowType) {
    return extensions.get(rowType);
  }

  /**
   * Retrieves all extension records related to the core record across all extensions as a map.
   */
  @Override
  public Map<Term, List<Record>> extensions() {
    return extensions;
  }

  /**
   * Get a new iterator over all extension records, no matter to which extension they belong.
   *
   * @return the ExtensionRecord iterator, reusing the same instance for each call
   */
  @Override
  public Iterator<Record> iterator() {
    List<Record> records = new ArrayList<>();
    for (List<Record> recs : extensions.values()) {
      records.addAll(recs);
    }
    return records.iterator();
  }

  public void newCoreRecord(Record core) {
    this.core = core;
    for (List<Record> lists : extensions.values()) {
      lists.clear();
    }
  }

  /**
   * @return set of extension rowTypes associated with this star record
   */
  @Override
  public Set<Term> rowTypes() {
    return extensions.keySet();
  }

  /**
   * @return the number of associated extension records across all rowTypes
   */
  @Override
  public int size() {
    int x = 0;
    for (List<Record> recs : extensions.values()) {
      x += recs.size();
    }
    return x;
  }

  @Override
  public String toString() {
    return "StarRecord with core "+core.toString()+" and extensions "+extensions;
  }
}


text:
namespace {

// Different platforms need slightly different constants to look good.
#if defined(OS_LINUX) && !defined(TOOLKIT_VIEWS)
const float kTextSize = 9.0;
const int kBottomMarginBrowserAction = 0;
const int kBottomMarginPageAction = 2;
const int kPadding = 2;
const int kTopTextPadding = 0;
#elif defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
const float kTextSize = 8.0;
const int kBottomMarginBrowserAction = 5;
const int kBottomMarginPageAction = 2;
const int kPadding = 2;
const int kTopTextPadding = 1;
#elif defined(OS_MACOSX)
const float kTextSize = 9.0;
const int kBottomMarginBrowserAction = 5;
const int kBottomMarginPageAction = 2;
const int kPadding = 2;
const int kTopTextPadding = 0;
#else
const float kTextSize = 10;
const int kBottomMarginBrowserAction = 5;
const int kBottomMarginPageAction = 2;
const int kPadding = 2;
// The padding between the top of the badge and the top of the text.
const int kTopTextPadding = -1;
#endif

const int kBadgeHeight = 11;
const int kMaxTextWidth = 23;
// The minimum width for center-aligning the badge.
const int kCenterAlignThreshold = 20;

class GetAttentionImageSource : public gfx::ImageSkiaSource {
 public:
  explicit GetAttentionImageSource(const gfx::ImageSkia& icon)
      : icon_(icon) {}

  // gfx::ImageSkiaSource overrides:
  virtual gfx::ImageSkiaRep GetImageForScale(ui::ScaleFactor scale_factor)
      OVERRIDE {
    gfx::ImageSkiaRep icon_rep = icon_.GetRepresentation(scale_factor);
    color_utils::HSL shift = {-1, 0, 0.5};
    return gfx::ImageSkiaRep(
        SkBitmapOperations::CreateHSLShiftedBitmap(icon_rep.sk_bitmap(), shift),
        icon_rep.scale_factor());
  }

 private:
  const gfx::ImageSkia icon_;
};

}  // namespace

// TODO(tbarzic): Merge AnimationIconImageSource and IconAnimation together.
// Source for painting animated skia image.
class AnimatedIconImageSource : public gfx::ImageSkiaSource {
 public:
  AnimatedIconImageSource(
      const gfx::ImageSkia& image,
      base::WeakPtr<ExtensionAction::IconAnimation> animation)
      : image_(image),
        animation_(animation) {
  }

 private:
  virtual ~AnimatedIconImageSource() {}

  virtual gfx::ImageSkiaRep GetImageForScale(ui::ScaleFactor scale) OVERRIDE {
    gfx::ImageSkiaRep original_rep = image_.GetRepresentation(scale);
    if (!animation_)
      return original_rep;

    // Original representation's scale factor may be different from scale
    // factor passed to this method. We want to use the former (since we are
    // using bitmap for that scale).
    return gfx::ImageSkiaRep(
        animation_->Apply(original_rep.sk_bitmap()),
        original_rep.scale_factor());
  }

  gfx::ImageSkia image_;
  base::WeakPtr<ExtensionAction::IconAnimation> animation_;

  DISALLOW_COPY_AND_ASSIGN(AnimatedIconImageSource);
};

// CanvasImageSource for creating browser action icon with a badge.
class ExtensionAction::IconWithBadgeImageSource
    : public gfx::CanvasImageSource {
 public:
  IconWithBadgeImageSource(const gfx::ImageSkia& icon,
                           const gfx::Size& spacing,
                           const std::string& text,
                           const SkColor& text_color,
                           const SkColor& background_color,
                           extensions::Extension::ActionInfo::Type action_type)
      : gfx::CanvasImageSource(icon.size(), false),
        icon_(icon),
        spacing_(spacing),
        text_(text),
        text_color_(text_color),
        background_color_(background_color),
        action_type_(action_type) {
  }

  virtual ~IconWithBadgeImageSource() {}

 private:
  virtual void Draw(gfx::Canvas* canvas) OVERRIDE {
    canvas->DrawImageInt(icon_, 0, 0, SkPaint());

    gfx::Rect bounds(size_.width() + spacing_.width(),
                     size_.height() + spacing_.height());

    // Draw a badge on the provided browser action icon's canvas.
    ExtensionAction::DoPaintBadge(canvas, bounds, text_, text_color_,
                                  background_color_, size_.width(),
                                  action_type_);
  }

  // Browser action icon image.
  gfx::ImageSkia icon_;
  // Extra spacing for badge compared to icon bounds.
  gfx::Size spacing_;
  // Text to be displayed on the badge.
  std::string text_;
  // Color of badge text.
  SkColor text_color_;
  // Color of the badge.
  SkColor background_color_;
  // Type of extension action this is for.
  extensions::Extension::ActionInfo::Type action_type_;

  DISALLOW_COPY_AND_ASSIGN(IconWithBadgeImageSource);
};

const int ExtensionAction::kDefaultTabId = -1;
// 100ms animation at 50fps (so 5 animation frames in total).
const int kIconFadeInDurationMs = 100;
const int kIconFadeInFramesPerSecond = 50;

ExtensionAction::IconAnimation::IconAnimation()
    : ui::LinearAnimation(kIconFadeInDurationMs, kIconFadeInFramesPerSecond,
                          NULL),
      weak_ptr_factory_(this) {}

ExtensionAction::IconAnimation::~IconAnimation() {
  // Make sure observers don't access *this after its destructor has started.
  weak_ptr_factory_.InvalidateWeakPtrs();
  // In case the animation was destroyed before it finished (likely due to
  // delays in timer scheduling), make sure it's fully visible.
  FOR_EACH_OBSERVER(Observer, observers_, OnIconChanged());
}

const SkBitmap& ExtensionAction::IconAnimation::Apply(
    const SkBitmap& icon) const {
  DCHECK_GT(icon.width(), 0);
  DCHECK_GT(icon.height(), 0);

  if (!device_.get() ||
      (device_->width() != icon.width()) ||
      (device_->height() != icon.height())) {
    device_.reset(new SkDevice(
      SkBitmap::kARGB_8888_Config, icon.width(), icon.height(), true));
  }

  SkCanvas canvas(device_.get());
  canvas.clear(SK_ColorWHITE);
  SkPaint paint;
  paint.setAlpha(CurrentValueBetween(0, 255));
  canvas.drawBitmap(icon, 0, 0, &paint);
  return device_->accessBitmap(false);
}

base::WeakPtr<ExtensionAction::IconAnimation>
ExtensionAction::IconAnimation::AsWeakPtr() {
  return weak_ptr_factory_.GetWeakPtr();
}

void ExtensionAction::IconAnimation::AddObserver(
    ExtensionAction::IconAnimation::Observer* observer) {
  observers_.AddObserver(observer);
}

void ExtensionAction::IconAnimation::RemoveObserver(
    ExtensionAction::IconAnimation::Observer* observer) {
  observers_.RemoveObserver(observer);
}

void ExtensionAction::IconAnimation::AnimateToState(double state) {
  FOR_EACH_OBSERVER(Observer, observers_, OnIconChanged());
}

ExtensionAction::IconAnimation::ScopedObserver::ScopedObserver(
    const base::WeakPtr<IconAnimation>& icon_animation,
    Observer* observer)
    : icon_animation_(icon_animation),
      observer_(observer) {
  if (icon_animation.get())
    icon_animation->AddObserver(observer);
}

ExtensionAction::IconAnimation::ScopedObserver::~ScopedObserver() {
  if (icon_animation_.get())
    icon_animation_->RemoveObserver(observer_);
}

ExtensionAction::ExtensionAction(
    const std::string& extension_id,
    extensions::Extension::ActionInfo::Type action_type,
    const extensions::Extension::ActionInfo& manifest_data)
    : extension_id_(extension_id),
      action_type_(action_type),
      has_changed_(false) {
  // Page/script actions are hidden/disabled by default, and browser actions are
  // visible/enabled by default.
  SetAppearance(kDefaultTabId,
                action_type == extensions::Extension::ActionInfo::TYPE_BROWSER ?
                ExtensionAction::ACTIVE : ExtensionAction::INVISIBLE);
  SetTitle(kDefaultTabId, manifest_data.default_title);
  SetPopupUrl(kDefaultTabId, manifest_data.default_popup_url);
  if (!manifest_data.default_icon.empty()) {
    set_default_icon(make_scoped_ptr(new ExtensionIconSet(
        manifest_data.default_icon)));
  }
  set_id(manifest_data.id);
}

ExtensionAction::~ExtensionAction() {
}

scoped_ptr<ExtensionAction> ExtensionAction::CopyForTest() const {
  scoped_ptr<ExtensionAction> copy(
      new ExtensionAction(extension_id_, action_type_,
                          extensions::Extension::ActionInfo()));
  copy->popup_url_ = popup_url_;
  copy->title_ = title_;
  copy->icon_ = icon_;
  copy->badge_text_ = badge_text_;
  copy->badge_background_color_ = badge_background_color_;
  copy->badge_text_color_ = badge_text_color_;
  copy->appearance_ = appearance_;
  copy->icon_animation_ = icon_animation_;
  copy->id_ = id_;

  if (default_icon_.get())
    copy->default_icon_.reset(new ExtensionIconSet(*default_icon_));

  return copy.Pass();
}

// static
int ExtensionAction::GetIconSizeForType(
    extensions::Extension::ActionInfo::Type type) {
  switch (type) {
    case extensions::Extension::ActionInfo::TYPE_BROWSER:
    case extensions::Extension::ActionInfo::TYPE_PAGE:
      return extension_misc::EXTENSION_ICON_ACTION;
    case extensions::Extension::ActionInfo::TYPE_SCRIPT_BADGE:
      return extension_misc::EXTENSION_ICON_BITTY;
    default:
      NOTREACHED();
      return 0;
  }
}

void ExtensionAction::SetPopupUrl(int tab_id, const GURL& url) {
  // We store |url| even if it is empty, rather than removing a URL from the
  // map.  If an extension has a default popup, and removes it for a tab via
  // the API, we must remember that there is no popup for that specific tab.
  // If we removed the tab's URL, GetPopupURL would incorrectly return the
  // default URL.
  SetValue(&popup_url_, tab_id, url);
}

bool ExtensionAction::HasPopup(int tab_id) const {
  return !GetPopupUrl(tab_id).is_empty();
}

GURL ExtensionAction::GetPopupUrl(int tab_id) const {
  return GetValue(&popup_url_, tab_id);
}

void ExtensionAction::SetIcon(int tab_id, const gfx::Image& image) {
  SetValue(&icon_, tab_id, image.AsImageSkia());
}

gfx::Image ExtensionAction::ApplyAttentionAndAnimation(
    const gfx::ImageSkia& original_icon,
    int tab_id) const {
  gfx::ImageSkia icon = original_icon;
  if (GetValue(&appearance_, tab_id) == WANTS_ATTENTION)
    icon = gfx::ImageSkia(new GetAttentionImageSource(icon), icon.size());

  return gfx::Image(ApplyIconAnimation(tab_id, icon));
}

gfx::ImageSkia ExtensionAction::GetExplicitlySetIcon(int tab_id) const {
  return GetValue(&icon_, tab_id);
}

bool ExtensionAction::SetAppearance(int tab_id, Appearance new_appearance) {
  const Appearance old_appearance = GetValue(&appearance_, tab_id);

  if (old_appearance == new_appearance)
    return false;

  SetValue(&appearance_, tab_id, new_appearance);

  // When showing a script badge for the first time on a web page, fade it in.
  // Other transitions happen instantly.
  if (old_appearance == INVISIBLE && tab_id != kDefaultTabId &&
      action_type_ == extensions::Extension::ActionInfo::TYPE_SCRIPT_BADGE) {
    RunIconAnimation(tab_id);
  }

  return true;
}

void ExtensionAction::ClearAllValuesForTab(int tab_id) {
  popup_url_.erase(tab_id);
  title_.erase(tab_id);
  icon_.erase(tab_id);
  badge_text_.erase(tab_id);
  badge_text_color_.erase(tab_id);
  badge_background_color_.erase(tab_id);
  appearance_.erase(tab_id);
  icon_animation_.erase(tab_id);
}

void ExtensionAction::PaintBadge(gfx::Canvas* canvas,
                                 const gfx::Rect& bounds,
                                 int tab_id) {
  ExtensionAction::DoPaintBadge(
      canvas,
      bounds,
      GetBadgeText(tab_id),
      GetBadgeTextColor(tab_id),
      GetBadgeBackgroundColor(tab_id),
      GetIconWidth(tab_id),
      action_type());
}

gfx::ImageSkia ExtensionAction::GetIconWithBadge(
    const gfx::ImageSkia& icon,
    int tab_id,
    const gfx::Size& spacing) const {
  if (tab_id < 0)
    return icon;

  return gfx::ImageSkia(
      new IconWithBadgeImageSource(icon,
                                   spacing,
                                   GetBadgeText(tab_id),
                                   GetBadgeTextColor(tab_id),
                                   GetBadgeBackgroundColor(tab_id),
                                   action_type()),
     icon.size());
}

// Determines which icon would be returned by |GetIcon|, and returns its width.
int ExtensionAction::GetIconWidth(int tab_id) const {
  // If icon has been set, return its width.
  gfx::ImageSkia icon = GetValue(&icon_, tab_id);
  if (!icon.isNull())
    return icon.width();
  // If there is a default icon, the icon width will be set depending on our
  // action type.
  if (default_icon_.get())
    return GetIconSizeForType(action_type());

  // If no icon has been set and there is no default icon, we need favicon
  // width.
  return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
          IDR_EXTENSIONS_FAVICON).ToImageSkia()->width();
}

// static
void ExtensionAction::DoPaintBadge(
    gfx::Canvas* canvas,
    const gfx::Rect& bounds,
    const std::string& text,
    const SkColor& text_color_in,
    const SkColor& background_color_in,
    int icon_width,
    extensions::Extension::ActionInfo::Type action_type) {
  if (text.empty())
    return;

  SkColor text_color = text_color_in;
  if (SkColorGetA(text_color_in) == 0x00)
    text_color = SK_ColorWHITE;

  SkColor background_color = background_color_in;
  if (SkColorGetA(background_color_in) == 0x00)
      background_color = SkColorSetARGB(255, 218, 0, 24);

  canvas->Save();

  SkPaint* text_paint = badge_util::GetBadgeTextPaintSingleton();
  text_paint->setTextSize(SkFloatToScalar(kTextSize));
  text_paint->setColor(text_color);

  // Calculate text width. We clamp it to a max size.
  SkScalar sk_text_width = text_paint->measureText(text.c_str(), text.size());
  int text_width = std::min(kMaxTextWidth, SkScalarFloor(sk_text_width));

  // Calculate badge size. It is clamped to a min width just because it looks
  // silly if it is too skinny.
  int badge_width = text_width + kPadding * 2;
  // Force the pixel width of badge to be either odd (if the icon width is odd)
  // or even otherwise. If there is a mismatch you get http://crbug.com/26400.
  if (icon_width != 0 && (badge_width % 2 != icon_width % 2))
    badge_width += 1;
  badge_width = std::max(kBadgeHeight, badge_width);

  // Paint the badge background color in the right location. It is usually
  // right-aligned, but it can also be center-aligned if it is large.
  int rect_height = kBadgeHeight;
  int bottom_margin =
      action_type == extensions::Extension::ActionInfo::TYPE_BROWSER ?
      kBottomMarginBrowserAction : kBottomMarginPageAction;
  int rect_y = bounds.bottom() - bottom_margin - kBadgeHeight;
  int rect_width = badge_width;
  int rect_x = (badge_width >= kCenterAlignThreshold) ?
      (bounds.x() + bounds.width() - badge_width) / 2 :
      bounds.right() - badge_width;
  gfx::Rect rect(rect_x, rect_y, rect_width, rect_height);

  SkPaint rect_paint;
  rect_paint.setStyle(SkPaint::kFill_Style);
  rect_paint.setAntiAlias(true);
  rect_paint.setColor(background_color);
  canvas->DrawRoundRect(rect, 2, rect_paint);

  // Overlay the gradient. It is stretchy, so we do this in three parts.
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  gfx::ImageSkia* gradient_left = rb.GetImageSkiaNamed(
      IDR_BROWSER_ACTION_BADGE_LEFT);
  gfx::ImageSkia* gradient_right = rb.GetImageSkiaNamed(
      IDR_BROWSER_ACTION_BADGE_RIGHT);
  gfx::ImageSkia* gradient_center = rb.GetImageSkiaNamed(
      IDR_BROWSER_ACTION_BADGE_CENTER);

  canvas->DrawImageInt(*gradient_left, rect.x(), rect.y());
  canvas->TileImageInt(*gradient_center,
      rect.x() + gradient_left->width(),
      rect.y(),
      rect.width() - gradient_left->width() - gradient_right->width(),
      rect.height());
  canvas->DrawImageInt(*gradient_right,
      rect.right() - gradient_right->width(), rect.y());

  // Finally, draw the text centered within the badge. We set a clip in case the
  // text was too large.
  rect.Inset(kPadding, 0);
  canvas->ClipRect(rect);
  canvas->sk_canvas()->drawText(
      text.c_str(), text.size(),
      SkFloatToScalar(rect.x() +
                      static_cast<float>(rect.width() - text_width) / 2),
      SkFloatToScalar(rect.y() + kTextSize + kTopTextPadding),
      *text_paint);
  canvas->Restore();
}

base::WeakPtr<ExtensionAction::IconAnimation> ExtensionAction::GetIconAnimation(
    int tab_id) const {
  std::map<int, base::WeakPtr<IconAnimation> >::iterator it =
      icon_animation_.find(tab_id);
  if (it == icon_animation_.end())
    return base::WeakPtr<ExtensionAction::IconAnimation>();
  if (it->second)
    return it->second;

  // Take this opportunity to remove all the NULL IconAnimations from
  // icon_animation_.
  icon_animation_.erase(it);
  for (it = icon_animation_.begin(); it != icon_animation_.end();) {
    if (it->second) {
      ++it;
    } else {
      // The WeakPtr is null; remove it from the map.
      icon_animation_.erase(it++);
    }
  }
  return base::WeakPtr<ExtensionAction::IconAnimation>();
}

gfx::ImageSkia ExtensionAction::ApplyIconAnimation(
    int tab_id,
    const gfx::ImageSkia& icon) const {
  base::WeakPtr<IconAnimation> animation = GetIconAnimation(tab_id);
  if (animation == NULL)
    return icon;

  return gfx::ImageSkia(new AnimatedIconImageSource(icon, animation),
                        icon.size());
}

namespace {
// Used to create a Callback owning an IconAnimation.
void DestroyIconAnimation(scoped_ptr<ExtensionAction::IconAnimation>) {}
}
void ExtensionAction::RunIconAnimation(int tab_id) {
  scoped_ptr<IconAnimation> icon_animation(new IconAnimation());
  icon_animation_[tab_id] = icon_animation->AsWeakPtr();
  icon_animation->Start();
  // After the icon is finished fading in (plus some padding to handle random
  // timer delays), destroy it. We use a delayed task so that the Animation is
  // deleted even if it hasn't finished by the time the MessageLoop is
  // destroyed.
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&DestroyIconAnimation, base::Passed(icon_animation.Pass())),
      base::TimeDelta::FromMilliseconds(kIconFadeInDurationMs * 2));
}


text:
package cgeo.geocaching.filter;

import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.R;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.Sensors;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.NonNull;

import android.util.Pair;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

public class MultiListingFilter extends AbstractFilter {

    private static final double MAX_DISTANCE_KILOMETERS = 0.02;

    protected MultiListingFilter() {
        super(R.string.caches_filter_multi_listing);
    }

    @Override
    public boolean accepts(@NonNull final Geocache cache) {
        // not used in this filter
        return false;
    }

    @Override
    public void filter(@NonNull final List<Geocache> list) {
        final List<Pair<Float, Geocache>> sorted = getDistanceSortedCaches(list);

        final HashSet<Geocache> filtered = new HashSet<>();
        for (int i = 0; i < sorted.size(); i++) {
            final Geocache current = sorted.get(i).second;
            for (int j = i + 1; j < sorted.size(); j++) {
                final Geocache next = sorted.get(j).second;
                if (current.getCoords().distanceTo(next) < MAX_DISTANCE_KILOMETERS && haveSimilarNames(current, next)) {
                    if (ConnectorFactory.getConnector(current) != ConnectorFactory.getConnector(next) && current.isFound() != next.isFound()) {
                        filtered.add(current);
                        filtered.add(next);
                    }
                }
                else {
                    break;
                }
            }
        }
        list.retainAll(filtered);
    }

    private static boolean haveSimilarNames(final Geocache current, final Geocache next) {
        return StringUtils.getLevenshteinDistance(current.getName(), next.getName()) < 3;
    }

    private static List<Pair<Float, Geocache>> getDistanceSortedCaches(final List<Geocache> list) {
        final GeoData geo = Sensors.getInstance().currentGeo();
        final Geopoint currentPos = new Geopoint(geo);
        final List<Pair<Float, Geocache>> sorted = new ArrayList<>();
        for (final Geocache cache : list) {
            final Geopoint coords = cache.getCoords();
            if (coords != null) {
                final float distance = currentPos.distanceTo(coords);
                sorted.add(new Pair<>(distance, cache));
            }
        }
        Collections.sort(sorted, new Comparator<Pair<Float, Geocache>>() {

            @Override
            public int compare(final Pair<Float, Geocache> lhs, final Pair<Float, Geocache> rhs) {
                return Float.compare(lhs.first, rhs.first);
            }
        });
        return sorted;
    }

}


text:
package opus

import (
	ac "github.com/dh1tw/remoteAudio/audiocodec"
	opus "gopkg.in/hraban/opus.v2"
)

// OpusDecoder is the data structure which holds internal values
// for the decoder.
type OpusDecoder struct {
	name    string
	options Options
	decoder *opus.Decoder
}

// NewOpusDecoder is the constructor method for an Opus decoder.
func NewOpusDecoder(opts ...Option) (*OpusDecoder, error) {

	oc := &OpusDecoder{
		name: "opus",
		options: Options{
			Samplerate: 48000,
			Channels:   2,
		},
	}

	for _, option := range opts {
		option(&oc.options)
	}

	decoder, err := opus.NewDecoder(int(oc.options.Samplerate),
		oc.options.Channels)

	if err != nil {
		return nil, err
	}

	oc.decoder = decoder
	return oc, nil
}

// Name returns the name of the audio codec
func (oc *OpusDecoder) Name() string {
	return oc.name
}

// Options returns a copy of the codec's options
func (oc *OpusDecoder) Options() Options {
	return oc.options
}

// Decode encoded Opus data into the supplied float32 buffer. On success, the
// number of samples written into the buffer will be returned.
func (oc *OpusDecoder) Decode(data []byte, pcm []float32, opts ...ac.Options) (int, error) {
	return oc.decoder.DecodeFloat32(data, pcm)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright Duke Comprehensive Cancer Center and SemanticBits

 Distributed under the OSI-approved BSD 3-Clause License.
 See http://ncip.github.com/c3pr/LICENSE.txt for details.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:cxf="http://cxf.apache.org/core"
	xsi:schemaLocation="
	http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

	<cxf:bus>
		<cxf:features>
			<cxf:logging />
		</cxf:features>
	</cxf:bus>

	<!--
		"localhost" and "dkrylov-PC" below must match CN names on
		corresponding SSL certificates. Won't work otherwise.
	-->
	<jaxws:client id="subjectManagementClient"
		serviceClass="edu.duke.cabig.c3pr.webservice.subjectmanagement.SubjectManagement"
		wsdlLocation="https://roectm800a:21443/c3pr/services/services/SubjectManagement?wsdl"
		address="https://roectm800a:21443/c3pr/services/services/SubjectManagement">
		<jaxws:features>
			<bean class="org.apache.cxf.feature.LoggingFeature" />
		</jaxws:features>

		<jaxws:properties>
			<entry key="ws-security.sts.client">
				<bean class="org.apache.cxf.ws.security.trust.STSClient" id="stsClient">
					<constructor-arg ref="cxf" />

                    <property name="inInterceptors">
                        <list>
                            <ref bean="logInbound" />
                        </list>
                    </property>
                    <property name="outInterceptors">
                        <list>
                            <ref bean="logOutbound" />
                        </list>
                    </property>
                    <property name="outFaultInterceptors">
                        <list>
                            <ref bean="logOutbound" />
                        </list>
                    </property>
                    <property name="inFaultInterceptors">
                        <list>
                            <ref bean="logInbound" />
                        </list>
                    </property>

                    <property name="wsdlLocation"
						value="https://r0177808idm.mayoid.gps.org/adfs/services/trust/mex" />

					<!-- Next two values come from STS's WSDL. -->
					<property name="serviceName"
                        value="{http://schemas.microsoft.com/ws/2008/06/identity/securitytokenservice}SecurityTokenService" />
					<property name="endpointName"
						value="{http://schemas.microsoft.com/ws/2008/06/identity/securitytokenservice}UserNameWSTrustBinding_IWSTrust13Async" />

					<!--
						STS must authenticate using Username Token profile and plain text
						username/password.
					-->
					<property name="properties">
						<map>
							<entry key="ws-security.username" value="user" />
							<entry key="ws-security.password" value="password" />
						</map>
					</property>
				</bean>
			</entry>
		</jaxws:properties>
	</jaxws:client>

    <bean id="logInbound" class="org.apache.cxf.interceptor.LoggingInInterceptor" />
    <bean id="logOutbound" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />

</beans>


text:
import com.google.testing.threadtester.AnnotatedTestRunner;
import com.google.testing.threadtester.MethodOption;
import com.google.testing.threadtester.ThreadedAfter;
import com.google.testing.threadtester.ThreadedBefore;
import com.google.testing.threadtester.ThreadedMain;
import com.google.testing.threadtester.ThreadedSecondary;

import java.util.HashSet;

import junit.framework.TestCase;

/**
 * Unit test for UniqueList. Demonstrates use of
 * {@link com.google.testing.threadtester.AnnotatedTestRunner}.
 *
 * NOTE: This test will fail. It was written to demonstrate a fault in the class
 * under test.
 *
 * @author alasdair.mackintosh@gmail.com (Alasdair Mackintosh)
 */
public class UniqueListTest extends TestCase {

  private static final String HELLO = "Hello";

  private volatile UniqueList<String> uniqueList;

  public void testPutIfAbsent() {
    System.out.printf("In testPutIfAbsent\n");
    // Create an AnnotatedTestRunner that will run the threaded tests defined in this
    // class. We want to test the behaviour of the private method "putIfAbsentInternal" so
    // we need to specify it by name using runner.setMethodOption()
    AnnotatedTestRunner runner = new AnnotatedTestRunner();
    HashSet<String> methods = new HashSet<String>();
    runner.setMethodOption(MethodOption.ALL_METHODS, methods);
    runner.setDebug(true);
    runner.runTests(this.getClass(), UniqueList.class);
  }

  @ThreadedBefore
  public void before() {
    // Set up a new UniqueList instance for the test
    uniqueList = new UniqueList<String>();
    System.out.printf("Created new list\n");
  }

  @ThreadedMain
  public void main() {
    // Add a new element to the list in the main test thread
    uniqueList.putIfAbsent(HELLO);
  }

  @ThreadedSecondary
  public void secondary() {
    // Add a new element to the list in the secondary test thread
    uniqueList.putIfAbsent(HELLO);
  }

  @ThreadedAfter
  public void after() {
    // If UniqueList is behaving correctly, it should only contain
    // a single copy of HELLO
    assertEquals(1, uniqueList.size());
    assertTrue(uniqueList.contains(HELLO));
  }
}


text:
package org.apache.fineract.integrationtests;

import org.apache.fineract.integrationtests.common.Utils;
import org.apache.fineract.integrationtests.common.loans.LoanTransactionHelper;
import org.junit.Before;

import com.jayway.restassured.builder.RequestSpecBuilder;
import com.jayway.restassured.builder.ResponseSpecBuilder;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.specification.RequestSpecification;
import com.jayway.restassured.specification.ResponseSpecification;

/**
 * Client Loan Integration Test for checking Loan Application Repayment
 * Schedule.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SurveyIntegrationTest {

    private ResponseSpecification responseSpec;
    private RequestSpecification requestSpec;
    private LoanTransactionHelper loanTransactionHelper;

    @Before
    public void setup() {
        Utils.initializeRESTAssured();
        this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
        this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
        this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
    }

}


text:
_windows-1258_ is a robust JavaScript implementation of [the windows-1258 character encoding as defined by the Encoding Standard](https://encoding.spec.whatwg.org/#windows-1258).

This encoding is known under the following names: cp1258, windows-1258, and x-cp1258.

## Installation

Via [npm](https://www.npmjs.com/):

```bash
npm install windows-1258
```

In a browser or in [Node.js](https://nodejs.org/):

```js
import {encode, decode, labels} from 'windows-1258';
// or…
import * as windows1258 from 'windows-1258';
```

## API

### `windows1258.labels`

An array of strings, each representing a [label](https://encoding.spec.whatwg.org/#label) for this encoding.

### `windows1258.encode(input, options)`

This function takes a plain text string (the `input` parameter) and encodes it according to windows-1258. The return value is an environment-agnostic `Uint16Array` of which each element represents an octet as per windows-1258.

```js
const encodedData = windows1258.encode(text);
```

The optional `options` object and its `mode` property can be used to set the error mode. The two available error modes are `'fatal'` (the default) or `'replacement'`. (Note: This differs from [the spec](https://encoding.spec.whatwg.org/#error-mode), which recognizes "fatal" and HTML" modes for encoders. The reason behind this difference is that the spec algorithm is aimed at producing HTML, whereas this library encodes into an environment-agnostic `Uint16Array` of bytes.)

```js
const encodedData = windows1258.encode(text, {
  mode: 'replacement'
});
// If `text` contains a symbol that cannot be represented in windows-1258,
// instead of throwing an error, it becomes 0xFFFD.
```

### `windows1258.decode(input, options)`

This function decodes `input` according to windows-1258. The `input` parameter can either be a `Uint16Array` of which each element represents an octet as per windows-1258, or a 'byte string' (i.e. a string of which each item represents an octet as per windows-1258).

```js
const text = windows1258.decode(encodedData);
```

The optional `options` object and its `mode` property can be used to set the [error mode](https://encoding.spec.whatwg.org/#error-mode). For decoding, the error mode can be `'replacement'` (the default) or `'fatal'`.

```js
const text = windows1258.decode(encodedData, {
  mode: 'fatal'
});
// If `encodedData` contains an invalid byte for the windows-1258 encoding,
// instead of replacing it with U+FFFD in the output, an error is thrown.
```

## Notes

[Similar modules for other single-byte legacy encodings are available.](https://www.npmjs.com/browse/keyword/legacy-encoding)

## Author

| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |

## License

_windows-1258_ is available under the [MIT](https://mths.be/mit) license.


text:
var findTr = function(event) {
  var target = event.srcElement || event.target
    , $target = $(target)
    , $tr = $target.parents('tr');

  return $tr;
}

var remove = function(event) {
  var $tr = findTr(event);
  var id = $tr.data('id');
  $.ajax({
    url: '/api/articles/' + id,
    type: 'DELETE',
    success: function(data, status, xhr){
      $('.alert').addClass('hidden');
      $tr.remove();
    }
  })
};

var update= function(event) {
  var $tr = findTr(event);
  $tr.find('button').attr('disabled', 'disabled');
  var data = { published: $tr.hasClass('unpublished')};
  var id = $tr.attr('data-id');
  $.ajax({
    url: '/api/articles/' + id,
    type: 'PUT',
    contentType: 'application/json',
    data: JSON.stringify({article: data}),
    success: function(dataResponse, status, xhr) {
      $tr.find('button').removeAttr('disabled');
      $('.alert').addClass('hidden');
      if(data.published){
        $tr.removeClass('unpublished').find('.glyphicon-play').removeClass('glyphicon-play').addClass('glyphicon-pause');
      } else {
        $tr.addClass('unpublished').find('.glyphicon-pause').removeClass('glyphicon-pause').addClass('glyphicon-play');
      }
    }
  });
};

$(function(){
  var $element = $('.admin tbody');
  $element.on('click', 'button.remove', remove);
  $element.on('click', 'button', update);
});


text:
<?php
class Kwc_Menu_Abstract_Events extends Kwc_Abstract_Events
{
    protected $_numLevels = 1; //overridden in Menu_Expanded

    protected $_level; //level setting of menu

    protected function _init()
    {
        parent::_init();
        $this->_initSettings();
    }

    //overwritten in Kwc_Menu_Trl_Events
    protected function _initSettings()
    {
        $this->_level = $menuLevel = Kwc_Abstract::getSetting($this->_class, 'level');
    }

    public function getListeners()
    {
        $ret = parent::getListeners();
        $ret[] = array(
            'class' => null,
            'event' => 'Kwf_Component_Event_Page_Added',
            'callback' => 'onPageChanged'
        );
        $ret[] = array(
            'class' => null,
            'event' => 'Kwf_Component_Event_Page_Removed',
            'callback' => 'onPageChanged'
        );
        $ret[] = array(
            'class' => null,
            'event' => 'Kwf_Component_Event_Page_PositionChanged',
            'callback' => 'onPageChanged'
        );
        $ret[] = array(
            'class' => null,
            'event' => 'Kwf_Component_Event_Page_ShowInMenuChanged',
            'callback' => 'onPageChanged'
        );
        $ret[] = array(
            'class' => null,
            'event' => 'Kwf_Component_Event_Page_ParentChanged',
            'callback' => 'onParentChanged'
        );
        $ret[] = array(
            'class' => null,
            'event' => 'Kwf_Component_Event_Component_RecursiveRemoved',
            'callback' => 'onRecursiveRemoved'
        );
        return $ret;
    }

    public function onParentChanged(Kwf_Component_Event_Page_ParentChanged $event)
    {
        $this->_onPageChanged($event, $event->component, $event->newParent);
        $this->_onPageChanged($event, $event->component, $event->oldParent);
    }

    //overridden in Kwc_Menu_Events to fire HasContentChanged
    protected function _onMenuChanged(Kwf_Events_Event_Abstract $event, Kwf_Component_Data $menu)
    {
        $this->fireEvent(new Kwf_Component_Event_Component_ContentChanged(
            $this->_class, $menu
        ));
    }

    public function onPageChanged(Kwf_Component_Event_Component_Abstract $event)
    {
        $data = $event->component;
        $this->_onPageChanged($event, $data, $data->parent);
    }

    private function _onPageChanged($event, Kwf_Component_Data $data, Kwf_Component_Data $parentData)
    {
        if (!$event instanceof Kwf_Component_Event_Page_ShowInMenuChanged
            && !$data->isShownInMenu()
        ) {
            //ignore pages not shown in menu
            return;
        }
        $this->_fireMenuEvent($data, $parentData);
    }

    protected function _fireMenuEvent(Kwf_Component_Data $data, Kwf_Component_Data $parentData = null)
    {
        $menuLevel = $this->_level;
        if (!$parentData) $parentData = $data->parent;

        //find category + level the changed page is in
        $level = 0;
        $categoryData = $parentData;

        if ($data->isPage) $level++;
        while ($categoryData && !Kwc_Abstract::getFlag($categoryData->componentClass, 'menuCategory')) {
            if ($categoryData->isPage) $level++;
            $categoryData = $categoryData->parent;
        }

        if (is_int($menuLevel)) {
            //numeric menu level
            if ($level+1 >= $menuLevel && $level+1 <= $menuLevel+$this->_numLevels) {
                $l = $level + 1;
                if ($l != $menuLevel) {
                    if ($data->isPage) $l--;
                    $data = $parentData;
                    while ($data) {
                        if ($l == $menuLevel) {
                            break;
                        }
                        if ($data->isPage) $l--;
                        $data = $data->parent;
                    }
                } else {
                    $data = $parentData;
                }
                $data = $data->getPageOrRoot();
                $menus = $data->getRecursiveChildComponents(array('componentClass'=>$this->_class));
                foreach ($menus as $m) {
                    $this->fireEvent(new Kwf_Component_Event_Component_ContentChanged(
                        $this->_class, $m
                    ));
                }
            }
        } else {
            //category menu level

            if (!$categoryData) return;

            //$cat is the category id of changed page
            $cat = Kwc_Abstract::getFlag($categoryData->componentClass, 'menuCategory');
            if ($cat) {
                if ($cat === true) $cat = $categoryData->id;
            }

            if ($cat === $menuLevel && $level >= 1 && $level <= $this->_numLevels) {
                //this menu shows this changed and not in a lower level
                $s = array(
                    'subroot' => $data
                );
                foreach (Kwc_Abstract::getComponentClasses() as $cls) { //get all categories
                    $c = Kwc_Abstract::getFlag($cls, 'menuCategory');
                    $cmps = array();
                    //get category that changed
                    if ($c === true) {
                        $cmps = Kwf_Component_Data_Root::getInstance()->getComponentsByClass($cls, array('id'=>$cat, 'subRoot'=>$data));
                    } else if ($c == $cat) {
                        $cmps = Kwf_Component_Data_Root::getInstance()->getComponentsByClass($cls, array('subRoot'=>$data));
                    } else {
                        continue;
                    }
                    foreach ($cmps as $i) {
                        //get menu that changed
                        foreach ($i->getRecursiveChildComponents(array('componentClass'=>$this->_class)) as $m) {
                            //do what needs to be done if menu item changed
                            $this->fireEvent(new Kwf_Component_Event_Component_ContentChanged(
                                $this->_class, $m
                            ));
                        }
                    }
                }
            }
        }
    }

    public function onRecursiveRemoved(Kwf_Component_Event_Component_RecursiveRemoved $event)
    {
        $components = $event->component->getRecursiveChildComponents(
            array('showInMenu' => true, 'page' => true)
        );
        foreach ($components as $component) {
            $this->onPageChanged(new Kwf_Component_Event_Page_Removed(
                $component->componentClass, $component, Kwf_Component_Event_Page_Removed::FLAG_ROW_ADDED_REMOVED
            ));
        }
    }
}


text: int main() { return sizeof(unsigned long long); }


text:
namespace YouTown.Validation
{
    public class NotNull : IValidator
    {
        public IValidationResult Validate(object value1, object value2 = null, string objectName = null)
        {
            if (value1 == null)
            {
                return new Invalid($"object {objectName} cannot be null");
            }
            return Validation.Validator.Valid;
        }
    }
}


text:
namespace Microsoft.Graph
{
    using System.Collections.Generic;
    using System.IO;
    using System.Net.Http;
    using System.Threading;

    /// <summary>
    /// The interface IOnenotePageContentRequest.
    /// </summary>
    public partial interface IOnenotePageContentRequest : IBaseRequest
    {
        /// <summary>
        /// Gets the stream.
        /// </summary>
        /// <returns>The stream.</returns>
        System.Threading.Tasks.Task<Stream> GetAsync();

        /// <summary>
        /// Gets the stream.
        /// </summary>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
        /// <returns>The stream.</returns>
        System.Threading.Tasks.Task<Stream> GetAsync(CancellationToken cancellationToken, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead);

        /// <summary>
        /// PUTs the specified stream.
        /// </summary>
        /// <typeparam name="T">The type returned by the PUT call.</typeparam>
        /// <param name="content">The stream to PUT.</param>
        /// <returns>The object returned by the PUT call.</returns>
        System.Threading.Tasks.Task<T> PutAsync<T>(Stream content) where T : OnenotePage;

        /// <summary>
        /// PUTs the specified stream.
        /// </summary>
        /// <typeparam name="T">The type returned by the PUT call.</typeparam>
        /// <param name="content">The stream to PUT.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
        /// <returns>The object returned by the PUT call.</returns>
        System.Threading.Tasks.Task<T> PutAsync<T>(Stream content, CancellationToken cancellationToken, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) where T : OnenotePage;

    }
}


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class MdGridOff extends React.Component<IconBaseProps> { }
export = MdGridOff;


text:
package org.apache.ambari.server.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.ambari.server.checks.CheckDescription;
import org.apache.ambari.server.orm.entities.RepositoryVersionEntity;
import org.apache.ambari.server.state.StackId;
import org.apache.ambari.server.state.stack.PrereqCheckStatus;
import org.apache.ambari.server.state.stack.UpgradePack.PrerequisiteCheckConfig;
import org.apache.ambari.server.state.stack.upgrade.UpgradeType;

/**
 * Represents a prerequisite check request.
 */
public class PrereqCheckRequest {
  private String m_clusterName;
  private StackId m_sourceStackId;
  private RepositoryVersionEntity m_targetRepositoryVersion;
  private PrerequisiteCheckConfig m_prereqCheckConfig;

  private UpgradeType m_upgradeType;

  private Map<CheckDescription, PrereqCheckStatus> m_results = new HashMap<>();
  private boolean m_revert = false;

  public PrereqCheckRequest(String clusterName, UpgradeType upgradeType) {
    m_clusterName = clusterName;
    m_upgradeType = upgradeType;
  }

  /**
   * Construct a request to performs checks before an Upgrade.
   * The default type is Rolling.
   * @param clusterName
   */
  public PrereqCheckRequest(String clusterName) {
    this(clusterName, UpgradeType.ROLLING);
  }

  public String getClusterName() {
    return m_clusterName;
  }

  public UpgradeType getUpgradeType() {
    return m_upgradeType;
  }

  /**
   * Sets the result of a check.
   * @param description the description
   * @param status      the status result
   */
  public void addResult(CheckDescription description, PrereqCheckStatus status) {
    m_results.put(description, status);
  }

  /**
   * Gets the result of a check of the supplied description
   * @param description the description
   * @return the return value, or {@code null} if it has not been run
   */
  public PrereqCheckStatus getResult(CheckDescription description) {
    return m_results.get(description);
  }

  /**
   * Gets the cluster's current stack before upgrade.
   *
   * @return the sourceStackId the source stack ID.
   */
  public StackId getSourceStackId() {
    return m_sourceStackId;
  }

  /**
   * Sets the cluster's current stack before upgrade.
   *
   * @param sourceStackId
   *          the sourceStackId to set
   */
  public void setSourceStackId(StackId sourceStackId) {
    m_sourceStackId = sourceStackId;
  }

  /**
   * Gets the target repository of the upgrade.
   *
   * @return the target repository.
   */
  public RepositoryVersionEntity getTargetRepositoryVersion() {
    return m_targetRepositoryVersion;
  }

  /**
   * Sets the target of the upgrade.
   *
   * @param targetRepositoryVersion
   *          the target repository version
   */
  public void setTargetRepositoryVersion(RepositoryVersionEntity targetRepositoryVersion) {
    m_targetRepositoryVersion = targetRepositoryVersion;
  }

  /**
   * Gets the prerequisite check config
   * @return the prereqCheckConfig
   */
  public PrerequisiteCheckConfig getPrerequisiteCheckConfig() {
    return m_prereqCheckConfig;
  }

  /**
   * Sets the prerequisite check config obtained from the upgrade pack
   * @param prereqCheckConfig The prereqCheckConfig
   */
  public void setPrerequisiteCheckConfig(PrerequisiteCheckConfig prereqCheckConfig) {
    m_prereqCheckConfig = prereqCheckConfig;
  }

  /**
   * @param revert
   *          {@code true} if the check is for a patch reversion
   */
  public void setRevert(boolean revert) {
    m_revert = revert;
  }

  /**
   * @return if the check is for a patch reversion
   */
  public boolean isRevert() {
    return m_revert;
  }
}