text:
package org.onosproject.drivers.odtn;

import com.google.common.collect.ImmutableList;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
import org.onlab.packet.ChassisId;
import org.onosproject.drivers.utilities.XmlConfigParser;
import org.onosproject.net.ChannelSpacing;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.OchSignal;
import org.onosproject.net.OduSignalType;
import org.onosproject.net.Port.Type;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DefaultDeviceDescription;
import org.onosproject.net.device.DefaultPortDescription;
import org.onosproject.net.device.DefaultPortDescription.Builder;
import org.onosproject.net.device.DeviceDescription;
import org.onosproject.net.device.DeviceDescriptionDiscovery;
import org.onosproject.net.device.PortDescription;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import org.onosproject.net.optical.device.OchPortHelper;
import org.onosproject.netconf.NetconfController;
import org.onosproject.netconf.NetconfDevice;
import org.onosproject.netconf.NetconfSession;
import org.onosproject.odtn.behaviour.OdtnDeviceDescriptionDiscovery;
import org.slf4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Driver Implementation of the DeviceDescrption discovery for OpenConfig
 * terminal devices.
 *
 */
public class AdvaTerminalDeviceDiscovery
    extends AbstractHandlerBehaviour
    implements OdtnDeviceDescriptionDiscovery, DeviceDescriptionDiscovery {

    private static final String RPC_TAG_NETCONF_BASE =
        "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">";

    private static final String RPC_CLOSE_TAG = "</rpc>";

    private static final String OC_PLATFORM_TYPES_TRANSCEIVER =
        "oc-platform-types:TRANSCEIVER";

    private static final String OC_PLATFORM_TYPES_PORT =
        "oc-platform-types:PORT";

    private static final String OC_TRANSPORT_TYPES_OPTICAL_CHANNEL =
        "oc-opt-types:OPTICAL_CHANNEL";

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

    /**
     * Returns the NetconfSession with the device for which the method was called.
     *
     * @param deviceId device indetifier
     *
     * @return The netconf session or null
     */
    private NetconfSession getNetconfSession(DeviceId deviceId) {
        NetconfController controller = handler().get(NetconfController.class);
        NetconfDevice ncdev = controller.getDevicesMap().get(deviceId);
        if (ncdev == null) {
            log.trace("No netconf device, returning null session");
            return null;
        }
        return ncdev.getSession();
    }

    /**
     * Get the deviceId for which the methods apply.
     *
     * @return The deviceId as contained in the handler data
     */
    private DeviceId did() {
        return handler().data().deviceId();
    }

    /**
     * Construct a String with a Netconf filtered get RPC Message.
     *
     * @param filter A valid XML tree with the filter to apply in the get
     * @return a String containing the RPC XML Document
     */
    private String filteredGetBuilder(String filter) {
        StringBuilder rpc = new StringBuilder(RPC_TAG_NETCONF_BASE);
        rpc.append("<get>");
        rpc.append("<filter type='subtree'>");
        rpc.append(filter);
        rpc.append("</filter>");
        rpc.append("</get>");
        rpc.append(RPC_CLOSE_TAG);
        return rpc.toString();
    }

    /**
     * Builds a request to get Device Components, config and operational data.
     *
     * @return A string with the Netconf RPC for a get with subtree rpcing based on
     *    /components/
     */
    private String getTerminalDeviceBuilder() {
        return filteredGetBuilder("<terminal-device xmlns='http://openconfig.net/yang/terminal-device'/>");
    }

    @Override
    public DeviceDescription discoverDeviceDetails() {
        return new DefaultDeviceDescription(handler().data().deviceId().uri(),
                                            Device.Type.TERMINAL_DEVICE,
                                            "ADVA",
                                            "FSP3000C",
                                            "3.1",
                                            "",
                                            new ChassisId("1"));
    }

    /**
     * Returns a list of PortDescriptions for the device.
     *
     * @return a list of descriptions.
     *
     * The RPC reply follows the following pattern:
     * //CHECKSTYLE:OFF
     *
{@code
     * <?xml version="1.0" encoding="UTF-8"?>
     * <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="7">
     * <data>
     *   <components xmlns="http://openconfig.net/yang/platform">
     *     <component>....
     *     </component>
     *     <component>....
     *     </component>
     *   </components>
     * </data>
     * </rpc-reply>
     * }

     * //CHECKSTYLE:ON
     */
    @Override
    public List<PortDescription> discoverPortDetails() {
        try {
            NetconfSession session = getNetconfSession(did());
            if (session == null) {
                log.error("discoverPortDetails called with null session for {}", did());
                return ImmutableList.of();
            }

            CompletableFuture<String> fut = session.rpc(getTerminalDeviceBuilder());
            String rpcReply = fut.get();

            XMLConfiguration xconf = (XMLConfiguration) XmlConfigParser.loadXmlString(rpcReply);
            xconf.setExpressionEngine(new XPathExpressionEngine());

            HierarchicalConfiguration logicalChannels = xconf.configurationAt("data/terminal-device/logical-channels");
            return parseLogicalChannels(logicalChannels);
        } catch (Exception e) {
            log.error("Exception discoverPortDetails() {}", did(), e);
            return ImmutableList.of();
        }
    }

    /**
     * Parses transceiver information from OpenConfig XML configuration.
     *
     * @param terminalDevice the XML document with components root.
     * @return List of ports
     *
     * //CHECKSTYLE:OFF
     *
{@code
     *   <components xmlns="http://openconfig.net/yang/platform">
     *     <component>....
     *     </component>
     *     <component>....
     *     </component>
     *   </components>
     * }

     * //CHECKSTYLE:ON
     */
    protected List<PortDescription> parseLogicalChannels(HierarchicalConfiguration terminalDevice) {
        return terminalDevice.configurationsAt("channel")
            .stream()
            .filter(channel -> !channel.getString("index", "unknown").equals("unknown"))
            .map(channel -> {
                try {
                    // Pass the root document for cross-reference
                    return parseLogicalChannel(channel);
                } catch (Exception e) {
                    return null;
                }
                })
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }

     /**
      * Parses a component XML doc into a PortDescription.
      *
      * @param channel subtree to parse. It must be a component ot type PORT.
      *  case we need to check transceivers or optical channels.
      *
      * @return PortDescription or null if component does not have onos-index
      */
     private PortDescription parseLogicalChannel(
             HierarchicalConfiguration channel) {

         HierarchicalConfiguration config = channel.configurationAt("config");
         String logicalChannelIndex = config.getString("index");
         String description = config.getString("description");
         String rateClass = config.getString("rate-class");
         log.info("Parsing Component {} type {} speed {}", logicalChannelIndex, description, rateClass);

         Map<String, String> annotations = new HashMap<>();
         annotations.put(OdtnDeviceDescriptionDiscovery.OC_LOGICAL_CHANNEL, logicalChannelIndex);

         // Store all properties as port properties

         Pattern clientPattern = Pattern.compile("(\\d*)/(\\d*)/c(\\d)"); // e.g. xe1/1
         Pattern linePattern = Pattern.compile("(\\d*)/(\\d*)/n(\\d)");
         Matcher clientMatch = clientPattern.matcher(description);
         Matcher lineMatch = linePattern.matcher(description);

         Pattern portSpeedPattern = Pattern.compile("TRIB_RATE_([0-9.]*)G");
         Matcher portSpeedMatch = portSpeedPattern.matcher(rateClass);

         Builder builder = DefaultPortDescription.builder();

         if (portSpeedMatch.find()) {
             Long speed = Long.parseLong(portSpeedMatch.group(1));
             builder.portSpeed(speed * 1000);
         }

         if (clientMatch.find()) {
             Long num = Long.parseLong(clientMatch.group(1));
             Long portNum = 100 + num;
             String connectionId = "connection:" + num.toString();

             annotations.put(OdtnDeviceDescriptionDiscovery.OC_NAME, description);
             annotations.putIfAbsent(PORT_TYPE, OdtnPortType.CLIENT.value());
             annotations.putIfAbsent(ONOS_PORT_INDEX, portNum.toString());
             annotations.putIfAbsent(CONNECTION_ID, connectionId);

             builder.withPortNumber(PortNumber.portNumber(portNum));
             builder.type(Type.PACKET);

             builder.annotations(DefaultAnnotations.builder().putAll(annotations).build());
             return builder.build();

         } else if (lineMatch.find()) {
             Long num = (Long.parseLong(lineMatch.group(1)) - 1) * 2 + Long.parseLong(lineMatch.group(2));
             Long portNum = 200 + num;
             String connectionId = "connection:" + num.toString();

             description = description.substring(0, description.length() - 6);

             annotations.putIfAbsent(PORT_TYPE, OdtnPortType.LINE.value());
             annotations.putIfAbsent(ONOS_PORT_INDEX, portNum.toString());
             annotations.putIfAbsent(CONNECTION_ID, connectionId);
             annotations.put(OdtnDeviceDescriptionDiscovery.OC_NAME, "optch " + description);

             OchSignal signalId = OchSignal.newDwdmSlot(ChannelSpacing.CHL_50GHZ, 1);
             return OchPortHelper.ochPortDescription(
                     PortNumber.portNumber(portNum),
                     true,
                     OduSignalType.ODU4, // TODO Client signal to be discovered
                     true,
                     signalId,
                     DefaultAnnotations.builder().putAll(annotations).build());

         } else {
             log.warn("Unexpected component description: {}", description);
             return null;
         }

     }
}


text:
package org.foo.managed.factory;

import java.util.Properties;
import org.osgi.framework.*;
import org.osgi.service.cm.ManagedServiceFactory;

public class Activator implements BundleActivator {
	private volatile ServiceRegistration m_reg;
	private volatile ManagedServiceFactoryExample m_factory;
	public void start(BundleContext context) {
		Properties props = new Properties();
		props.put(Constants.SERVICE_PID, "org.foo.managed.factory");
		m_reg = context.registerService(ManagedServiceFactory.class.getName(),
			m_factory = new ManagedServiceFactoryExample(), props);
	}
    public void stop(BundleContext context) {
    	m_reg.unregister();
    	m_factory.stop();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.helger.commons.name;

import javax.annotation.Nonnull;

import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.hashcode.HashCodeGenerator;

public final class MockHasName implements IHasName, Comparable <MockHasName>
{
  private final String m_sName;

  public MockHasName (final int nID)
  {
    this (Integer.toString (nID));
  }

  public MockHasName (@Nonnull @Nonempty final String sName)
  {
    m_sName = ValueEnforcer.notEmpty (sName, "Name");
  }

  @Nonnull
  @Nonempty
  public String getName ()
  {
    return m_sName;
  }

  public int compareTo (final MockHasName o)
  {
    return m_sName.compareTo (o.m_sName);
  }

  @Override
  public boolean equals (final Object o)
  {
    if (o == this)
      return true;
    if (o == null || !getClass ().equals (o.getClass ()))
      return false;
    final MockHasName rhs = (MockHasName) o;
    return m_sName.equals (rhs.m_sName);
  }

  @Override
  public int hashCode ()
  {
    return new HashCodeGenerator (this).append (m_sName).getHashCode ();
  }
}


text:
.class Lcom/zte/mifavor/widget/DateTimePickerZTE$7;
.super Ljava/lang/Object;
.source "DateTimePickerZTE.java"

# interfaces
.implements Lcom/zte/mifavor/widget/NumberPickerZTE$OnValueChangeListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/zte/mifavor/widget/DateTimePickerZTE;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/zte/mifavor/widget/DateTimePickerZTE;

# direct methods
.method constructor <init>(Lcom/zte/mifavor/widget/DateTimePickerZTE;)V
    .locals 0

    .prologue
    .line 460
    iput-object p1, p0, Lcom/zte/mifavor/widget/DateTimePickerZTE$7;->this$0:Lcom/zte/mifavor/widget/DateTimePickerZTE;

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

    return-void
.end method

# virtual methods
.method public onValueChange(Lcom/zte/mifavor/widget/NumberPickerZTE;II)V
    .locals 2
    .param p1, "picker"    # Lcom/zte/mifavor/widget/NumberPickerZTE;
    .param p2, "oldVal"    # I
    .param p3, "newVal"    # I

    .prologue
    .line 462
    iget-object v0, p0, Lcom/zte/mifavor/widget/DateTimePickerZTE$7;->this$0:Lcom/zte/mifavor/widget/DateTimePickerZTE;

    # invokes: Lcom/zte/mifavor/widget/DateTimePickerZTE;->updateInputState()V
    invoke-static {v0}, Lcom/zte/mifavor/widget/DateTimePickerZTE;->access$000(Lcom/zte/mifavor/widget/DateTimePickerZTE;)V

    .line 463
    invoke-virtual {p1}, Lcom/zte/mifavor/widget/NumberPickerZTE;->requestFocus()Z

    .line 464
    iget-object v1, p0, Lcom/zte/mifavor/widget/DateTimePickerZTE$7;->this$0:Lcom/zte/mifavor/widget/DateTimePickerZTE;

    iget-object v0, p0, Lcom/zte/mifavor/widget/DateTimePickerZTE$7;->this$0:Lcom/zte/mifavor/widget/DateTimePickerZTE;

    # getter for: Lcom/zte/mifavor/widget/DateTimePickerZTE;->mIsAm:Z
    invoke-static {v0}, Lcom/zte/mifavor/widget/DateTimePickerZTE;->access$1000(Lcom/zte/mifavor/widget/DateTimePickerZTE;)Z

    move-result v0

    if-nez v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    # setter for: Lcom/zte/mifavor/widget/DateTimePickerZTE;->mIsAm:Z
    invoke-static {v1, v0}, Lcom/zte/mifavor/widget/DateTimePickerZTE;->access$1002(Lcom/zte/mifavor/widget/DateTimePickerZTE;Z)Z

    .line 465
    iget-object v0, p0, Lcom/zte/mifavor/widget/DateTimePickerZTE$7;->this$0:Lcom/zte/mifavor/widget/DateTimePickerZTE;

    # invokes: Lcom/zte/mifavor/widget/DateTimePickerZTE;->updateAmPmControl()V
    invoke-static {v0}, Lcom/zte/mifavor/widget/DateTimePickerZTE;->access$1100(Lcom/zte/mifavor/widget/DateTimePickerZTE;)V

    .line 466
    iget-object v0, p0, Lcom/zte/mifavor/widget/DateTimePickerZTE$7;->this$0:Lcom/zte/mifavor/widget/DateTimePickerZTE;

    # invokes: Lcom/zte/mifavor/widget/DateTimePickerZTE;->onTimeChanged()V
    invoke-static {v0}, Lcom/zte/mifavor/widget/DateTimePickerZTE;->access$1200(Lcom/zte/mifavor/widget/DateTimePickerZTE;)V

    .line 467
    return-void

    .line 464
    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="20dp"
    android:height="20dp"
    android:viewportWidth="20"
    android:viewportHeight="20"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M9.583,15.75V11.229H1.521V8.771H9.583V4.25L18.771,10Z"/>
</vector>


text:
package vg.civcraft.mc.mercury.venus;

import vg.civcraft.mc.mercury.MercuryPlugin;
import vg.civcraft.mc.mercury.ServiceHandler;

public class VenusHandler implements ServiceHandler{

	private VenusService service;
	private MercuryPlugin plugin = MercuryPlugin.instance;

	public VenusHandler(){
		service = new VenusService();
		if (service.connected)
			service.start();
		else
			service = null;
	}

	// Venus doesn't need to be pinged.
	@Override
	public void pingService() {

	}

	@Override
	public void addServerToServerList() {

	}

	@Override
	public void sendMessage(String destination, String message, String... channels) {
		for (String channel: channels)
			if (service != null)
				service.sendMessage(destination, message, channel);
	}

	// Venus doesn't need channels registered.
	@Override
	public void addChannels(String... channels) {

	}

	@Override
	public void destory() {
		if (service != null)
			service.teardown();
	}

	@Override
	public boolean isEnabled(){
		if (service != null)
			return true;
		else
			return false;
	}

}


text:
local cjson = require "cjson.safe"
local utils = require "kong.tools.utils"
local singletons = require "kong.singletons"
local constants = require "kong.constants"

local kong_dict = ngx.shared.kong
local udp_sock = ngx.socket.udp
local timer_at = ngx.timer.at
local ngx_log = ngx.log
local concat = table.concat
local tostring = tostring
local pairs = pairs
local type = type
local ERR = ngx.ERR
local sub = string.sub

local PING_INTERVAL = 3600
local PING_KEY = "events:reports"
local BUFFERED_REQUESTS_COUNT_KEYS = "events:requests"

local _buffer = {}
local _enabled = false
local _unique_str = utils.random_string()
local _buffer_immutable_idx

do
  -- initialize immutable buffer data (the same for each report)

  local meta = require "kong.meta"

  local system_infos = utils.get_system_infos()

  -- <14>: syslog facility code 'log alert'
  _buffer[#_buffer + 1] = "<14>version=" .. meta._VERSION

  for k, v in pairs(system_infos) do
    _buffer[#_buffer + 1] = k .. "=" .. v
  end

  _buffer_immutable_idx = #_buffer -- max idx for immutable slots
end

local function log(lvl, ...)
  ngx_log(lvl, "[reports] ", ...)
end

-- UDP logger

local function send_report(signal_type, t, host, port)
  if not _enabled then
    return
  elseif type(signal_type) ~= "string" then
    return error("signal_type (arg #1) must be a string", 2)
  end

  t = t or {}
  host = host or constants.SYSLOG.ADDRESS
  port = port or constants.SYSLOG.PORT

  -- add signal type to data

  t.signal = signal_type

  -- insert given entity in mutable part of buffer

  local mutable_idx = _buffer_immutable_idx

  for k, v in pairs(t) do
    if k ~= "created_at" and sub(k, -2) ~= "id" then
      if type(v) == "table" then
        local json, err = cjson.encode(v)
        if err then
          log(ERR, "could not JSON encode given table entity: ", err)
        end

        v = json
      end

      mutable_idx = mutable_idx + 1
      _buffer[mutable_idx] = k .. "=" .. tostring(v)
    end
  end

  local sock = udp_sock()
  local ok, err = sock:setpeername(host, port)
  if not ok then
    log(ERR, "could not set peer name for UDP socket: ", err)
    return
  end

  sock:settimeout(1000)

  -- concat and send buffer

  --print(concat(_buffer, ";", 1, mutable_idx))

  ok, err = sock:send(concat(_buffer, ";", 1, mutable_idx))
  if not ok then
    log(ERR, "could not send data: ", err)
  end

  ok, err = sock:close()
  if not ok then
    log(ERR, "could not close socket: ", err)
  end
end

-- ping timer handler

-- Hold a lock for the whole interval (exptime) to prevent multiple
-- worker processes from sending the test request simultaneously.
-- Other workers do not need to wait until this lock is released,
-- and can ignore the event, knowing another worker is handling it.
-- We substract 1ms to the exp time to prevent a race condition
-- with the next timer event.
local function get_lock(key, exptime)
  local ok, err = kong_dict:safe_add(key, true, exptime - 0.001)
  if not ok and err ~= "exists" then
    log(ERR, "could not get lock from 'kong' shm: ", err)
  end

  return ok
end

local function create_timer(...)
  local ok, err = timer_at(...)
  if not ok then
    log(ERR, "could not create ping timer: ", err)
  end
end

local function ping_handler(premature)
  if premature then
    return
  end

  -- all workers need to register a recurring timer, in case one of them
  -- crashes. Hence, this must be called before the `get_lock()` call.
  create_timer(PING_INTERVAL, ping_handler)

  if not get_lock(PING_KEY, PING_INTERVAL) then
    return
  end

  local n_requests, err = kong_dict:get(BUFFERED_REQUESTS_COUNT_KEYS)
  if err then
    log(ERR, "could not get buffered requests count from 'kong' shm: ", err)
  elseif not n_requests then
    n_requests = 0
  end

  send_report("ping", {
    requests = n_requests,
    unique_id = _unique_str,
    database = singletons.configuration.database
  })

  local ok, err = kong_dict:incr(BUFFERED_REQUESTS_COUNT_KEYS, -n_requests, n_requests)
  if not ok then
    log(ERR, "could not reset buffered requests count in 'kong' shm: ", err)
  end
end

return {
  -- plugin handler
  init_worker = function()
    if not _enabled then
      return
    end

    create_timer(PING_INTERVAL, ping_handler)
  end,
  log = function()
    if not _enabled then
      return
    end

    local ok, err = kong_dict:incr(BUFFERED_REQUESTS_COUNT_KEYS, 1, 0)
    if not ok then
      log(ERR, "could not increment buffered requests count in 'kong' shm: ",
                err)
    end
  end,

  -- custom methods
  toggle = function(enable)
    _enabled = enable
  end,
  send = send_report,
}


text:
package api

import (
	"fmt"
	"testing"

	"github.com/hashicorp/consul/testutil"
)

func TestCatalog_Datacenters(t *testing.T) {
	c, s := makeClient(t)
	defer s.Stop()

	catalog := c.Catalog()

	testutil.WaitForResult(func() (bool, error) {
		datacenters, err := catalog.Datacenters()
		if err != nil {
			return false, err
		}

		if len(datacenters) == 0 {
			return false, fmt.Errorf("Bad: %v", datacenters)
		}

		return true, nil
	}, func(err error) {
		t.Fatalf("err: %s", err)
	})
}

func TestCatalog_Nodes(t *testing.T) {
	c, s := makeClient(t)
	defer s.Stop()

	catalog := c.Catalog()

	testutil.WaitForResult(func() (bool, error) {
		nodes, meta, err := catalog.Nodes(nil)
		if err != nil {
			return false, err
		}

		if meta.LastIndex == 0 {
			return false, fmt.Errorf("Bad: %v", meta)
		}

		if len(nodes) == 0 {
			return false, fmt.Errorf("Bad: %v", nodes)
		}

		return true, nil
	}, func(err error) {
		t.Fatalf("err: %s", err)
	})
}

func TestCatalog_Services(t *testing.T) {
	c, s := makeClient(t)
	defer s.Stop()

	catalog := c.Catalog()

	testutil.WaitForResult(func() (bool, error) {
		services, meta, err := catalog.Services(nil)
		if err != nil {
			return false, err
		}

		if meta.LastIndex == 0 {
			return false, fmt.Errorf("Bad: %v", meta)
		}

		if len(services) == 0 {
			return false, fmt.Errorf("Bad: %v", services)
		}

		return true, nil
	}, func(err error) {
		t.Fatalf("err: %s", err)
	})
}

func TestCatalog_Service(t *testing.T) {
	c, s := makeClient(t)
	defer s.Stop()

	catalog := c.Catalog()

	testutil.WaitForResult(func() (bool, error) {
		services, meta, err := catalog.Service("consul", "", nil)
		if err != nil {
			return false, err
		}

		if meta.LastIndex == 0 {
			return false, fmt.Errorf("Bad: %v", meta)
		}

		if len(services) == 0 {
			return false, fmt.Errorf("Bad: %v", services)
		}

		return true, nil
	}, func(err error) {
		t.Fatalf("err: %s", err)
	})
}

func TestCatalog_Node(t *testing.T) {
	c, s := makeClient(t)
	defer s.Stop()

	catalog := c.Catalog()
	name, _ := c.Agent().NodeName()

	testutil.WaitForResult(func() (bool, error) {
		info, meta, err := catalog.Node(name, nil)
		if err != nil {
			return false, err
		}

		if meta.LastIndex == 0 {
			return false, fmt.Errorf("Bad: %v", meta)
		}
		if len(info.Services) == 0 {
			return false, fmt.Errorf("Bad: %v", info)
		}

		return true, nil
	}, func(err error) {
		t.Fatalf("err: %s", err)
	})
}

func TestCatalog_Registration(t *testing.T) {
	c, s := makeClient(t)
	defer s.Stop()

	catalog := c.Catalog()

	service := &AgentService{
		ID:      "redis1",
		Service: "redis",
		Tags:    []string{"master", "v1"},
		Port:    8000,
	}

	check := &AgentCheck{
		Node:      "foobar",
		CheckID:   "service:redis1",
		Name:      "Redis health check",
		Notes:     "Script based health check",
		Status:    "passing",
		ServiceID: "redis1",
	}

	reg := &CatalogRegistration{
		Datacenter: "dc1",
		Node:       "foobar",
		Address:    "192.168.10.10",
		Service:    service,
		Check:      check,
	}

	testutil.WaitForResult(func() (bool, error) {
		if _, err := catalog.Register(reg, nil); err != nil {
			return false, err
		}

		node, _, err := catalog.Node("foobar", nil)
		if err != nil {
			return false, err
		}

		if _, ok := node.Services["redis1"]; !ok {
			return false, fmt.Errorf("missing service: redis1")
		}

		health, _, err := c.Health().Node("foobar", nil)
		if err != nil {
			return false, err
		}

		if health[0].CheckID != "service:redis1" {
			return false, fmt.Errorf("missing checkid service:redis1")
		}

		return true, nil
	}, func(err error) {
		t.Fatalf("err: %s", err)
	})

	// Test catalog deregistration of the previously registered service
	dereg := &CatalogDeregistration{
		Datacenter: "dc1",
		Node:       "foobar",
		Address:    "192.168.10.10",
		ServiceID:  "redis1",
	}

	if _, err := catalog.Deregister(dereg, nil); err != nil {
		t.Fatalf("err: %v", err)
	}

	testutil.WaitForResult(func() (bool, error) {
		node, _, err := catalog.Node("foobar", nil)
		if err != nil {
			return false, err
		}

		if _, ok := node.Services["redis1"]; ok {
			return false, fmt.Errorf("ServiceID:redis1 is not deregistered")
		}

		return true, nil
	}, func(err error) {
		t.Fatalf("err: %s", err)
	})

	// Test deregistration of the previously registered check
	dereg = &CatalogDeregistration{
		Datacenter: "dc1",
		Node:       "foobar",
		Address:    "192.168.10.10",
		CheckID:    "service:redis1",
	}

	if _, err := catalog.Deregister(dereg, nil); err != nil {
		t.Fatalf("err: %v", err)
	}

	testutil.WaitForResult(func() (bool, error) {
		health, _, err := c.Health().Node("foobar", nil)
		if err != nil {
			return false, err
		}

		if len(health) != 0 {
			return false, fmt.Errorf("CheckID:service:redis1 is not deregistered")
		}

		return true, nil
	}, func(err error) {
		t.Fatalf("err: %s", err)
	})

	// Test node deregistration of the previously registered node
	dereg = &CatalogDeregistration{
		Datacenter: "dc1",
		Node:       "foobar",
		Address:    "192.168.10.10",
	}

	if _, err := catalog.Deregister(dereg, nil); err != nil {
		t.Fatalf("err: %v", err)
	}

	testutil.WaitForResult(func() (bool, error) {
		node, _, err := catalog.Node("foobar", nil)
		if err != nil {
			return false, err
		}

		if node != nil {
			return false, fmt.Errorf("node is not deregistered: %v", node)
		}

		return true, nil
	}, func(err error) {
		t.Fatalf("err: %s", err)
	})
}


text:
#ifndef cmWIXDirectoriesSourceWriter_h
#define cmWIXDirectoriesSourceWriter_h

#include "cmWIXSourceWriter.h"

#include <CPack/cmCPackGenerator.h>

#include <string>

/** \class cmWIXDirectoriesSourceWriter
 * \brief Helper class to generate directories.wxs
 */
class cmWIXDirectoriesSourceWriter : public cmWIXSourceWriter
{
public:
  cmWIXDirectoriesSourceWriter(cmCPackLog* logger,
    std::string const& filename);

  void EmitStartMenuFolder(std::string const& startMenuFolder);

  void EmitDesktopFolder();

  void EmitStartupFolder();

  size_t BeginInstallationPrefixDirectory(
      std::string const& programFilesFolderId,
      std::string const& installRootString);

  void EndInstallationPrefixDirectory(size_t size);
};

#endif


text:
/**
 * This package contains interfaces for set API which enhance the performance and functionality of {@link java.util.Set}.
 *

 *      This package contains 6 interfaces:
 *

 *

 *       {@link com.gs.collections.api.set.FixedSizeSet} - a set that may be mutated, but cannot grow or shrink in size.
 *

 *

 *       {@link com.gs.collections.api.set.ImmutableSet} - the non-modifiable equivalent interface to {@link com.gs.collections.api.set.MutableSet}.
 *

 *

 *       {@link com.gs.collections.api.set.MutableSet} - an implementation of a JCF Set which provides internal iterator methods matching the Smalltalk Collection protocol.
 *

 *

 *       {@link com.gs.collections.api.set.Pool} - locates an object in the pool which is equal to {@code key}.
 *

 *

 *       {@link com.gs.collections.api.set.SetIterable} - a read-only Set API, with the minor exception inherited from {@link java.lang.Iterable} (iterable.iterator().remove()).
 *

 *

 *       {@link com.gs.collections.api.set.UnsortedSetIterable} - an iterable whose items are unique.
 *

 *

 */
package com.gs.collections.api.set;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">idouban</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

    <string name="drawer_open">Open navigation drawer</string>
    <string name="drawer_close">Close navigation drawer</string>

    <string name="retry">重试</string>
    <string name="load_more">加载更多</string>

    <string name="double_press_back_exit_msg">再按一次退出</string>

</resources>


text:
Acest program este un text editor care poate fi rulat in **python 2.7.8** si poate fi preluat prin copy/paste din pagina []() sau prin clonarea acestui git in terminal prin comanda:

            git clone https://github.com/mhcrnl/PmwTkEx.git

Acest program a fost rulat pe un sistem **Fedora 21** cu **Python 2.7.8** in urmatoarele aplicatii:

1.Terminal:

            python texteditor.py

2.IDLE 2.7.8

3.Geany 1.25

####This is a repository for a text editor.

![texteditor.png](img/texteditor.png)


text:
<?php
//============================================================+
// File name   : example_058.php
// Begin       : 2010-04-22
// Last Update : 2010-05-20
//
// Description : Example 058 for TCPDF class
//               SVG Image
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com s.r.l.
//               Via Della Pace, 11
//               09044 Quartucciu (CA)
//               ITALY
//               www.tecnick.com
//               info@tecnick.com
//============================================================+

require_once('../config/lang/eng.php');
require_once('../tcpdf.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 058');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 058', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

//set some language-dependent strings
$pdf->setLanguageArray($l);

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

// set font
$pdf->SetFont('helvetica', '', 10);

// add a page
$pdf->AddPage();

// NOTE: Uncomment the following line to rasterize SVG image using the ImageMagick library.
//$pdf->setRasterizeVectorImages(true);

$pdf->ImageSVG($file='../images/testsvg.svg', $x=15, $y=30, $w='', $h='', $link='http://www.tcpdf.org', $align='', $palign='', $border=1, $fitonpage=false);

$pdf->ImageSVG($file='../images/tux.svg', $x=30, $y=100, $w='', $h=100, $link='', $align='', $palign='', $border=0, $fitonpage=false);

$pdf->SetFont('helvetica', '', 8);
$pdf->SetY(195);
$txt = '© The copyright holder of the above Tux image is Larry Ewing, allows anyone to use it for any purpose, provided that the copyright holder is properly attributed. Redistribution, derivative work, commercial use, and all other use is permitted.';
$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);

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

//Close and output PDF document
$pdf->Output('example_058.pdf', 'I');

//============================================================+
// END OF FILE
//============================================================+
?>


text:
import React from 'react';
import { connect } from 'react-redux';
import { getScreen } from '../actions/screenActions';

let GetScreen = ({ dispatch }) => {
    return (

    )
}

/*

 dispatch(getScreen("zzzzzcreen"))} >
            Get Screen URL

 */
GetScreen = connect()(GetScreen);

export default GetScreen;


text:
class VueServiceGenerator : public ServiceGenerator {
public:
    VueServiceGenerator(const QString &service, const QList<QPair<QString, QMetaType::Type>> &fields, int pkIdx, int lockRevIdx);
    ~VueServiceGenerator() { }

private:
    virtual QString headerFileTemplate() const;
    virtual QString sourceFileTemplate() const;
};


text:
var lUpdate = document.getElementById('l-update'),
	lSlide = document.getElementById('l-slide'),
	lSet = document.getElementById('l-set'),
	lChange = document.getElementById('l-change'),
	lStart = document.getElementById('l-start'),
	lEnd = document.getElementById('l-end');

slider.noUiSlider.on('update', function(){
	addClassFor(lUpdate, 'tShow', 450);
});

slider.noUiSlider.on('slide', function(){
	addClassFor(lSlide, 'tShow', 450);
});

slider.noUiSlider.on('set', function(){
	addClassFor(lSet, 'tShow', 450);
});

slider.noUiSlider.on('change', function(){
	addClassFor(lChange, 'tShow', 450);
});

slider.noUiSlider.on('start', function(){
	addClassFor(lStart, 'tShow', 450);
});

slider.noUiSlider.on('end', function(){
	addClassFor(lEnd, 'tShow', 450);
});


text:
ScopedLog::ScopedLog(const wchar_t* filepath)
    : log_file_(INVALID_HANDLE_VALUE) {
  // Create the log file for append.
  log_file_ = CreateFile(filepath,
                         GENERIC_WRITE,
                         0,     // Share mode
                         NULL,  // Security attributes
                         OPEN_ALWAYS,
                         FILE_ATTRIBUTE_NORMAL,
                         NULL);
  if (log_file_ != INVALID_HANDLE_VALUE)
    SetFilePointer(log_file_, 0, NULL, FILE_END);
}

ScopedLog::~ScopedLog() {
  if (log_file_ == INVALID_HANDLE_VALUE)
    return;
  CloseHandle(log_file_);
}

void ScopedLog::Append(const wchar_t* format, ...) {
  va_list ap;
  wchar_t log_string[1024];
  if (log_file_ == INVALID_HANDLE_VALUE)
    return;

  va_start(ap, format);
  StringCbVPrintf(log_string, sizeof(log_string), format, ap);
  va_end(ap);

  SYSTEMTIME systime;
  wchar_t log_entry[1040];
  size_t cb = 0;
  DWORD bytes_written = 0;
  GetLocalTime(&systime);
  StringCbPrintf(log_entry, sizeof(log_entry),
                 L"%02d:%02d:%02d.%03d %s\r\n",
                 systime.wHour,
                 systime.wMinute,
                 systime.wSecond,
                 systime.wMilliseconds,
                 log_string);
  StringCbLength(log_entry, sizeof(log_entry), &cb);
  WriteFile(log_file_, log_entry, cb, &bytes_written, NULL);
}


text:
var paypal = require('paypal-rest-sdk');
var config = require('./config');

paypal.configure(config.paypal);

module.exports = paypal;


text:
@protocol FBFormPhoneViewCellDelegate <NSObject>

-(void)phoneTextField:(NSString *)phone;

@end

@interface FBFormPhoneViewCell : UITableViewCell

@property(nonatomic, weak) id<FBFormPhoneViewCellDelegate> delegate;

@end


text:
namespace MindEngine.Core.Scene.Widget.Control
{
    using Component.Style;
    using Control.Style;
    using Element;
    using Element.Style;

    public class MMControlSkin
    {
        public MMControlSkin(string name)
        {
            this.Name = name;
        }

        public string Name { get; }

        /// <summary>
        /// Control style defines a set of control specific property that could
        /// be reused.
        /// </summary>
        public MMWidgetDesignCollection<MMControlStyle> ControlStyles { get; set; } = new MMWidgetDesignCollection<MMControlStyle>();

        /// <summary>
        /// Component style defines a set of control specific property that could
        /// be reused.
        /// </summary>
        public MMWidgetDesignCollection<MMComponentStyle> ComponentStyles { get; set; } = new MMWidgetDesignCollection<MMComponentStyle>();

        /// <summary>
        /// Control element defines a set of non-control elements that could be
        /// reused in widget design.
        /// </summary>
        public MMWidgetDesignCollection<MMElementStyle> ElementStyles { get; set; } = new MMWidgetDesignCollection<MMElementStyle>();
    }
}


text:
template <typename Duration>
constexpr long check_seconds(Duration d)
{
    using HMS = std::chrono::hh_mm_ss<Duration>;
    ASSERT_SAME_TYPE(std::chrono::seconds, decltype(std::declval<HMS>().seconds()));
    ASSERT_NOEXCEPT(                                std::declval<HMS>().seconds());
    return HMS(d).seconds().count();
}

int main(int, char**)
{
    using microfortnights = std::chrono::duration<int, std::ratio<756, 625>>;

    static_assert( check_seconds(std::chrono::seconds( 1)) == 1, "");
    static_assert( check_seconds(std::chrono::seconds(-1)) == 1, "");

    assert( check_seconds(std::chrono::seconds( 5000)) == 20);
    assert( check_seconds(std::chrono::seconds(-5000)) == 20);
    assert( check_seconds(std::chrono::minutes( 5000)) == 0);
    assert( check_seconds(std::chrono::minutes(-5000)) == 0);
    assert( check_seconds(std::chrono::hours( 11))     == 0);
    assert( check_seconds(std::chrono::hours(-11))     == 0);

    assert( check_seconds(std::chrono::milliseconds( 123456789LL)) == 36);
    assert( check_seconds(std::chrono::milliseconds(-123456789LL)) == 36);
    assert( check_seconds(std::chrono::microseconds( 123456789LL)) == 3);
    assert( check_seconds(std::chrono::microseconds(-123456789LL)) == 3);
    assert( check_seconds(std::chrono::nanoseconds( 123456789LL))  == 0);
    assert( check_seconds(std::chrono::nanoseconds(-123456789LL))  == 0);

    assert( check_seconds(microfortnights(  1000)) ==  9);
    assert( check_seconds(microfortnights( -1000)) ==  9);
    assert( check_seconds(microfortnights( 10000)) == 36);
    assert( check_seconds(microfortnights(-10000)) == 36);

    return 0;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Using as: ESA/390 Opcodes</title>

<meta name="description" content="Using as: ESA/390 Opcodes">
<meta name="keywords" content="Using as: ESA/390 Opcodes">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="AS-Index.html#AS-Index" rel="index" title="AS Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="ESA_002f390_002dDependent.html#ESA_002f390_002dDependent" rel="up" title="ESA/390-Dependent">
<link href="i386_002dDependent.html#i386_002dDependent" rel="next" title="i386-Dependent">
<link href="ESA_002f390-Directives.html#ESA_002f390-Directives" rel="prev" title="ESA/390 Directives">

Previous: ESA/390 Directives, Up: ESA/390-Dependent   [Contents][Index]

9.14.6 Opcodes

For detailed information on the ESA/390 machine instruction set, see
ESA/390 Principles of Operation (IBM Publication Number DZ9AR004).


text:
package org.b3log.latke.repository.jdbc.mapping;

import org.b3log.latke.repository.jdbc.util.FieldDefinition;

/**
 * the interface for mapping.
 *
 * @author Love Yao
 * @version 1.0.0.0, Jan 12, 2012
 */
public interface Mapping {

    /**
     * for mapping from java definition to database table-definition sql.
     *
     * @param definition {@link FieldDefinition}
     * @return table-definition sql.
     */
    String toDataBaseSting(FieldDefinition definition);
}


text:
require ('coffeescript/register');
var config = require('../config/config'),
    AWS = require('aws-sdk'),
    Promise = require("bluebird"),
    ImageQueue = Promise.promisifyAll(require('../app/services/image_queue'));

var running = false;

/*
*
* New Way to do sleep without blocking the main thead
*
*/

function sleep(ms) {
  return new Promise(resolve => setTimeout(function() { dequeue(); }, ms));
}

async function dequeue() {
  if(!running) {
    try {
      running = true;
      console.log('executing');
      image_queue = new ImageQueue(config.input_queue);
      image_queue.dequeue(function(err,local_filename) {
        //do nothing
        if(err) {
          console.log(err);
        } else {
          console.log('successfully proccessed image ' + local_filename)
        }
        running = false;
      });
      // setTimeout(function() { running = false; }, 8000);
    } catch (err) {
      console.log(err)
      running = false;
    }
  } else {
    console.log('not executing');
  }
  await sleep(5000);
}

dequeue().catch(function(e) {
  console.log(e.stack);
  //best practice is to shut down the process due to memory leaks
  process.exit(1)
});

//Global catches for the workers.

//If you don't catch this and you don't handle the rejection the worker runs forever, I would rather have it finish if someone screws up.
//deprecated as down the road it will stop the process but for now, we need this.
process.on('unhandledRejection', (err) => {
  console.error((new Date).toUTCString() + ' unhandledRejection:', err.message)
  console.error(err.stack)
  process.exit(1)
});


text:
/**
 * InvQueForm.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.2RC2 Nov 16, 2004 (12:19:44 EST) WSDL2Java emitter.
 */

package com.baosight.ssbs.go.ws.domain;

public class InvQueForm  implements java.io.Serializable {
    private java.lang.String contractId;
    private java.lang.String customerId;
    private java.lang.String invDateFrom;
    private java.lang.String invDateTo;
    private java.lang.String invId;
    private java.lang.String password;
    private java.lang.String segNo;

    public InvQueForm() {
    }

    public InvQueForm(
           java.lang.String contractId,
           java.lang.String customerId,
           java.lang.String invDateFrom,
           java.lang.String invDateTo,
           java.lang.String invId,
           java.lang.String password,
           java.lang.String segNo) {
           this.contractId = contractId;
           this.customerId = customerId;
           this.invDateFrom = invDateFrom;
           this.invDateTo = invDateTo;
           this.invId = invId;
           this.password = password;
           this.segNo = segNo;
    }

    /**
     * Gets the contractId value for this InvQueForm.
     *
     * @return contractId
     */
    public java.lang.String getContractId() {
        return contractId;
    }

    /**
     * Sets the contractId value for this InvQueForm.
     *
     * @param contractId
     */
    public void setContractId(java.lang.String contractId) {
        this.contractId = contractId;
    }

    /**
     * Gets the customerId value for this InvQueForm.
     *
     * @return customerId
     */
    public java.lang.String getCustomerId() {
        return customerId;
    }

    /**
     * Sets the customerId value for this InvQueForm.
     *
     * @param customerId
     */
    public void setCustomerId(java.lang.String customerId) {
        this.customerId = customerId;
    }

    /**
     * Gets the invDateFrom value for this InvQueForm.
     *
     * @return invDateFrom
     */
    public java.lang.String getInvDateFrom() {
        return invDateFrom;
    }

    /**
     * Sets the invDateFrom value for this InvQueForm.
     *
     * @param invDateFrom
     */
    public void setInvDateFrom(java.lang.String invDateFrom) {
        this.invDateFrom = invDateFrom;
    }

    /**
     * Gets the invDateTo value for this InvQueForm.
     *
     * @return invDateTo
     */
    public java.lang.String getInvDateTo() {
        return invDateTo;
    }

    /**
     * Sets the invDateTo value for this InvQueForm.
     *
     * @param invDateTo
     */
    public void setInvDateTo(java.lang.String invDateTo) {
        this.invDateTo = invDateTo;
    }

    /**
     * Gets the invId value for this InvQueForm.
     *
     * @return invId
     */
    public java.lang.String getInvId() {
        return invId;
    }

    /**
     * Sets the invId value for this InvQueForm.
     *
     * @param invId
     */
    public void setInvId(java.lang.String invId) {
        this.invId = invId;
    }

    /**
     * Gets the password value for this InvQueForm.
     *
     * @return password
     */
    public java.lang.String getPassword() {
        return password;
    }

    /**
     * Sets the password value for this InvQueForm.
     *
     * @param password
     */
    public void setPassword(java.lang.String password) {
        this.password = password;
    }

    /**
     * Gets the segNo value for this InvQueForm.
     *
     * @return segNo
     */
    public java.lang.String getSegNo() {
        return segNo;
    }

    /**
     * Sets the segNo value for this InvQueForm.
     *
     * @param segNo
     */
    public void setSegNo(java.lang.String segNo) {
        this.segNo = segNo;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof InvQueForm)) return false;
        InvQueForm other = (InvQueForm) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.contractId==null && other.getContractId()==null) ||
             (this.contractId!=null &&
              this.contractId.equals(other.getContractId()))) &&
            ((this.customerId==null && other.getCustomerId()==null) ||
             (this.customerId!=null &&
              this.customerId.equals(other.getCustomerId()))) &&
            ((this.invDateFrom==null && other.getInvDateFrom()==null) ||
             (this.invDateFrom!=null &&
              this.invDateFrom.equals(other.getInvDateFrom()))) &&
            ((this.invDateTo==null && other.getInvDateTo()==null) ||
             (this.invDateTo!=null &&
              this.invDateTo.equals(other.getInvDateTo()))) &&
            ((this.invId==null && other.getInvId()==null) ||
             (this.invId!=null &&
              this.invId.equals(other.getInvId()))) &&
            ((this.password==null && other.getPassword()==null) ||
             (this.password!=null &&
              this.password.equals(other.getPassword()))) &&
            ((this.segNo==null && other.getSegNo()==null) ||
             (this.segNo!=null &&
              this.segNo.equals(other.getSegNo())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getContractId() != null) {
            _hashCode += getContractId().hashCode();
        }
        if (getCustomerId() != null) {
            _hashCode += getCustomerId().hashCode();
        }
        if (getInvDateFrom() != null) {
            _hashCode += getInvDateFrom().hashCode();
        }
        if (getInvDateTo() != null) {
            _hashCode += getInvDateTo().hashCode();
        }
        if (getInvId() != null) {
            _hashCode += getInvId().hashCode();
        }
        if (getPassword() != null) {
            _hashCode += getPassword().hashCode();
        }
        if (getSegNo() != null) {
            _hashCode += getSegNo().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(InvQueForm.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://domain.ws.go.ssbs.baosight.com", "InvQueForm"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("contractId");
        elemField.setXmlName(new javax.xml.namespace.QName("http://domain.ws.go.ssbs.baosight.com", "contractId"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("customerId");
        elemField.setXmlName(new javax.xml.namespace.QName("http://domain.ws.go.ssbs.baosight.com", "customerId"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("invDateFrom");
        elemField.setXmlName(new javax.xml.namespace.QName("http://domain.ws.go.ssbs.baosight.com", "invDateFrom"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("invDateTo");
        elemField.setXmlName(new javax.xml.namespace.QName("http://domain.ws.go.ssbs.baosight.com", "invDateTo"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("invId");
        elemField.setXmlName(new javax.xml.namespace.QName("http://domain.ws.go.ssbs.baosight.com", "invId"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("password");
        elemField.setXmlName(new javax.xml.namespace.QName("http://domain.ws.go.ssbs.baosight.com", "password"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("segNo");
        elemField.setXmlName(new javax.xml.namespace.QName("http://domain.ws.go.ssbs.baosight.com", "segNo"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
"""Provides Pixel Bundle object for working with T1 pixels."""

from __future__ import absolute_import
from .. import t1types
from ..entity import Entity

class Pixel(Entity):
    """Pixel entity, or entity_type == 'pixel_bundle'"""
    collection = 'pixel_bundles'
    resource = 'pixel_bundle'
    _relations = {
        'advertiser', 'agency', 'provider',
    }
    _roi_fields = t1types.enum({'S1', 'S2', 'V1', 'V2'}, None)
    _pixel_types = t1types.enum({'creative', 'event', 'data', 'segment'},
                                'event')
    _pricing = t1types.enum({'CPM', 'CPTS'}, 'CPM')
    _rmx_conv_types = t1types.enum({'one', 'variable'}, 'one')
    _tag_types = t1types.enum({'dfa', 'uat', 'image', 'iframe', 'js'},
                              'image')
    _pull = {
        'advertiser_id': int,
        'agency_id': int,
        'cost_cpm': float,
        'cost_cpts': float,
        'cost_pct_cpm': float,
        'created_on': t1types.strpt,
        'currency': None,
        'currency_fixed': None,
        'eligible': t1types.int_to_bool,
        'external_identifier': None,
        'id': int,
        'keywords': None,
        'name': None,
        'pixel_type': None,
        'pricing': None,
        'provider_id': int,
        'revenue': None,
        'rmx_conversion_minutes': int,
        'rmx_conversion_type': None,
        'rmx_friendly': t1types.int_to_bool,
        'rmx_merit': t1types.int_to_bool,
        'rmx_pc_window_minutes': int,
        'rmx_pv_window_minutes': int,
        'segment_op': None,
        'status': t1types.int_to_bool,
        'tag_type': None,
        'tags': None,
        'type': None,
        'updated_on': t1types.strpt,
        'version': int,
    }

    _push = _pull.copy()
    _push.update({
        'cost_cpm': t1types.none_to_empty,
        'cost_pct_cpm': t1types.none_to_empty,
        'currency': _roi_fields,
        'eligible': int,
        'pixel_type': _pixel_types,
        'pricing': _pricing,
        'revenue': _roi_fields,
        'rmx_conversion_type': _rmx_conv_types,
        'rmx_friendly': int,
        'rmx_merit': int,
        'status': int,
        'tag_type': _tag_types,
    })
    _readonly = Entity._readonly | {'external_identifier', 'tags', }
    _readonly_update = {'advertiser_id', 'agency_id', 'pixel_type',
                        'provider_id', 'tag_type'}

    def __init__(self, session, properties=None, **kwargs):
        super(Pixel, self).__init__(session, properties, **kwargs)

    def save(self, data=None, url=None):
        """Extra validation for data pixels

        :param data: dict optional data to use instead of self
        :return: None. Object is updated or error is raised
        """
        if self.pixel_type != 'data':
            return super(Pixel, self).save(data=data)

        if data is None:
            data = self.properties.copy()
        if self.pricing == 'CPM':
            data.pop('cost_cpts', None)
            if not getattr(self, 'cost_pct_cpm', None):
                data.pop('cost_pct_cpm', None)
            elif not getattr(self, 'cost_cpm', None):
                data.pop('cost_cpm', None)
        else:
            data.pop('cost_cpm', None)
            data.pop('cost_pct_cpm', None)

        return super(Pixel, self).save(data=data, url=url)

PixelBundle = Pixel


text:
package org.rioproject.gnostic.test;

import java.io.IOException;
import java.rmi.RemoteException;

/**
 * Provides ability to set the load for the TestService
 */
public interface TestService {
    enum Status {
        ALLOWED, DISALLOWED
    }
    double getLoad() throws RemoteException;
    void setLoad(double load) throws RemoteException;
    Status getStatus() throws IOException;
    void setStatus(Status status) throws IOException;
    void sendNotify() throws IOException;
    void executedRHS() throws IOException;
    int getNotificationCount() throws IOException;
    int getRHSExecutedCount() throws IOException;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCvSharp;
using SampleBase;

namespace CStyleSamplesCS
{
    /// <summary>
    /// samples/c/squares.c
    /// </summary>
    class Squares
    {
        const int Thresh = 50;
        const string WindowName = "Square Detection Demo";
        readonly static string[] TargetFiles =
        {
            FilePath.Image.Square1,
            FilePath.Image.Square2,
            FilePath.Image.Square3,
            FilePath.Image.Square4,
            FilePath.Image.Square5,
            FilePath.Image.Square6,
        };

        public Squares()
        {
            // create memory storage that will contain all the dynamic data
            CvMemStorage storage = new CvMemStorage(0);

            for (int i = 0; i < TargetFiles.Length; i++)
            {
                // load i-th image
                using (IplImage img = new IplImage(TargetFiles[i], LoadMode.Color))
                {
                    // create window and a trackbar (slider) with parent "image" and set callback
                    // (the slider regulates upper threshold, passed to Canny edge detector)
                    Cv.NamedWindow(WindowName, WindowMode.AutoSize);

                    // find and draw the squares
                    DrawSquares(img, FindSquares4(img, storage));
                }

                // clear memory storage - reset free space position
                storage.Clear();

                // wait for key.
                // Also the function cvWaitKey takes care of event processing
                int c = Cv.WaitKey(0);
                if ((char)c == 27)
                    break;
            }

            Cv.DestroyWindow(WindowName);
        }

        /// <summary>
        /// helper function:
        /// finds a cosine of Angle between vectors
        /// from pt0->pt1 and from pt0->pt2
        /// </summary>
        /// <param name="pt1"></param>
        /// <param name="pt2"></param>
        /// <param name="pt0"></param>
        /// <returns></returns>
        static double Angle(CvPoint pt1, CvPoint pt2, CvPoint pt0)
        {
            double dx1 = pt1.X - pt0.X;
            double dy1 = pt1.Y - pt0.Y;
            double dx2 = pt2.X - pt0.X;
            double dy2 = pt2.Y - pt0.Y;
            return (dx1 * dx2 + dy1 * dy2) / Math.Sqrt((dx1 * dx1 + dy1 * dy1) * (dx2 * dx2 + dy2 * dy2) + 1e-10);
        }

        /// <summary>
        /// returns sequence of squares detected on the image.
        /// the sequence is stored in the specified memory storage
        /// </summary>
        /// <param name="img"></param>
        /// <param name="storage"></param>
        /// <returns></returns>
        static CvPoint[] FindSquares4(IplImage img, CvMemStorage storage)
        {
            const int N = 11;

            CvSize sz = new CvSize(img.Width & -2, img.Height & -2);
            IplImage timg = img.Clone(); // make a copy of input image
            IplImage gray = new IplImage(sz, BitDepth.U8, 1);
            IplImage pyr = new IplImage(sz.Width / 2, sz.Height / 2, BitDepth.U8, 3);
            // create empty sequence that will contain points -
            // 4 points per square (the square's vertices)
            CvSeq<CvPoint> squares = new CvSeq<CvPoint>(SeqType.Zero, CvSeq.SizeOf, storage);

            // select the maximum ROI in the image
            // with the width and height divisible by 2
            timg.ROI = new CvRect(0, 0, sz.Width, sz.Height);

            // down-Scale and upscale the image to filter out the noise
            Cv.PyrDown(timg, pyr, CvFilter.Gaussian5x5);
            Cv.PyrUp(pyr, timg, CvFilter.Gaussian5x5);
            IplImage tgray = new IplImage(sz, BitDepth.U8, 1);

            // find squares in every color plane of the image
            for (int c = 0; c < 3; c++)
            {
                // extract the c-th color plane
                timg.COI = c + 1;
                Cv.Copy(timg, tgray, null);

                // try several threshold levels
                for (int l = 0; l < N; l++)
                {
                    // hack: use Canny instead of zero threshold level.
                    // Canny helps to catch squares with gradient shading
                    if (l == 0)
                    {
                        // apply Canny. Take the upper threshold from slider
                        // and set the lower to 0 (which forces edges merging)
                        Cv.Canny(tgray, gray, 0, Thresh, ApertureSize.Size5);
                        // dilate canny output to remove potential
                        // holes between edge segments
                        Cv.Dilate(gray, gray, null, 1);
                    }
                    else
                    {
                        // apply threshold if l!=0:
                        //     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
                        Cv.Threshold(tgray, gray, (l + 1) * 255.0 / N, 255, ThresholdType.Binary);
                    }

                    // find contours and store them all as a list
                    CvSeq<CvPoint> contours;
                    Cv.FindContours(gray, storage, out contours, CvContour.SizeOf, ContourRetrieval.List, ContourChain.ApproxSimple, new CvPoint(0, 0));

                    // test each contour
                    while (contours != null)
                    {
                        // approximate contour with accuracy proportional
                        // to the contour perimeter
                        CvSeq<CvPoint> result = Cv.ApproxPoly(contours, CvContour.SizeOf, storage, ApproxPolyMethod.DP, contours.ContourPerimeter() * 0.02, false);
                        // square contours should have 4 vertices after approximation
                        // relatively large area (to filter out noisy contours)
                        // and be convex.
                        // Note: absolute value of an area is used because
                        // area may be positive or negative - in accordance with the
                        // contour orientation
                        if (result.Total == 4 && Math.Abs(result.ContourArea(CvSlice.WholeSeq)) > 1000 && result.CheckContourConvexity())
                        {
                            double s = 0;

                            for (int i = 0; i < 5; i++)
                            {
                                // find minimum Angle between joint
                                // edges (maximum of cosine)
                                if (i >= 2)
                                {
                                    double t = Math.Abs(Angle(result[i].Value, result[i - 2].Value, result[i - 1].Value));
                                    s = s > t ? s : t;
                                }
                            }

                            // if cosines of all angles are small
                            // (all angles are ~90 degree) then write quandrange
                            // vertices to resultant sequence
                            if (s < 0.3)
                            {
                                for (int i = 0; i < 4; i++)
                                {
                                    //Console.WriteLine(result[i]);
                                    squares.Push(result[i].Value);
                                }
                            }
                        }

                        // take the next contour
                        contours = contours.HNext;
                    }
                }
            }

            // release all the temporary images
            gray.Dispose();
            pyr.Dispose();
            tgray.Dispose();
            timg.Dispose();

            return squares.ToArray();
        }

        /// <summary>
        /// the function draws all the squares in the image
        /// </summary>
        /// <param name="img"></param>
        /// <param name="squares"></param>
        static void DrawSquares(IplImage img, CvPoint[] squares)
        {
            using (IplImage cpy = img.Clone())
            {
                // read 4 sequence elements at a time (all vertices of a square)
                for (int i = 0; i < squares.Length; i += 4)
                {
                    CvPoint[] pt = new CvPoint[4];

                    // read 4 vertices
                    pt[0] = squares[i + 0];
                    pt[1] = squares[i + 1];
                    pt[2] = squares[i + 2];
                    pt[3] = squares[i + 3];

                    // draw the square as a closed polyline
                    Cv.PolyLine(cpy, new CvPoint[][] { pt }, true, CvColor.Green, 3, LineType.AntiAlias, 0);
                }

                // show the resultant image
                Cv.ShowImage(WindowName, cpy);
            }
        }
    }
}


text:
<?php
	include_once '../../includes/ChatlyAuth.php';
	ChatlyAuth::startSecureSession();

	ChatlyAuth::logout();

	header('Location: /');


text:
Why Not Other Tech:

Alternative Technology Paths. Most of these will be found to be complementary.

    Document Assembly.

    Rules as Code.

    NLP text crunching.

    Word and CRM.


text:
// Copyright 2012 Google Inc.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @description Tests that Intl.DateTimeFormat.prototype is an object that
 * has been initialized as an Intl.DateTimeFormat.
 * @author: Roozbeh Pournader
 */

// test by calling a function that would fail if "this" were not an object
// initialized as an Intl.DateTimeFormat
if (typeof Intl.DateTimeFormat.prototype.format(0) !== "string") {
    $ERROR("Intl.DateTimeFormat's prototype is not an object that has been " +
        "initialized as an Intl.DateTimeFormat");
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MtApi.Monitors.Triggers;

namespace MtApi.Monitors
{
    public class TradeMonitor : MtMonitorBase
    {
        #region Fields
        private List<MtOrder> _prevOrders;
        private readonly object _locker = new object();
        #endregion

        #region Events
        //
        // Summary:
        //     Occurs when orders are opened or closed.
        public event EventHandler<AvailabilityOrdersEventArgs> AvailabilityOrdersChanged;
        #endregion

        #region ctor
        /// <summary>
        /// Constructor for initializing an instance of <see cref="TradeMonitor"/>.
        /// </summary>
        /// <param name="apiClient">The <see cref="MtApiClient"/> which will be used to communicate with MetaTrader.</param>
        /// <param name="monitorTrigger">The custom instance of <see cref="IMonitorTrigger"/> which will be used to trigger this instance of <see cref="TradeMonitor"/>.</param>
        public TradeMonitor(MtApiClient apiClient, IMonitorTrigger monitorTrigger) : base(apiClient, monitorTrigger) { }
        #endregion

        protected override void OnMtConnected()
        {
            InitialCheck();
            base.OnMtConnected();
        }
        protected override void OnStart()
        {
            if (IsMtConnected)
                InitialCheck();
            base.OnStart();
        }

        protected override void OnTriggerRaised()
        {
            if (IsMtConnected)
                Check();
        }

        private void Check()
        {
            try
            {
                CheckOrders();
            }
            catch (MtConnectionException)
            {
                //TODO: write error to log
            }
            catch (MtExecutionException)
            {
                //TODO: write error to log
            }
        }
        private void InitialCheck()
        {
            lock (_locker)
                _prevOrders = null;

            Task.Factory.StartNew(Check);
        }
        private void CheckOrders()
        {
            var openedOrders = new List<MtOrder>();
            var closedOrders = new List<MtOrder>();
            List<MtOrder> prevOrders;

            // get current orders from MetaTrader
            var tradesOrders = ApiClient.GetOrders(OrderSelectSource.MODE_TRADES);

            lock (_locker)
                prevOrders = _prevOrders;

            if (prevOrders != null) //skip checking on first load orders
            {
                //check open orders
                openedOrders = tradesOrders.Where(to => prevOrders.Find(a => a.Ticket == to.Ticket) == null).ToList();

                //check closed orders
                var closeOrdersTemp = prevOrders.Where(po => tradesOrders.Find(a => a.Ticket == po.Ticket) == null).ToList();

                if (closeOrdersTemp.Count > 0)
                {
                    //get closed orders from history with actual values
                    var historyOrders = ApiClient.GetOrders(OrderSelectSource.MODE_HISTORY);
                    closedOrders = closeOrdersTemp.Where(cot => historyOrders.Find(a => a.Ticket == cot.Ticket) != null).ToList();
                }
            }

            lock (_locker)
                _prevOrders = tradesOrders;

            if (openedOrders.Count > 0 || closedOrders.Count > 0)
            {
                AvailabilityOrdersChanged?.Invoke(this, new AvailabilityOrdersEventArgs(openedOrders, closedOrders));
            }
        }
    }
}


text:
// ***********************************************************************
// <copyright file="OrderCategoryConfiguration.cs" company="Holotrek">
//     Copyright © Holotrek 2016
// </copyright>
// ***********************************************************************

using System.Data.Entity.ModelConfiguration;
using Kore.Domain.EF.Tests.Domain.Orders.Models;

namespace Kore.Domain.EF.Tests.Domain.Orders
{
    /// <summary>
    /// The EF configuration class for the Category entity
    /// </summary>
    public class OrderCategoryConfiguration : EntityTypeConfiguration<OrderCategory>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="OrderCategoryConfiguration" /> class.
        /// </summary>
        /// <param name="repository">The repository.</param>
        public OrderCategoryConfiguration(OrderRepository repository)
        {
            repository.ConfigureEntity(this);
            this.ToTable("Categories").HasKey(x => x.CategoryId);
        }
    }
}


text:
// TODO: add ts support for next-swc api
// @ts-ignore
import { parse } from '../../swc'
// @ts-ignore
import { getBaseSWCOptions } from '../../swc/options'
import { getRawPageExtensions } from '../../utils'

function isClientComponent(importSource: string, pageExtensions: string[]) {
  return new RegExp(`\\.client(\\.(${pageExtensions.join('|')}))?`).test(
    importSource
  )
}

function isServerComponent(importSource: string, pageExtensions: string[]) {
  return new RegExp(`\\.server(\\.(${pageExtensions.join('|')}))?`).test(
    importSource
  )
}

function isNextComponent(importSource: string) {
  return (
    importSource.includes('next/link') || importSource.includes('next/image')
  )
}

export function isImageImport(importSource: string) {
  // TODO: share extension with next/image
  // TODO: add other static assets, jpeg -> jpg
  return ['jpg', 'jpeg', 'png', 'webp', 'avif'].some((imageExt) =>
    importSource.endsWith('.' + imageExt)
  )
}

async function parseImportsInfo(
  resourcePath: string,
  source: string,
  imports: Array<string>,
  isClientCompilation: boolean,
  pageExtensions: string[]
): Promise<{
  source: string
  defaultExportName: string
}> {
  const opts = getBaseSWCOptions({
    filename: resourcePath,
    globalWindow: isClientCompilation,
  })

  const ast = await parse(source, { ...opts.jsc.parser, isModule: true })
  const { body } = ast
  const beginPos = ast.span.start
  let transformedSource = ''
  let lastIndex = 0
  let defaultExportName
  for (let i = 0; i < body.length; i++) {
    const node = body[i]
    switch (node.type) {
      case 'ImportDeclaration': {
        const importSource = node.source.value
        if (!isClientCompilation) {
          if (
            !(
              isClientComponent(importSource, pageExtensions) ||
              isNextComponent(importSource) ||
              isImageImport(importSource)
            )
          ) {
            continue
          }
          const importDeclarations = source.substring(
            lastIndex,
            node.source.span.start - beginPos
          )
          transformedSource += importDeclarations
          transformedSource += JSON.stringify(`${node.source.value}?flight`)
        } else {
          // For the client compilation, we skip all modules imports but
          // always keep client components in the bundle. All client components
          // have to be imported from either server or client components.
          if (
            !(
              isClientComponent(importSource, pageExtensions) ||
              isServerComponent(importSource, pageExtensions) ||
              // Special cases for Next.js APIs that are considered as client
              // components:
              isNextComponent(importSource) ||
              isImageImport(importSource)
            )
          ) {
            continue
          }
        }

        lastIndex = node.source.span.end - beginPos
        imports.push(`require(${JSON.stringify(importSource)})`)
        continue
      }
      case 'ExportDefaultDeclaration': {
        const def = node.decl
        if (def.type === 'Identifier') {
          defaultExportName = def.name
        } else if (def.type === 'FunctionExpression') {
          defaultExportName = def.identifier.value
        }
        break
      }
      default:
        break
    }
  }

  if (!isClientCompilation) {
    transformedSource += source.substring(lastIndex)
  }

  return { source: transformedSource, defaultExportName }
}

export default async function transformSource(
  this: any,
  source: string
): Promise<string> {
  const { client: isClientCompilation, pageExtensions: pageExtensionsJson } =
    this.getOptions()
  const { resourcePath } = this
  const pageExtensions = JSON.parse(pageExtensionsJson)

  if (typeof source !== 'string') {
    throw new Error('Expected source to have been transformed to a string.')
  }

  if (resourcePath.includes('/node_modules/')) {
    return source
  }

  const imports: string[] = []
  const { source: transformedSource, defaultExportName } =
    await parseImportsInfo(
      resourcePath,
      source,
      imports,
      isClientCompilation,
      getRawPageExtensions(pageExtensions)
    )

  /**
   * Server side component module output:
   *
   * export default function ServerComponent() { ... }
   * + export const __rsc_noop__=()=>{ ... }
   * + ServerComponent.__next_rsc__=1;
   *
   * Client side component module output:
   *
   * The function body of ServerComponent will be removed
   */

  const noop = `export const __rsc_noop__=()=>{${imports.join(';')}}`
  const defaultExportNoop = isClientCompilation
    ? `export default function ${defaultExportName}(){}\n${defaultExportName}.__next_rsc__=1;`
    : defaultExportName
    ? `${defaultExportName}.__next_rsc__=1;`
    : ''

  const transformed = transformedSource + '\n' + noop + '\n' + defaultExportNoop

  return transformed
}


text:
section.settings {
  padding: 12px;
}


text:
@interface BBBMockBundle : NSBundle
@property (nonatomic, strong) NSDictionary *infoDictionaryToReturn;
@property (nonatomic, copy) NSString *currentAppVersion;
@property (nonatomic, copy) NSString *currentBundleVersion;
@end


text:
<?php

    return array(

        // The root of the project (note that this is the directory below the application).
        'sourcePath' => dirname(__FILE__) . '/..',
        // Where the messge files should be placed.
        'messagePath' => dirname(__FILE__) . '/../messages',
        // The list of languages that message files should be created for.
        'languages' => array(),
        // What file types should be scanned?
        'fileTypes' => array('php'),
        // Yii already has translation for itself, so exclude the framework directory.
        'exclude' => array('/vendor'),

        // These are the defaults, but specified here as a reference should you wish to change them at a later date.
        'translator' => 'Yii::t',
        'overwrite' => true,
        'removeOld' => false,
        'sort' => false,

    );


text:
import pytest
from pytest import approx

import pyomo.core as po

import calliope
from calliope.test.common.util import build_test_model as build_model

class TestCostMinimisationObjective:
    def test_nationalscale_minimize_emissions(self):
        model = calliope.examples.national_scale(
            scenario="minimize_emissions_costs",
            override_dict={"model.subset_time": ["2005-01-01", "2005-01-01"]},
        )
        model.run()

        assert model.results.energy_cap.loc["region1-2", "csp"] == approx(10000)
        assert model.results.energy_cap.loc[
            "region1", "ac_transmission:region2"
        ] == approx(10000)

        assert model.results.carrier_prod.sum("timesteps").loc[
            "power", "region1", "ccgt"
        ] == approx(66530.36492823533)

        assert float(model.results.cost.loc[{"costs": "emissions"}].sum()) == approx(
            13129619.1
        )

    def test_nationalscale_maximize_utility(self):
        model = calliope.examples.national_scale(
            scenario="maximize_utility_costs",
            override_dict={"model.subset_time": ["2005-01-01", "2005-01-01"]},
        )
        model.run()

        assert model.results.energy_cap.loc["region1-2", "csp"] == approx(10000.0)
        assert model.results.energy_cap.loc[
            "region1", "ac_transmission:region2"
        ] == approx(10000.0)

        assert model.results.carrier_prod.sum("timesteps").loc[
            "power", "region1", "ccgt"
        ] == approx(115569.4354)

        assert float(model.results.cost.sum()) > 6.6e7

    @pytest.mark.parametrize(
        "scenario,cost_class,weight",
        [
            ("monetary_objective", ["monetary"], [1]),
            ("emissions_objective", ["emissions"], [1]),
            ("weighted_objective", ["monetary", "emissions"], [0.9, 0.1]),
        ],
    )
    def test_weighted_objective_results(self, scenario, cost_class, weight):
        model = build_model(model_file="weighted_obj_func.yaml", scenario=scenario)
        model.run()
        assert sum(
            model.results.cost.loc[{"costs": cost_class[i]}].sum().item() * weight[i]
            for i in range(len(cost_class))
        ) == approx(po.value(model._backend_model.obj))

    def test_update_cost_classes_weights(self):
        model = build_model(
            model_file="weighted_obj_func.yaml", scenario="weighted_objective"
        )

        model.run()
        obj_value = model._backend_model.obj()
        total_cost = model.results.cost.sum()
        model.backend.update_param("objective_cost_class", {"monetary": 1.8})
        model.backend.update_param("objective_cost_class", {"emissions": 0.2})

        new_model = model.backend.rerun()
        updated_obj_value = model._backend_model.obj()
        updated_total_cost = new_model.results.cost.sum()

        assert updated_obj_value == 2 * obj_value
        assert updated_total_cost == total_cost


text: [cycle.js](https://github.com/staltz/cycle) experiment


text:
var fs         = require('fs');
var path       = require('path');
var fileExists = require('./file-exists');

// This module checks if a path is a local repository
// If the repository is a link, it will be falsy
module.exports = function (dir, callback) {
  fileExists(path.join(dir, '.git'), function (exists) {
    if (!exists) return callback(false);
    fs.lstat(dir, function (err, stat) {
      if (err) return callback(false);
      callback(!stat.isSymbolicLink());
    });
  });
};


text:
import unittest
import numpy as np

import op_test
import paddle
import paddle.fluid as fluid
import paddle.fluid.framework as framework
import paddle.fluid.layers as layers

paddle.enable_static()

class TestAssignValueOp(op_test.OpTest):
    def setUp(self):
        self.op_type = "assign_value"
        self.inputs = {}
        self.attrs = {}
        self.init_data()
        self.attrs["shape"] = self.value.shape
        self.attrs["dtype"] = framework.convert_np_dtype_to_dtype_(
            self.value.dtype
        )
        self.outputs = {"Out": self.value}

    def init_data(self):
        self.value = np.random.random(size=(2, 5)).astype(np.float32)
        self.attrs["fp32_values"] = [float(v) for v in self.value.flat]

    def test_forward(self):
        self.check_output()

class TestAssignValueOp2(TestAssignValueOp):
    def init_data(self):
        self.value = np.random.random(size=(2, 5)).astype(np.int32)
        self.attrs["int32_values"] = [int(v) for v in self.value.flat]

class TestAssignValueOp3(TestAssignValueOp):
    def init_data(self):
        self.value = np.random.random(size=(2, 5)).astype(np.int64)
        self.attrs["int64_values"] = [int(v) for v in self.value.flat]

class TestAssignValueOp4(TestAssignValueOp):
    def init_data(self):
        self.value = np.random.choice(a=[False, True], size=(2, 5)).astype(
            np.bool
        )
        self.attrs["bool_values"] = [int(v) for v in self.value.flat]

class TestAssignApi(unittest.TestCase):
    def setUp(self):
        self.init_dtype()
        self.value = (-100 + 200 * np.random.random(size=(2, 5))).astype(
            self.dtype
        )
        self.place = (
            fluid.CUDAPlace(0)
            if fluid.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )

    def init_dtype(self):
        self.dtype = "float32"

    def test_assign(self):
        main_program = fluid.Program()
        with fluid.program_guard(main_program):
            x = layers.create_tensor(dtype=self.dtype)
            layers.assign(input=self.value, output=x)

        exe = fluid.Executor(self.place)
        [fetched_x] = exe.run(main_program, feed={}, fetch_list=[x])
        np.testing.assert_array_equal(fetched_x, self.value)
        self.assertEqual(fetched_x.dtype, self.value.dtype)

class TestAssignApi2(TestAssignApi):
    def init_dtype(self):
        self.dtype = "int32"

class TestAssignApi3(TestAssignApi):
    def init_dtype(self):
        self.dtype = "int64"

class TestAssignApi4(TestAssignApi):
    def setUp(self):
        self.init_dtype()
        self.value = np.random.choice(a=[False, True], size=(2, 5)).astype(
            np.bool
        )
        self.place = (
            fluid.CUDAPlace(0)
            if fluid.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )

    def init_dtype(self):
        self.dtype = "bool"

if __name__ == '__main__':
    unittest.main()


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/rg_dialog_normal_cancel_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/rg_dialog_normal_cancel_normal"/>

</selector><!-- From: file:/F:/wumiao/sdkdemo/app/src/main/res/drawable/rg_dialog_normal_cancel_selector.xml -->


text:
"""Recurrent neural network module."""

from . import rnn_cell
from .rnn_cell import *

from . import rnn
from .rnn import *

from . import io
from .io import *


text:
<?php

namespace ApiExport\Module\App\Business\Feed;

use ApiExport\Module\App\Business\Feed\Exception\InvalidClassFeedParserException;
use ApiExport\Module\App\Business\Feed\Parser\InterfaceParser;

/**
 * Class Parser.
 */
class Parser
{
    /** @var  string */
    protected $content;
    /** @var  string */
    protected $type;
    /** @var  string */
    protected $url;

    /**
     * @param $content
     * @param $type
     * @param null $url
     */
    public function __construct($content, $type, $url = null)
    {
        $this->content = $content;
        $this->type = $type;
        $this->url = $url;
    }

    /**
     * @param null $type
     * @param bool $streamContent
     *
     * @return array|mixed|null
     *
     * @throws InvalidClassFeedParserException
     */
    public function parse($type = null, $streamContent = false)
    {
        $realType = $type ?: $this->type;
        $className = __NAMESPACE__.'\\Parser\\'.ucfirst($realType);
        if (!class_exists($className)) {
            throw new InvalidClassFeedParserException();
        }

        /** @var InterfaceParser $class */
        $class = (new \ReflectionClass($className))->newInstance($this->content);

        return $streamContent ? $class->parseStream($this->url, $realType) : $class->parse($realType);
    }

    /*
     * Getters / Setters
     */

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

    /**
     * @param string $content
     */
    public function setContent($content)
    {
        $this->content = $content;
    }

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

    /**
     * @param string $type
     */
    public function setType($type)
    {
        $this->type = $type;
    }

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

    /**
     * @param string $url
     */
    public function setUrl($url)
    {
        $this->url = $url;
    }
}


text:
define(["d3"], function (d3) {
  var  scheme=colorbrewer.Set1[9];
  //var paired =colorbrewer.Paired[12];
  var colorScheme = [scheme[0], scheme[1], scheme[2], scheme[3], scheme[6],  scheme[7], scheme[8]];
  //var colorScheme = [paired[5], paired[1], paired[3], paired[9], paired[11], paired[8], paired[0],  paired[4], paired[2]];
  //var scheme = Object.create(d3.scale.category10().domain());
  //scheme.splice(1, 1);

  var scale = d3.scale.ordinal()
    .domain(d3.range(colorScheme.length))
    .range(colorScheme);
  var numTypes = -1;

  return {
    nextColor: function () {
      numTypes++;
      this.colorsLeft--;
      return scale(numTypes);
      //return "gray";
    },

    maxNumColors: colorScheme.length,
    colorsLeft: colorScheme.length
  };

});


text:
"use strict"

class Login{

    toLogin(){
        window.location.href="index1.html";
    }

    init(){
        document.getElementById("accountName").focus();
        var loginBt=document.getElementById("loginBt");
        loginBt.addEventListener("click",this.toLogin,false);
    }

}

var login=new Login();
login.init();


text:
package com.gemstone.gemfire.cache.query.internal;

import com.gemstone.gemfire.cache.query.CqStatistics;

/**
 * Provides statistical information about a CqQuery.
 *
 * @since 5.5
 * @author Rao Madduri
 */
public class CqStatisticsImpl implements CqStatistics {
  private CqQueryImpl cqQuery;

//  private long numInserts;
//  private long numDeletes;
//  private long numUpdates;
//  private long numEvents;

  /**
   * Constructor for CqStatisticsImpl
   * @param cq - CqQuery reference to the CqQueryImpl object
   */
  public CqStatisticsImpl(CqQueryImpl cq) {
    cqQuery = cq;
  }

  /**
   * Returns the number of Insert events for this CQ.
   * @return the number of insert events
   */
  public long numInserts() {
    return this.cqQuery.getVsdStats().getNumInserts();
  }

  /**
   * Returns number of Delete events for this CQ.
   * @return the number of delete events
   */
  public long numDeletes() {
    return this.cqQuery.getVsdStats().getNumDeletes();
  }

  /**
   * Returns number of Update events for this CQ.
   * @return the number of update events
   */
  public long numUpdates(){
    return this.cqQuery.getVsdStats().getNumUpdates();
  }

  /**
   * Returns the total number of events for this CQ.
   * @return the total number of insert, update, and delete events
   */
  public long numEvents(){
    return cqQuery.getVsdStats().getNumEvents();
  }

}


text:
import { Routes } from '@angular/router';
import { HomeComponent } from './home';
import { PostsComponent } from './posts';
import { ProjectsComponent } from './projects';
import { ContactComponent } from './contact';

export const rootRouterConfig: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'posts', component: PostsComponent },
    { path: 'projects', component: ProjectsComponent },
    { path: 'contact', component: ContactComponent }
];


text:
package com.google.cloud.pubsublite.cloudpubsub;

import static com.google.cloud.pubsublite.internal.UncheckedApiPreconditions.checkState;

import com.google.api.gax.rpc.ApiException;
import com.google.auto.value.AutoValue;
import java.io.Serializable;

/**
 * Describes limits on bytes and messages outstanding for a single partition Pub/Sub Lite
 * subscriber. These are hard limits enforced by the server.
 */
@AutoValue
public abstract class FlowControlSettings implements Serializable {
  private static final long serialVersionUID = 982475982347L;

  /** Create a new builder for these settings. */
  public static Builder builder() {
    return new AutoValue_FlowControlSettings.Builder();
  }

  @AutoValue.Builder
  public abstract static class Builder {
    /** The number of quota bytes that may be outstanding to the client. */
    public abstract Builder setBytesOutstanding(long bytes);

    /** The number of messages that may be outstanding to the client. */
    public abstract Builder setMessagesOutstanding(long elements);

    abstract FlowControlSettings autoBuild();

    public FlowControlSettings build() throws ApiException {
      FlowControlSettings settings = autoBuild();
      checkState(settings.bytesOutstanding() > 0, "Cannot have 0 or less bytes outstanding.");
      checkState(settings.messagesOutstanding() > 0, "Cannot have 0 or less messages outstanding.");
      return settings;
    }
  }

  /** The number of quota bytes that may be outstanding to the client. */
  public abstract long bytesOutstanding();

  /** The number of messages that may be outstanding to the client. */
  public abstract long messagesOutstanding();
}


text:
package se.trixon.bivi.core.about;

import java.util.ResourceBundle;
import org.openide.util.ImageUtilities;
import se.trixon.almond.about.AboutAction;

/**
 *
 * @author Patrik Karlsson <patrik@trixon.se>
 */
public class AboutInitializer {

    public static void init() {
        AboutAction.setAboutBundle(ResourceBundle.getBundle("se/trixon/bivi/core/about/about"));
        AboutAction.setLicenseBundle(ResourceBundle.getBundle("se/trixon/bivi/core/about/license"));
        AboutAction.setImageIcon(ImageUtilities.loadImageIcon("se/trixon/bivi/core/about/logo.png", false));
    }
}


text:
from plaid.api.api import API

class Item(API):
    '''Sandbox item endpoints.'''

    def reset_login(self, access_token):
        '''
        Put an item into an ITEM_LOGIN_REQUIRED error state.

        :param  str     access_token:
        '''
        return self.client.post('/sandbox/item/reset_login', {
            'access_token': access_token,
        })

class Sandbox(API):
    '''
    Sandbox-only endpoints.
    (`HTTP docs <https://plaid.com/docs/api/#sandbox>`__)

    These endpoints may not be used in other environments.

    .. autoclass:: plaid.api.sandbox.Item
        :members:
    '''

    def __init__(self, client):
        super(Sandbox, self).__init__(client)
        self.item = Item(client)


text:
sudo apt-get update -y
sudo apt-get install -y apache2 git php5 php5-mysql php5-curl mysql-client curl

sudo git clone https://github.com/Langenoir1878/Simple-AWS-Tests.git

mv ./Application-setup/images /var/www/html/images
mv ./Simple-AWS-Tests/* /var/www/html

curl -sS https://getcomposer.org/installer | sudo php &> /tmp/getcomposer.txt

sudo php composer.phar require aws/aws-sdk-php &> /tmp/runcomposer.txt

sudo mv vendor /var/www/html &> /tmp/movevendor.txt

sudo php /var/www/html/setup.php &> /tmp/database-setup.txt

echo "Hi, install-webserver.sh has been called!" > /tmp/hello.txt


text:
package com.pungwe.db.io.store;

import com.pungwe.db.io.serializers.Serializer;
import com.pungwe.db.types.Header;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.map.LRUMap;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by ian on 09/03/2015.
 */
public class InstanceCachingStore implements Store {

	final Store store;
	private final int cacheSize;
	private volatile LRUMap<Long, Record<?>> cache;
	private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

	public InstanceCachingStore(Store store, int cacheSize) {
		this.store = store;
		this.cacheSize = cacheSize;
		cache = new LRUMap<>(cacheSize);
	}

	@Override
	public <T> long put(T value, Serializer<T> serializer) throws IOException {

		lock.writeLock().lock();
		try {
			// Get a new position
			if (cache.isFull()) {
				flushCache();
			}
			long recId = getNextId();
			Record rec = new Record();
			rec.value = value;
			rec.serializer = serializer;
			cache.put(recId, rec);
			return recId;
		} finally {
			if (lock.writeLock().isHeldByCurrentThread()) {
				lock.writeLock().unlock();
			}
		}
	}

	@Override
	public <T> T get(long position, Serializer<T> serializer) throws IOException {
		// Get never adds to the cache, it only checks if the value is there...
		try {
			lock.readLock().lock();
			if (cache.containsKey(position)) {
				T value = (T)cache.get(position).value;
				return value;
			}
			return store.get(position, serializer);
		} finally {
			lock.readLock().unlock();
		}
	}

	@Override
	public <T> long update(long position, T value, Serializer<T> serializer) throws IOException {
		lock.writeLock().lock();
		try {
			// Get a new position
			if (cache.isFull()) {
				flushCache();
			}
			Record rec = new Record();
			rec.value = value;
			rec.serializer = serializer;
			cache.put(position, rec);
			return position;
		} finally {
			if (lock.writeLock().isHeldByCurrentThread()) {
				lock.writeLock().unlock();
			}
		}
	}

	private void flushCache() throws IOException {
		LRUMap<Long, Record<?>> current = cache;
		cache = new LRUMap<Long, Record<?>>(cacheSize);
		MapIterator<Long, Record<?>> it = current.mapIterator();
		while (it.hasNext()) {
			Long key = it.next();
			Record<Object> value = (Record<Object>)it.getValue();
			store.update(key, value.value, value.serializer);
		}
	}

	@Override
	public Header getHeader() {
		return store.getHeader();
	}

	@Override
	public void remove(long position) throws IOException {

	}

	@Override
	public void commit() throws IOException {
		flushCache(); // force flush
		store.commit();
	}

	@Override
	public void rollback() throws UnsupportedOperationException, IOException {

	}

	@Override
	public boolean isClosed() throws IOException {
		return false;
	}

	@Override
	public void lock(long position, int size) {

	}

	@Override
	public void unlock(long position, int size) {

	}

	@Override
	public boolean isAppendOnly() {
		return store.isAppendOnly();
	}

	@Override
	public void close() throws IOException {

	}

	@Override
	public long getNextId() throws IOException {
		return store.getNextId();
	}

	@Override
	public long getCurrentId() throws IOException {
		return store.getCurrentId();
	}

	@Override
	public long getFirstId() throws IOException {
		return store.getFirstId();
	}

	private static class Record<T> {
		private volatile T value;
		private Serializer<T> serializer;
	}
}


text:
#define WIN32_LEAN_AND_MEAN     1
#include <windows.h>

extern "C" {

/**@cond internal */

unsigned long __flsindex = FLS_OUT_OF_INDEXES;

void * gpFlsAlloc = 0;
void * gpFlsGetValue = 0;
void * gpFlsSetValue = 0;
void * gpFlsFree = 0;

void __cdecl _freeptd (void *) {
}

void __cdecl _initptd (void *, void *) {
}

void * __cdecl _getptd (void) {
        return 0;
}
void * __cdecl _getptd_noexit (void) {
        return 0;
}

#if     _MSC_VER < 1700

/**
 * Fake FLS allocator/set/get routines. On VS2012 with AMD64 these are in a new
 * API wrapping file called winapisupp so they aren't as easy to shoot down.
 */

DWORD WINAPI __crtFlsAlloc (PFLS_CALLBACK_FUNCTION) {
        return FLS_OUT_OF_INDEXES;
}

PVOID WINAPI __crtFlsGetValue (DWORD) {
        return 0;
}

BOOL WINAPI __crtFlsSetValue (DWORD, PVOID) {
        return TRUE;
}

BOOL WINAPI __crtFlsFree (DWORD) {
        return TRUE;
}

#endif

void __cdecl _init_pointers (void);
void __cdecl _mtinitlocks (void);

void __cdecl _mtinit (void) {
        _init_pointers ();
        _mtinitlocks ();

        HMODULE         kernel = GetModuleHandleW (L"kernel32.dll");
        if (kernel == 0)
                return;

#if     _MSC_VER < 1700
        gpFlsAlloc = EncodePointer (__crtFlsAlloc);
        gpFlsGetValue = EncodePointer (__crtFlsGetValue);
        gpFlsSetValue = EncodePointer (__crtFlsSetValue);
        gpFlsFree = EncodePointer (__crtFlsFree);
#endif
}

#if     _MSC_VER > 1600 || __AMD64__

struct {
        int             refcount;
} __initialmbcinfo;
void * __ptmbcinfo = & __initialmbcinfo;

void * __cdecl __updatetmbcinfo (void) {
        return 0;
}

#endif

#if     _MSC_VER > 1600

/*
 * In Visual Studio 2010 and 2012 and presumably going forward, the DinkumWare
 * iostreams are all built strictly on top of classic POSIX fopen (), making
 * them interoperate well but adding quite a lot to the legacy drag. We don't
 * want these to exist.
 *
 * In VS2012 Update 1, the init function name changed from ioinit0 to ioinit.
 */

void * _stdbuf [2];

void __cdecl _ioinit (void) {
}

void __cdecl _ioinit0 (void) {
}

void __cdecl _ioterm (void) {
}

#endif

void __cdecl _mtdeletelocks (void);

void __cdecl _mtterm (void) {
        _mtdeletelocks ();
}

void * __cdecl __set_flsgetvalue (void) {
        return 0;
}

void * _encoded_null (void) {
        return EncodePointer (0);
}

void __cdecl __initmbctable (void) {
}

void * __pPurecall = 0;

void _initp_misc_purevirt (void * encoded_null) {
        __pPurecall = encoded_null;
}

int __cdecl _setargv (void) {
        return 0;
}

int __cdecl _setenvp (void) {
        return 0;
}

/**@endcond*/

}