text:
using System;
using System.Collections.Generic;
using System.Threading;
using De.Osthus.Ambeth.Config;
using De.Osthus.Ambeth.Event.Config;
using De.Osthus.Ambeth.Event.Model;
using De.Osthus.Ambeth.Ioc;
using De.Osthus.Ambeth.Ioc.Annotation;
using De.Osthus.Ambeth.Log;
using De.Osthus.Ambeth.Service;
using De.Osthus.Ambeth.Util;

namespace De.Osthus.Ambeth.Event
{
    public class EventPoller : IEventPoller, IOfflineListener, IStartingBean, IDisposableBean
    {
        [LogInstance]
        public ILogger Log { private get; set; }

        [Autowired]
        public IEventDispatcher EventDispatcher { protected get; set; }

        [Autowired]
        public IEventService EventService { protected get; set; }

        [Property(EventConfigurationConstants.PollingSleepInterval, DefaultValue = "500")]
        public TimeSpan PollSleepInterval { protected get; set; }

        [Property(EventConfigurationConstants.MaxWaitInterval, DefaultValue = "30000")]
        public TimeSpan MaxWaitInterval { protected get; set; }

        [Property(EventConfigurationConstants.StartPausedActive, DefaultValue = "false")]
        public bool StartPaused { protected get; set; }

        protected readonly Object writeLock = new Object();

        protected volatile bool stopRequested = false;

        protected volatile bool pauseRequested = false;

        protected int iterationId = 1;

        public virtual void AfterStarted()
        {
            if (StartPaused)
            {
                PausePolling();
            }
            StartPolling();
        }

        public virtual void Destroy()
        {
            StopPolling();
        }

        public void StopPolling()
        {
            lock (writeLock)
            {
                stopRequested = true;
                pauseRequested = false;
                iterationId++;
                Monitor.PulseAll(writeLock);
            }
        }

        public void StartPolling()
        {
            int stackIterationId = iterationId;
            Thread thread = new Thread(new ThreadStart(delegate()
            {
                try
                {
                    long currentServerSession = EventService.GetCurrentServerSession();
                    long currentEventSequence = EventService.GetCurrentEventSequence();
                    while (!stopRequested && stackIterationId == iterationId)
                    {
                        lock (writeLock)
                        {
                            while (pauseRequested && !stopRequested)
                            {
                                Monitor.Wait(writeLock);
                                if (stopRequested)
                                {
                                    break;
                                }
                            }
                        }
                        bool errorOccured;
                        currentEventSequence = TryPolling(currentServerSession, currentEventSequence, out errorOccured);
                        if (errorOccured)
                        {
                            Thread.Sleep(TimeSpan.FromMilliseconds(Math.Max(5000, PollSleepInterval.TotalMilliseconds)));
                        }
                        else
                        {
                            Thread.Sleep(PollSleepInterval);
                        }
                    }
                }
                catch (Exception e)
                {
                    if (Log.ErrorEnabled)
                    {
                        Log.Error(e);
                    }
                }
            }));
            thread.Name = "Event Polling";
            thread.IsBackground = true;
            thread.Start();
        }

        protected long TryPolling(long currentServerSession, long currentEventSequence, out bool errorOccured)
        {
            errorOccured = true;
            IList<IEventItem> events = null;
            try
            {
                events = EventService.PollEvents(currentServerSession, currentEventSequence, MaxWaitInterval);
                errorOccured = false;
            }
            catch (Exception e)
            {
                if (Log.ErrorEnabled)
                {
                    Log.Error(e);
                }
            }
            if (events == null || events.Count == 0)
            {
                return currentEventSequence;
            }
            long timeBeforeDispatch = DateTimeUtil.CurrentTimeMillis();
            EventDispatcher.EnableEventQueue();
            try
            {
                for (int a = 0, size = events.Count; a < size; a++)
                {
                    IEventItem eventObject = events[a];
                    EventDispatcher.DispatchEvent(eventObject.EventObject, eventObject.DispatchTime, eventObject.SequenceNumber);
                    currentEventSequence = eventObject.SequenceNumber;
                }
            }
            finally
            {
                EventDispatcher.FlushEventQueue();
            }
            if (Log.InfoEnabled)
            {
                long timeAfterDispatch = DateTimeUtil.CurrentTimeMillis();
                Log.Info("Dispatching " + events.Count + " event(s) took " + (timeAfterDispatch - timeBeforeDispatch) + " ms.");
            }
            return currentEventSequence;
        }

        public void PausePolling()
        {
            lock (writeLock)
            {
                if (pauseRequested)
                {
                    return;
                }
                if (Log.InfoEnabled)
                {
                    Log.Info("Polling activated, but paused for concurrency reasons till " + typeof(IEventPoller).Name + ".ResumePolling() is called");
                }
                pauseRequested = true;
                Monitor.PulseAll(writeLock);
            }
        }

        public void ResumePolling()
        {
            lock (writeLock)
            {
                if (!pauseRequested)
                {
                    return;
                }
                if (Log.InfoEnabled)
                {
                    Log.Info("Polling resumed");
                }
                pauseRequested = false;
                Monitor.PulseAll(writeLock);
            }
        }

        public void BeginOnline()
        {
            StopPolling();
        }

        public void HandleOnline()
        {
            // Intended blank
        }

        public void EndOnline()
        {
            StartPolling();
        }

        public void BeginOffline()
        {
            StopPolling();
        }

        public void HandleOffline()
        {
            // Intended blank
        }

        public void EndOffline()
        {
            StartPolling();
        }
    }
}


text:
module FecUtils::ItemizedParsers
  class IndividualParse
    include FecUtils::ItemizedParsers::Base

    column :filer_identification_number,   1, 9
    column :amendment_indicator,          10, 1
    column :report_type,                  11, 3
    column :primary_general_indicator,    14, 1
    column :microfilm_location,           15, 11
    column :transaction_type,             26, 3
    column :contributor_name,             29, 34
    column :city_or_town,                 63, 18
    column :state,                        81, 2
    column :zip_code,                     83, 5
    column :occupation,                   88, 35
    column :transaction_date,            123, 8, :date
    column :amount,                      131, 7, :amount
    column :other_identification,        138, 9
    column :fec_record,                  147, 7
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.gflogger.base;

import org.gflogger.*;
import org.gflogger.appender.AppenderFactory;

/**
 * TestDefaultLoggerServiceImpl
 *
 * @author Vladimir Dolzhenko, vladimir.dolzhenko@gmail.com
 */
public class TestDefaultSlf4jFormatLoggerServiceImpl extends TestSlf4jFormatLoggerServiceImpl {

	@Override
	protected LoggerService createLoggerService(int maxMessageSize,
			ObjectFormatterFactory objectFormatterFactory,
			GFLoggerBuilder[] loggers,
			AppenderFactory... factories) {
		final LoggerService loggerService =
			new Slf4JLoggerServiceImpl(4, maxMessageSize, objectFormatterFactory, loggers, factories);
		return loggerService;
	}
}


text:
import re
import abc

class OperationResult:
	def __init__(self, line, discard):
		self.line = line
		self.discard = discard
		self.error = None

class Operation:
	__metaclass__ = abc.ABCMeta
	def __init__(self):
		pass

	@abc.abstractmethod
	def apply(self, line, state):
		pass


text:
class ExternalLinkLog < LazyLoggingModel

  validates_presence_of :external_url

  # A possibly-geocoding reference to a single IPv4 address.
  belongs_to :ip_address
  validates_presence_of :ip_address_raw # 32-bit integer representation

  # A user ID will be recorded iff the user is logged in to a normal account.
  belongs_to :user

  # A string of client-side information provided by the web browser.
  validates_presence_of :user_agent

  def before_validation
    self.ip_address_raw = self.ip_address.number if self.ip_address and not self.ip_address_raw
    true # continue validation, as normal
  end

  def self.log(external_url, request, user)
    return nil if external_url.blank? or request.nil? or user.nil?

    opts = {
      :ip_address_raw => IpAddress.ip2int(request.remote_ip),
      :user_agent => request.user_agent,
      :path => request.referer,
      :external_url => external_url
    }
    opts[:user_id] = user.id unless user.nil?
    ExternalLinkLog.create(opts)
  end

end


text:
package stingray;

/**
 *  An object that can provide a rotated version.
 */
public interface Rotatable
{
  /**
   *  Get a new object that is rotated around the given axis by the given angle.
   *  @param axis The axis of rotation.
   *  @param radians The angle, in radians.
   *  @return A new object equivalent to the original object, rotated by the requested amount.
   */
  public Rotatable rotate(Vector axis, double radians);
}


text:
"""A test bench for the Google Cloud Storage C++ Client Library."""

import argparse
import error_response
import flask
import gcs_bucket
import gcs_object
import json
import os
import re
import testbench_utils
import time
import sys
from werkzeug import serving
from werkzeug.middleware.dispatcher import DispatcherMiddleware

root = flask.Flask(__name__, subdomain_matching=True)
root.debug = True

@root.route("/")
def index():
    """Default handler for the test bench."""
    return "OK"

@root.route("/<path:object_name>", subdomain="<bucket_name>")
def root_get_object(bucket_name, object_name):
    return xml_get_object(bucket_name, object_name)

@root.route("/<bucket_name>/<path:object_name>", subdomain="")
def root_get_object_with_bucket(bucket_name, object_name):
    return xml_get_object(bucket_name, object_name)

@root.route("/<path:object_name>", subdomain="<bucket_name>", methods=["PUT"])
def root_put_object(bucket_name, object_name):
    return xml_put_object(flask.request.host_url, bucket_name, object_name)

@root.route("/<bucket_name>/<path:object_name>", subdomain="", methods=["PUT"])
def root_put_object_with_bucket(bucket_name, object_name):
    return xml_put_object(flask.request.host_url, bucket_name, object_name)

@root.errorhandler(error_response.ErrorResponse)
def root_error(error):
    return error.as_response()

# Define the WSGI application to handle bucket requests.
GCS_HANDLER_PATH = "/storage/v1"
gcs = flask.Flask(__name__)
gcs.debug = True

def insert_magic_bucket(base_url):
    if len(testbench_utils.all_buckets()) == 0:
        bucket_name = os.environ.get(
            "GOOGLE_CLOUD_CPP_STORAGE_TEST_BUCKET_NAME", "test-bucket"
        )
        bucket = gcs_bucket.GcsBucket(base_url, bucket_name)
        testbench_utils.insert_bucket(bucket_name, bucket)

@gcs.route("/")
def gcs_index():
    """The default handler for GCS requests."""
    return "OK"

@gcs.errorhandler(error_response.ErrorResponse)
def gcs_error(error):
    return error.as_response()

@gcs.route("/b")
def buckets_list():
    """Implement the 'Buckets: list' API: return the Buckets in a project."""
    base_url = flask.url_for("gcs_index", _external=True)
    project = flask.request.args.get("project")
    if project is None or project.endswith("-"):
        raise error_response.ErrorResponse(
            "Invalid or missing project id in `Buckets: list`"
        )
    insert_magic_bucket(base_url)
    result = {"next_page_token": "", "items": []}
    for name, b in testbench_utils.all_buckets():
        result["items"].append(b.metadata)
    return testbench_utils.filtered_response(flask.request, result)

@gcs.route("/b", methods=["POST"])
def buckets_insert():
    """Implement the 'Buckets: insert' API: create a new Bucket."""
    base_url = flask.url_for("gcs_index", _external=True)
    insert_magic_bucket(base_url)
    payload = json.loads(flask.request.data)
    bucket_name = payload.get("name")
    if bucket_name is None:
        raise error_response.ErrorResponse(
            "Missing bucket name in `Buckets: insert`", status_code=412
        )
    if testbench_utils.has_bucket(bucket_name):
        raise error_response.ErrorResponse(
            "Bucket %s already exists" % bucket_name, status_code=400
        )
    bucket = gcs_bucket.GcsBucket(base_url, bucket_name)
    testbench_utils.insert_bucket(bucket_name, bucket)
    return testbench_utils.filtered_response(flask.request, bucket.metadata)

@gcs.route("/b/<bucket_name>")
def buckets_get(bucket_name):
    """Implement the 'Buckets: get' API: return the metadata for a bucket."""
    base_url = flask.url_for("gcs_index", _external=True)
    insert_magic_bucket(base_url)
    bucket = testbench_utils.lookup_bucket(bucket_name)
    bucket.check_preconditions(flask.request)
    return testbench_utils.filtered_response(flask.request, bucket.metadata)

@gcs.route("/b/<bucket_name>", methods=["DELETE"])
def buckets_delete(bucket_name):
    """Implement the 'Buckets: delete' API."""
    bucket = testbench_utils.lookup_bucket(bucket_name)
    bucket.check_preconditions(flask.request)
    testbench_utils.delete_bucket(bucket_name)
    return testbench_utils.filtered_response(flask.request, {})

@gcs.route("/b/<bucket_name>/o")
def objects_list(bucket_name):
    """Implement the 'Objects: list' API: return the objects in a bucket."""
    # Lookup the bucket, if this fails the bucket does not exist, and this
    # function should return an error.
    base_url = flask.url_for("gcs_index", _external=True)
    insert_magic_bucket(base_url)
    _ = testbench_utils.lookup_bucket(bucket_name)
    result = {"next_page_token": "", "items": [], "prefixes:": []}
    versions_parameter = flask.request.args.get("versions")
    all_versions = versions_parameter is not None and bool(versions_parameter)
    prefixes = set()
    prefix = flask.request.args.get("prefix", "", str)
    delimiter = flask.request.args.get("delimiter", "", str)
    start_offset = flask.request.args.get("startOffset", "", str)
    end_offset = flask.request.args.get("endOffset", "", str)
    bucket_link = bucket_name + "/o/"
    for name, o in testbench_utils.all_objects():
        if name.find(bucket_link + prefix) != 0:
            continue
        if o.get_latest() is None:
            continue
        # We assume `delimiter` has only one character.
        if name[len(bucket_link) :] < start_offset:
            continue
        if end_offset != "" and name[len(bucket_link) :] >= end_offset:
            continue
        delimiter_index = name.find(delimiter, len(bucket_link + prefix))
        if delimiter != "" and delimiter_index > 0:
            # We don't want to include `bucket_link` in the returned prefix.
            prefixes.add(name[len(bucket_link) : delimiter_index + 1])
            continue
        if all_versions:
            for object_version in o.revisions.values():
                result["items"].append(object_version.metadata)
        else:
            result["items"].append(o.get_latest().metadata)
    result["prefixes"] = list(prefixes)
    return testbench_utils.filtered_response(flask.request, result)

@gcs.route(
    "/b/<source_bucket>/o/<path:source_object>/copyTo/b/<destination_bucket>/o/<path:destination_object>",
    methods=["POST"],
)
def objects_copy(source_bucket, source_object, destination_bucket, destination_object):
    """Implement the 'Objects: copy' API, copy an object."""
    object_path, blob = testbench_utils.lookup_object(source_bucket, source_object)
    blob.check_preconditions(
        flask.request,
        if_generation_match="ifSourceGenerationMatch",
        if_generation_not_match="ifSourceGenerationNotMatch",
        if_metageneration_match="ifSourceMetagenerationMatch",
        if_metageneration_not_match="ifSourceMetagenerationNotMatch",
    )
    source_revision = blob.get_revision(flask.request, "sourceGeneration")
    if source_revision is None:
        raise error_response.ErrorResponse(
            "Revision not found %s" % object_path, status_code=404
        )

    destination_path, destination = testbench_utils.get_object(
        destination_bucket,
        destination_object,
        gcs_object.GcsObject(destination_bucket, destination_object),
    )
    base_url = flask.url_for("gcs_index", _external=True)
    current_version = destination.copy_from(base_url, flask.request, source_revision)
    testbench_utils.insert_object(destination_path, destination)
    return testbench_utils.filtered_response(flask.request, current_version.metadata)

@gcs.route(
    "/b/<source_bucket>/o/<path:source_object>/rewriteTo/b/<destination_bucket>/o/<path:destination_object>",
    methods=["POST"],
)
def objects_rewrite(
    source_bucket, source_object, destination_bucket, destination_object
):
    """Implement the 'Objects: rewrite' API."""
    base_url = flask.url_for("gcs_index", _external=True)
    insert_magic_bucket(base_url)
    object_path, blob = testbench_utils.lookup_object(source_bucket, source_object)
    blob.check_preconditions(
        flask.request,
        if_generation_match="ifSourceGenerationMatch",
        if_generation_not_match="ifSourceGenerationNotMatch",
        if_metageneration_match="ifSourceMetagenerationMatch",
        if_metageneration_not_match="ifSourceMetagenerationNotMatch",
    )
    response = blob.rewrite_step(
        base_url, flask.request, destination_bucket, destination_object
    )
    return testbench_utils.filtered_response(flask.request, response)

def objects_get_common(bucket_name, object_name, revision):
    # Respect the Range: header, if present.
    range_header = flask.request.headers.get("range")
    response_payload = revision.media
    begin = 0
    end = len(response_payload)
    if range_header is not None:
        m = re.match("bytes=([0-9]+)-([0-9]+)", range_header)
        if m:
            begin = int(m.group(1))
            end = int(m.group(2))
            response_payload = response_payload[begin : end + 1]
        m = re.match("bytes=([0-9]+)-$", range_header)
        if m:
            begin = int(m.group(1))
            response_payload = response_payload[begin:]
        m = re.match("bytes=-([0-9]+)$", range_header)
        if m:
            last = int(m.group(1))
            response_payload = response_payload[-last:]
    # Process custom headers to test error conditions.
    instructions = flask.request.headers.get("x-goog-testbench-instructions")
    if instructions == "return-broken-stream":

        def streamer():
            chunk_size = 64 * 1024
            for r in range(0, len(response_payload), chunk_size):
                if r > 1024 * 1024:
                    print("\n\n###### EXIT to simulate crash\n")
                    sys.exit(1)
                time.sleep(0.1)
                chunk_end = min(r + chunk_size, len(response_payload))
                yield response_payload[r:chunk_end]

        length = len(response_payload)
        content_range = "bytes %d-%d/%d" % (begin, end - 1, length)
        headers = {
            "Content-Range": content_range,
            "Content-Length": length,
            "x-goog-hash": revision.x_goog_hash_header(),
            "x-goog-generation": revision.generation,
        }
        return flask.Response(streamer(), status=200, headers=headers)

    if instructions == "return-corrupted-data":
        response_payload = testbench_utils.corrupt_media(response_payload)

    if instructions is not None and instructions.startswith("stall-always"):
        length = len(response_payload)
        content_range = "bytes %d-%d/%d" % (begin, end - 1, length)

        def streamer():
            chunk_size = 16 * 1024
            for r in range(begin, end, chunk_size):
                chunk_end = min(r + chunk_size, end)
                if r == begin:
                    time.sleep(10)
                yield response_payload[r:chunk_end]

        headers = {
            "Content-Range": content_range,
            "x-goog-hash": revision.x_goog_hash_header(),
            "x-goog-generation": revision.generation,
        }
        return flask.Response(streamer(), status=200, headers=headers)

    if instructions == "stall-at-256KiB" and begin == 0:
        length = len(response_payload)
        content_range = "bytes %d-%d/%d" % (begin, end - 1, length)

        def streamer():
            chunk_size = 16 * 1024
            for r in range(begin, end, chunk_size):
                chunk_end = min(r + chunk_size, end)
                if r == 256 * 1024:
                    time.sleep(10)
                yield response_payload[r:chunk_end]

        headers = {
            "Content-Range": content_range,
            "x-goog-hash": revision.x_goog_hash_header(),
            "x-goog-generation": revision.generation,
        }
        return flask.Response(streamer(), status=200, headers=headers)

    if instructions is not None and instructions.startswith("return-503-after-256K"):
        length = len(response_payload)
        headers = {
            "Content-Range": "bytes %d-%d/%d" % (begin, end - 1, length),
            "x-goog-hash": revision.x_goog_hash_header(),
            "x-goog-generation": revision.generation,
        }
        if begin == 0:

            def streamer():
                chunk_size = 4 * 1024
                for r in range(0, len(response_payload), chunk_size):
                    if r >= 256 * 1024:
                        print("\n\n###### EXIT to simulate crash\n")
                        sys.exit(1)
                    time.sleep(0.01)
                    chunk_end = min(r + chunk_size, len(response_payload))
                    yield response_payload[r:chunk_end]

            return flask.Response(streamer(), status=200, headers=headers)
        if instructions.endswith("/retry-1"):
            print("## Return error for retry 1")
            return flask.Response("Service Unavailable", status=503)
        if instructions.endswith("/retry-2"):
            print("## Return error for retry 2")
            return flask.Response("Service Unavailable", status=503)
        print("## Return success for %s" % instructions)
        return flask.Response(response_payload, status=200, headers=headers)

    response = flask.make_response(response_payload)
    length = len(response_payload)
    content_range = "bytes %d-%d/%d" % (begin, end - 1, length)
    response.headers["Content-Range"] = content_range
    response.headers["x-goog-hash"] = revision.x_goog_hash_header()
    response.headers["x-goog-generation"] = revision.generation
    return response

@gcs.route("/b/<bucket_name>/o/<path:object_name>", methods=["DELETE"])
def objects_delete(bucket_name, object_name):
    """Implement the 'Objects: delete' API.  Delete objects."""
    object_path, blob = testbench_utils.lookup_object(bucket_name, object_name)
    blob.check_preconditions(flask.request)
    remove = blob.del_revision(flask.request)
    if remove:
        testbench_utils.delete_object(object_path)
    return testbench_utils.filtered_response(flask.request, {})

@gcs.route("/b/<bucket_name>/o/<path:object_name>/compose", methods=["POST"])
def objects_compose(bucket_name, object_name):
    """Implement the 'Objects: compose' API: concatenate Objects."""
    payload = json.loads(flask.request.data)
    source_objects = payload["sourceObjects"]
    if source_objects is None:
        raise error_response.ErrorResponse(
            "You must provide at least one source component.", status_code=400
        )
    if len(source_objects) > 32:
        raise error_response.ErrorResponse(
            "The number of source components provided"
            " (%d) exceeds the maximum (32)" % len(source_objects),
            status_code=400,
        )
    composed_media = b""
    for source_object in source_objects:
        source_object_name = source_object.get("name")
        if source_object_name is None:
            raise error_response.ErrorResponse("Required.", status_code=400)
        source_object_path, source_blob = testbench_utils.lookup_object(
            bucket_name, source_object_name
        )
        source_revision = source_blob.get_latest()
        generation = source_object.get("generation")
        if generation is not None:
            source_revision = source_blob.get_revision_by_generation(generation)
            if source_revision is None:
                raise error_response.ErrorResponse(
                    "No such object: %s" % source_object_path, status_code=404
                )
        object_preconditions = source_object.get("objectPreconditions")
        if object_preconditions is not None:
            if_generation_match = object_preconditions.get("ifGenerationMatch")
            source_blob.check_preconditions_by_value(
                if_generation_match, None, None, None
            )
        composed_media += source_revision.media
    composed_object_path, composed_object = testbench_utils.get_object(
        bucket_name, object_name, gcs_object.GcsObject(bucket_name, object_name)
    )
    composed_object.check_preconditions(flask.request)
    base_url = flask.url_for("gcs_index", _external=True)
    current_version = composed_object.compose_from(
        base_url, flask.request, composed_media
    )
    testbench_utils.insert_object(composed_object_path, composed_object)
    return testbench_utils.filtered_response(flask.request, current_version.metadata)

# Define the WSGI application to handle bucket requests.
DOWNLOAD_HANDLER_PATH = "/download/storage/v1"
download = flask.Flask(__name__)
download.debug = True

@download.errorhandler(error_response.ErrorResponse)
def download_error(error):
    return error.as_response()

@gcs.route("/b/<bucket_name>/o/<path:object_name>")
@download.route("/b/<bucket_name>/o/<path:object_name>")
def objects_get(bucket_name, object_name):
    """Implement the 'Objects: get' API.  Read objects or their metadata."""
    _, blob = testbench_utils.lookup_object(bucket_name, object_name)
    blob.check_preconditions(flask.request)
    revision = blob.get_revision(flask.request)

    media = flask.request.args.get("alt", None)
    if media is None or media == "json":
        return testbench_utils.filtered_response(flask.request, revision.metadata)
    if media != "media":
        raise error_response.ErrorResponse("Invalid alt=%s parameter" % media)
    revision.validate_encryption_for_read(flask.request)
    return objects_get_common(bucket_name, object_name, revision)

# Define the WSGI application to handle bucket requests.
UPLOAD_HANDLER_PATH = "/upload/storage/v1"
upload = flask.Flask(__name__)
upload.debug = True

@upload.errorhandler(error_response.ErrorResponse)
def upload_error(error):
    return error.as_response()

@upload.route("/b/<bucket_name>/o", methods=["POST"])
def objects_insert(bucket_name):
    """Implement the 'Objects: insert' API.  Insert a new GCS Object."""
    gcs_url = flask.url_for(
        "objects_insert", bucket_name=bucket_name, _external=True
    ).replace("/upload/", "/")
    insert_magic_bucket(gcs_url)

    upload_type = flask.request.args.get("uploadType")
    if upload_type is None:
        raise error_response.ErrorResponse(
            "uploadType not set in Objects: insert", status_code=400
        )
    if upload_type not in {"multipart", "media", "resumable"}:
        raise error_response.ErrorResponse(
            "testbench does not support %s uploadType" % upload_type, status_code=400
        )

    if upload_type == "resumable":
        bucket = testbench_utils.lookup_bucket(bucket_name)
        upload_url = flask.url_for(
            "objects_insert", bucket_name=bucket_name, _external=True
        )
        return bucket.create_resumable_upload(upload_url, flask.request)

    object_path = None
    blob = None
    current_version = None
    if upload_type == "media":
        object_name = flask.request.args.get("name", None)
        if object_name is None:
            raise error_response.ErrorResponse(
                "name not set in Objects: insert", status_code=412
            )
        object_path, blob = testbench_utils.get_object(
            bucket_name, object_name, gcs_object.GcsObject(bucket_name, object_name)
        )
        blob.check_preconditions(flask.request)
        current_version = blob.insert(gcs_url, flask.request)
    else:
        resource, media_headers, media_body = testbench_utils.parse_multi_part(
            flask.request
        )
        object_name = flask.request.args.get("name", resource.get("name", None))
        if object_name is None:
            raise error_response.ErrorResponse(
                "name not set in Objects: insert", status_code=412
            )
        object_path, blob = testbench_utils.get_object(
            bucket_name, object_name, gcs_object.GcsObject(bucket_name, object_name)
        )
        blob.check_preconditions(flask.request)
        current_version = blob.insert_multipart(
            gcs_url, flask.request, resource, media_headers, media_body
        )
    testbench_utils.insert_object(object_path, blob)
    return testbench_utils.filtered_response(flask.request, current_version.metadata)

@upload.route("/b/<bucket_name>/o", methods=["PUT"])
def resumable_upload_chunk(bucket_name):
    """Receive a chunk for a resumable upload."""
    gcs_url = flask.url_for(
        "objects_insert", bucket_name=bucket_name, _external=True
    ).replace("/upload/", "/")
    bucket = testbench_utils.lookup_bucket(bucket_name)
    return bucket.receive_upload_chunk(gcs_url, flask.request)

@upload.route("/b/<bucket_name>/o", methods=["DELETE"])
def delete_resumable_upload(bucket_name):
    upload_type = flask.request.args.get("uploadType")
    if upload_type != "resumable":
        raise error_response.ErrorResponse(
            "testbench can delete resumable uploadType only", status_code=400
        )
    upload_id = flask.request.args.get("upload_id")
    if upload_id is None:
        raise error_response.ErrorResponse(
            "missing upload_id in delete_resumable_upload", status_code=400
        )
    bucket = testbench_utils.lookup_bucket(bucket_name)
    if upload_id not in bucket.resumable_uploads:
        raise error_response.ErrorResponse("upload_id does not exist", status_code=404)
    bucket.resumable_uploads.pop(upload_id)
    return testbench_utils.filtered_response(flask.request, {})

def xml_put_object(gcs_url, bucket_name, object_name):
    """Implement PUT for the XML API."""
    insert_magic_bucket(gcs_url)
    object_path, blob = testbench_utils.get_object(
        bucket_name, object_name, gcs_object.GcsObject(bucket_name, object_name)
    )
    generation_match = flask.request.headers.get("x-goog-if-generation-match")
    metageneration_match = flask.request.headers.get("x-goog-if-metageneration-match")
    blob.check_preconditions_by_value(
        generation_match, None, metageneration_match, None
    )
    revision = blob.insert_xml(gcs_url, flask.request)
    testbench_utils.insert_object(object_path, blob)
    response = flask.make_response("")
    response.headers["x-goog-hash"] = revision.x_goog_hash_header()
    return response

def xml_get_object(bucket_name, object_name):
    """Implement the 'Objects: insert' API.  Insert a new GCS Object."""
    object_path, blob = testbench_utils.lookup_object(bucket_name, object_name)
    if flask.request.args.get("acl") is not None:
        raise error_response.ErrorResponse(
            "ACL query not supported in XML API", status_code=500
        )
    if flask.request.args.get("encryption") is not None:
        raise error_response.ErrorResponse(
            "Encryption query not supported in XML API", status_code=500
        )
    generation_match = flask.request.headers.get("if-generation-match")
    metageneration_match = flask.request.headers.get("if-metageneration-match")
    blob.check_preconditions_by_value(
        generation_match, None, metageneration_match, None
    )
    revision = blob.get_revision(flask.request)
    return objects_get_common(bucket_name, object_name, revision)

application = DispatcherMiddleware(
    root,
    {
        GCS_HANDLER_PATH: gcs,
        UPLOAD_HANDLER_PATH: upload,
        DOWNLOAD_HANDLER_PATH: download,
    },
)


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

var gulp = require('gulp');
var inject = require('gulp-inject');
var mainBowerFiles = require('gulp-main-bower-files');

exports.inject = function () {
  var scripts = gulp.src(paths.scripts, {read: false});
  var appScripts = gulp.src(paths.appScripts, {read: false});
  var appCss = gulp.src(paths.appCss, {read: false});
  var bower = gulp.src(paths.bower).pipe(mainBowerFiles({includeDev: true}));
  var css = gulp.src(paths.injectCss, {read: false});
  var themeConstant = gulp.src(['public/js/_theme.js', 'public/templates.js'], {read: false});

  return gulp.src(paths.app + 'index.html')
    .pipe(inject(css, {
      name: 'css',
      relative: true,
      ignorePath: '../public'
    }))
    .pipe(inject(scripts, {
      name: 'scripts',
      relative: true,
      ignorePath: '../src'
    }))
    .pipe(inject(themeConstant, {
      name: 'theme',
      relative: true,
      ignorePath: '../public'
    }))
    .pipe(inject(appScripts, {
      name: 'appscripts',
      relative: true,
      ignorePath: '../'
    }))
    .pipe(inject(bower, {
      name: 'bower',
      relative: true,
      ignorePath: '../bower_components/'
    }))
    .pipe(gulp.dest(paths.dest));
};


text:
class Computer
  attr_reader :input, :noun, :position, :verb

  def initialize(noun, verb)
    @noun = noun
    @verb = verb
    load_input
    @position = 0
  end

  def execute_all
    loop do
      break unless execute_instruction
    end
  end

  def position_zero
    input[0]
  end

  private

  def load_instruction
    instruction = input[position]
    input1 = input[position + 1]
    input2 = input[position + 2]
    output = input[position + 3]
    @position += 4
    return instruction, input1, input2, output
  end

  def execute_instruction
    instruction, input1, input2, output = load_instruction
    return false if instruction == 99

    case instruction
    when 1
      add(input1, input2, output)
    when 2
      multiply(input1, input2, output)
    end
  end

  def add(input1, input2, output)
    input[output] = input[input1] + input[input2]
  end

  def multiply(input1, input2, output)
    input[output] = input[input1] * input[input2]
  end

  def load_input
    @input = File.read('input').split(',').map { |n| n.strip.to_i }
    set_noun_and_verb
  end

  def set_noun_and_verb
    input[1] = noun
    input[2] = verb
  end
end

EXPECTED = 19690720

(0..99).each do |noun|
  (0..99).each do |verb|
    computer = Computer.new(noun, verb)
    computer.execute_all
    puts "Noun: #{noun}\nVerb: #{verb}" if EXPECTED == computer.position_zero
  end
end


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Sber. öst. Akad. Wiss. Abt. I 168: 874.

#### Original name
null

### Remarks
null


text:
package jadx.core.dex.nodes;

import com.android.dex.ClassData.*;

import jadx.core.dex.attributes.nodes.*;
import jadx.core.dex.info.*;
import jadx.core.dex.info.AccessInfo.*;
import jadx.core.dex.instructions.args.*;

public class FieldNode extends LineAttrNode {

	private final ClassNode parent;
	private final FieldInfo fieldInfo;
	private final AccessInfo accFlags;

	private ArgType type; // store signature

	public FieldNode(ClassNode cls, Field field) {
		this.parent = cls;
		this.fieldInfo = FieldInfo.fromDex(cls.dex(), field.getFieldIndex());
		this.type = fieldInfo.getType();
		this.accFlags = new AccessInfo(field.getAccessFlags(), AFType.FIELD);
	}

	public FieldNode(ClassNode cls, FieldInfo fieldInfo, int accessFlags) {
		this.parent = cls;
		this.fieldInfo = fieldInfo;
		this.type = fieldInfo.getType();
		this.accFlags = new AccessInfo(accessFlags, AFType.FIELD);
	}

	public FieldInfo getFieldInfo() {
		return fieldInfo;
	}

	public AccessInfo getAccessFlags() {
		return accFlags;
	}

	public String getName() {
		return fieldInfo.getName();
	}

	public String getAlias() {
		return fieldInfo.getAlias();
	}

	public ArgType getType() {
		return type;
	}

	public void setType(ArgType type) {
		this.type = type;
	}

	public ClassNode getParentClass() {
		return parent;
	}

	@Override
	public int hashCode() {
		return fieldInfo.hashCode();
	}

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

	@Override
	public String toString() {
		return fieldInfo.getDeclClass() + "." + fieldInfo.getName() + " :" + type;
	}
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="bc.css">

### Forge Rooms, Effective Filtered Element Collectors

I successfully made it from Switzerland to Paris by train yesterday, in spite of the strikes here.

Now I am happily occupied with the Forge accelerator in the Autodesk office.

My only worry is how to get back again tomorrow.
This time again, the train I had originally booked has been cancelled.

We'll see how it goes.

Meanwhile, let's take a look at:

- [DA4R room support and new samples](#2)
- [Effective filtered element collection](#3)
- [Don't waste time optimising prematurely](#4)

#### DA4R Room Support and New Samples

Some recent [Forge Design Automation for Revit or DA4R](https://thebuildingcoder.typepad.com/blog/about-the-author.html#5.55) news
and samples:

Most importantly,
a [new RVT to SVF model derivative parameter generates additional content, including rooms and spaces](https://forge.autodesk.com/blog/new-rvt-svf-model-derivative-parameter-generates-additional-content-including-rooms-and-spaces).

Lots of other exciting [new samples](https://forge.autodesk.com/categories/code-samples) are available, including:

- Run additional programs inside a WorkItem
- Get number of BIM 360 projects per user
- Working with 2D and 3D scenes and geometry in Forge Viewer
- Fast track your cross-platform React native Forge app with the Expo SDK
- How to convert your plugin to work with Design Automation API for AutoCAD
- Go semantic with Viewer-custom web component for Forge Viewer
- New RVT->SVF Model Derivative parameter generates additional content, including rooms and spaces
- Combining PointClouds and Revit models in Forge Viewer
- Switch to orthographic corner view
- Custom BIM 360 search with Elasticsearch
- Get volume and surface area in the Viewer
- Run command from an AutoCAD AppBundle
- Run iLogic Rule without AppBundle

Here is a [link to view all samples](https://forge.autodesk.com/categories/code-samples).

#### Effective Filtered Element Collection

Back to the desktop Revit API, one issue that almost every Revit add-in developer faces is the efficiency of filtered element collectors.

Several interesting aspects are pointed out (and repeated) in the thread on
an [efficient way to check if an element exists in a view](https://forums.autodesk.com/t5/revit-api-forum/efficient-way-to-check-if-an-element-exists-in-a-view/m-p/9187613):

**Question:** I'm creating a list of views that contain .dwg ImportInstance(s).
For each view in the document, I'm using a `FilteredElementCollector` to get a list of elements meeting the criteria; if this list is not empty, the view is added to the list:

  foreach( Element e in viewElements )
  {
    View view = (View) e;

    var stopwatch = new Stopwatch();
    stopwatch.Start();

    List<Element> elementsInView
      = new FilteredElementCollector( doc, view.Id )
        .OfClass( typeof( ImportInstance ) )
        .Where( e => e.Category.Name.EndsWith( ".dwg" ) )
        .OfType<Element>()
        .ToList();

    stopwatch.Stop();

    Debug.WriteLine( view.Name + ": "
      + stopwatch.ElapsedMilliseconds + "ms" );

    // if the current view contains at least 1 DWG
    // ImportInstance, add the view to the list

    if( elementsInView.Count > 0 )
    {
      viewsWithCAD.Add( view );
      continue;
    }
  }

The FilteredElementCollector can understandably take more than 4000 ms to collect elements from a view containing many elements.

My goal is only to see if a single element exists in a view – not to collect all of the elements meeting the criteria; if I could make the FilteredElementCollector stop immediately after finding an element meeting the criteria, that would be helpful.

I would appreciate any advice on how to achieve this more efficiently.

Thank you.

**Answer by Fair59**, [Frank Aarssen](https://forums.autodesk.com/t5/user/viewprofilepage/user-id/2083518):
Stopping the collector at the first element:

  Element e1
    = new FilteredElementCollector( doc, view.Id )
      .OfClass( typeof( ImportInstance ) )
      .FirstElement();

Possible further speed improvement:

- Select all `ImportInstance` elements
- If it is not a DWG: exclude from collector in view-loop → no need for `category.Name` check
- Else: if DWG is ViewSpecific, i.e., is "2D annotation" in view → `ownerview` contains DWG, can be added to `viewsWithCAD`, and can be excluded from view-loop

  IEnumerable<ImportInstance> instances
    = new FilteredElementCollector( doc )
      .OfClass( typeof( ImportInstance ) )
      .Cast<ImportInstance>();

  List<ElementId> toExclude = new List<ElementId>();
  foreach( ImportInstance instance in instances )
  {
    if( !instance.Category.Name.EndsWith( ".dwg" ) )
    {
      toExclude.Add( instance.Id );
      continue;
    }
    if( instance.ViewSpecific ) // dwg only exists in ownerview
    {
      View ownerview = doc.GetElement( instance.OwnerViewId ) as View;
      viewsWithCAD.Add( ownerview );
      if( viewElements.Contains( ownerview ) )
        viewElements.Remove( ownerview );
    }
  }

  foreach( Element e in viewElements )
  {
    View view = (View) e;
    var stopwatch = new Stopwatch();
    stopwatch.Start();
    Element e1 = null;
    if( toExclude.Count > 0 )
    {
      e1 = new FilteredElementCollector( doc, view.Id )
        .Excluding( toExclude )
        .OfClass( typeof( ImportInstance ) )
        .FirstElement();
    }
    else
    {
      e1 = new FilteredElementCollector( doc, view.Id )
        .OfClass( typeof( ImportInstance ) )
        .FirstElement();
    }
    stopwatch.Stop();
    Debug.WriteLine( view.Name + ": "
      + stopwatch.ElapsedMilliseconds + "ms" );

    // if the current view contains at least 1 DWG
    // ImportInstance, add the view to the list

    if( e1 != null )
    {
      viewsWithCAD.Add( view );
    }
  }

Many thanks for the interesting question, and many thanks to Fair59 for yet another extremely knowledgeable and helpful solution!

**Notes:** I do keep pointing out that converting a filtered element collector to a List is an inefficient thing to do, if you can avoid it.

It forces the collector to retrieve all the data, convert it to the .NET memory space, duplicate it, costing time and space.

For the same reasons, it is much more efficient to test and apply as many filters as possible within the Revit memory space before passing any data across to .NET.

In this case, you can test the parameter values using a parameter filter instead of the LINQ post-processing that you are applying in you sample code snippet.

As Fair59 points out and we have discussed in the past, you can cancel a collector as soon as your target has been reached:

- [Aborting filtered element collection](https://thebuildingcoder.typepad.com/blog/2019/02/cancelling-filtered-element-collection.html)

So, you can save time and space in several ways:

- Use a parameter filter instead of LINQ or .NET post-processing
- Do not convert to a `List`

Both of these force the filtered element collector to retrieve and return all results.

Here is an explanation of the various types of filters versus post-processing in .NET:

- [Slow, slower still and faster filtering](https://thebuildingcoder.typepad.com/blog/2019/04/slow-slower-still-and-faster-filtering.html)

Here are some discussions and a benchmark of the results of using a parameter filter versus LINQ and .NET post-processing:

- [Filtering for a specific parameter value](https://thebuildingcoder.typepad.com/blog/2018/06/forge-tutorials-and-filtering-for-a-parameter-value.html#3)
- [Filtered element collector benchmark](https://thebuildingcoder.typepad.com/blog/2019/05/filtered-element-collector-benchmark.html#3)

We also discussed the issue of finding all views displaying an element a couple of times in the past:

- [Views displaying given element](https://thebuildingcoder.typepad.com/blog/2014/05/views-displaying-given-element-svg-and-nosql.html#6)
- [Determining views showing an element](https://thebuildingcoder.typepad.com/blog/2016/12/determining-views-showing-an-element.html)
- [Retrieving elements visible in view](https://thebuildingcoder.typepad.com/blog/2017/05/retrieving-elements-visible-in-view.html)
- [Can you avoid generating graphics?](https://thebuildingcoder.typepad.com/blog/2019/10/generating-graphics-and-collecting-assets.html#2)

#### Don't Waste Time Optimising Prematurely

[Mastjaso](https://forums.autodesk.com/t5/user/viewprofilepage/user-id/1058186) adds
some important professional advice in
his [comment below](https://thebuildingcoder.typepad.com/blog/2019/12/forge-rooms-effective-filtered-element-collectors.html#comment-4719321388):

> Interesting discussion on filtered element collectors, though I have to say that I have personally spend far too much time worrying about the efficiencies of those collectors when it has turned out to be inconsequential.

> For new developers starting out, or ones tackling a new project for the first time, I'd remember the adage that premature optimization is the death of software.
I start basically all my projects with super basic `OfClass` filtered element collectors and then cast and convert them to the .NET memory space so that I can use LINQ which produces shorter, more readable, and easier to debug code than the filtered element collection API.
It's only near the end of a project, once features are settled that I'll start swapping out LINQ for more nuanced uses of the FEC, but even then I'll only do it *if* I need the performance boost somewhere.

Before optimising anything at all, benchmark or profile to find out where and whether there are any serious performance issues at all.


text:
@interface HomeViewController () <UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSArray *data;
@end

@implementation HomeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initNavBar];
    [self loadTableView];
}

- (void)initNavBar
{
    self.title = @"请选择演示类型";
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    NSString *title = @"KWListView\n请选择演示类型";
    NSMutableAttributedString *attTitle = [[NSMutableAttributedString alloc] initWithString:title attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],NSForegroundColorAttributeName:[UIColor grayColor]}];
    [attTitle addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:17],NSForegroundColorAttributeName:[UIColor redColor]} range:[title rangeOfString:@"KWListView"]];
    titleLabel.attributedText = attTitle;
    titleLabel.numberOfLines = 0;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
}

- (void)loadTableView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    self.tableView = tableView;

    self.tableView.tableFooterView = [[UIView alloc] init];
}

# pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"homeCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    NSString *title = self.data[indexPath.row];
    cell.textLabel.text = title;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PlayViewController *vc = [[PlayViewController alloc] initWithType:indexPath.row];
    vc.title = self.data[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

# pragma mark - getter
- (NSArray *)data
{
    if (!_data) {
        _data = @[
                  @"加载失败",@"数据为空",@"加载成功",
                  ];
    }
    return _data;
}
@end


text:
import {Observable} from '@reactivex/rxjs';

import * as Util from "./Util"
import {HttpClient} from "./Http"
import { Option } from "flib"
import {
  Path, Input, eventAndStateChoice,
  GameEventAndState, BriscolaEvent, GameState, ActiveGameState, Card, gameStateChoice,
  CompetitionEventAndState, CompetitionEvent, CompetitionState,
  PlayerEventAndState, CurrentPlayer, PlayerEvent
} from "ddd-briscola-model"

import { ResourceFetch, mapping } from "nrest-fetch"

function asGameEventAndState(a: any): Option<GameEventAndState> {
  if (a instanceof GameEventAndState) return Option.some(a)
  else return Option.None;
}

function asCompetitionEventAndState(a: any): Option<CompetitionEventAndState> {
  if (a instanceof CompetitionEventAndState) return Option.some(a)
  else return Option.None;
}

function asPlayerEventAndState(a: any): Option<PlayerEventAndState> {
  if (a instanceof PlayerEventAndState) return Option.some(a)
  else return Option.None;
}

export class PlayerService {
  gamesChannel: Observable<GameEventAndState>
  competitionsChannel: Observable<CompetitionEventAndState>
  playersChannel: Observable<PlayerEventAndState>
  eventsLog: Observable<BriscolaEvent | CompetitionEvent | PlayerEvent>

  constructor(private resourceFetch: ResourceFetch, private http:HttpClient, webSocketFactory:(url: string) => Observable<MessageEvent>, public player: CurrentPlayer) {
    const webSocket: Observable<GameEventAndState | CompetitionEventAndState | PlayerEventAndState> = webSocketFactory(player.webSocket).flatMap((msgEv: MessageEvent) => {
      const data = msgEv.data
      if (typeof data === "string") {
        const msg = JSON.parse(data)
        return resourceFetch.fetchObject(msg, eventAndStateChoice).then(
          (v) => Promise.resolve(v),
          err => {
            console.log("error parsing web socket message")
            console.log(`error ${err}`)
            if (err && err.stack) console.log(err.stack)
            console.log(data)
            return Promise.reject(`error fetching event and state ${data}, error : ${err}`)
          }
        )
      } else {
        console.log("Error")
        console.log("msgEv.data:")
        console.log(data)
        return Promise.reject("expecting string")
      }
    })

    this.gamesChannel = Util.rxCollect(webSocket, asGameEventAndState)
    this.competitionsChannel = Util.rxCollect(webSocket, asCompetitionEventAndState)
    this.playersChannel = Util.rxCollect(webSocket, asPlayerEventAndState)
    this.eventsLog = webSocket.map(es => es.event)
  }

  createCompetition(players: Path[], kind: Input.MatchKind, deadlineKind: Input.CompetitionStartDeadline): Promise<CompetitionState> {
    return this.http.POST<Input.Competition>(this.player.createCompetition, {
      players: players,
      kind: kind,
      deadline: deadlineKind
    }).then(p => this.resourceFetch.fetchObject(p, mapping(CompetitionState)))
  }

  playCard(gameState: ActiveGameState, mcard: Card): Option<Promise<GameState>> {

    const card = Input.card(mcard)
    const url: Option<Path> = gameState.playerState.map(ps => ps.self)

    return url.map(url => {
      return this.http.POST<Input.Card>(url, {
        "number": card.number,
        seed: card.seed
      }).then(resp => {
        return resp.json().then(ws => {
          return this.resourceFetch.fetchObject(ws, gameStateChoice)
        })
      })
    })
  }

  acceptCompetition(cs: CompetitionState): Option<Promise<CompetitionState>> {
    return cs.accept.map(url =>
      this.http.POST<void>(url).then(resp =>
        resp.json().then(ws => this.resourceFetch.fetchObject(ws, mapping(CompetitionState)))))
  }

  declineCompetition(cs: CompetitionState): Option<Promise<CompetitionState>> {
    return cs.decline.map(url =>
      this.http.POST<void>(url).then(resp =>
        resp.json().then(ws => this.resourceFetch.fetchObject(ws, mapping(CompetitionState)))))
  }

}


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

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.lucene.index.MergePolicy.OneMerge (Lucene 4.6.1 API)</title>
<meta name="date" content="2014-01-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Uses of Class
org.apache.lucene.index.MergePolicy.OneMerge

Packages that use MergePolicy.OneMerge

Package
Description

org.apache.lucene.index

Code to maintain and access indices.

Uses of MergePolicy.OneMerge in org.apache.lucene.index

Fields in org.apache.lucene.index with type parameters of type MergePolicy.OneMerge

Modifier and Type
Field and Description

List<MergePolicy.OneMerge>
MergePolicy.MergeSpecification.merges

The subset of segments to be included in the primitive merge.

Methods in org.apache.lucene.index that return MergePolicy.OneMerge

Modifier and Type
Method and Description

MergePolicy.OneMerge
ConcurrentMergeScheduler.MergeThread.getCurrentMerge()

Return the current merge, or null if this MergeThread is done.

MergePolicy.OneMerge
IndexWriter.getNextMerge()

Expert: the MergeScheduler calls this method to retrieve the next
 merge requested by the MergePolicy

MergePolicy.OneMerge
ConcurrentMergeScheduler.MergeThread.getRunningMerge()

Return the currently running merge.

Methods in org.apache.lucene.index with parameters of type MergePolicy.OneMerge

Modifier and Type
Method and Description

void
MergePolicy.MergeSpecification.add(MergePolicy.OneMerge merge)

Adds the provided MergePolicy.OneMerge to this
  specification.

protected void
ConcurrentMergeScheduler.doMerge(MergePolicy.OneMerge merge)

Does the actual merge, by calling IndexWriter.merge(org.apache.lucene.index.MergePolicy.OneMerge)

protected ConcurrentMergeScheduler.MergeThread
ConcurrentMergeScheduler.getMergeThread(IndexWriter writer,
              MergePolicy.OneMerge merge)

Create and return a new MergeThread

void
IndexWriter.merge(MergePolicy.OneMerge merge)

Merges the indicated segments, replacing them in the stack with a
 single segment.

void
ConcurrentMergeScheduler.MergeThread.setRunningMerge(MergePolicy.OneMerge merge)

Record the currently running merge.

Constructors in org.apache.lucene.index with parameters of type MergePolicy.OneMerge

Constructor and Description

ConcurrentMergeScheduler.MergeThread(IndexWriter writer,
                                    MergePolicy.OneMerge startMerge)

Sole constructor.

MergeState.CheckAbort(MergePolicy.OneMerge merge,
                     Directory dir)

Creates a #CheckAbort instance.

Overview

Package

Class

Use

Tree

Deprecated

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

          Copyright © 2000-2014 Apache Software Foundation.  All Rights Reserved.


text:
layout: post
title: Control Echo Blinds Using a Phone
image: /images/Echo-Blinds/IFTTT-Do/swipe-screen.PNG
---

Welp, our Amazon Echo broke, and now we can't close the blinds. Of course we could just close them with our hands, the way people do, but let's be honest--that's preposterous. Once you automate, you never go back to hand-operate!

Luckily, there's a pretty easy solution while we wait for the development kit for Google Home to come out in December.

If you haven't yet forayed into the world of If This Then That (IFTTT), this is the perfect opportunity. I will ashamedly admit that this is my first time using the service!

### Toolbox Additions

We are only adding one item to our toolbox for this one.

    Inventory

			IFTTT DO Button

			This is a very simple button created by IFTTT. It's literally just a button that you can program to do anything you want. In this case, we'll create two buttons--one to close the blinds, one to open them.

And off we go.

	1

### Download the Do app

You can download either the iOS or Android app on your mobile device. I have an iPhone, as you'll see in the screenshots below.

	2

### Join the Maker channel

Launch the app and click the big plus sign at the top to add a new "recipe". Choose the Channels tab at the top and scroll down until you find the Maker channel (the first icon in the second row in the image below). For some reason when you use the search tool in the Do app, it doesn't find the channel, so you need to scroll down. Note that the location and look of the icon may change, but it'll still be called Maker.

	3

### Create a new recipe

Once you're in the channel, click "Create a New Recipe."

Then select "Make a web request." You should see a screen like this:

These web requests are a powerful new way that IFTTT lets you make buttons that will basically let you do anything that can be sent over the internet in a web request. This is a super convenient feature for us since our Echo Blinds project is already operating through web requests. Check out our earlier post for a refresher on how it worked with the Amazon Echo. All we're doing now is replacing the Echo steps with the IFTTT Do Button to get the message into the Relay Server. The Arduino setup will see nothing different and will continue to poll the Relay Server until a new message arrives.

For this first version, we're creating two buttons. One to "open blinds" and one to "close blinds". For the next iteration we can build a toggle switch that can use just one button.

	4

### Create the "open blinds" button

The messages that we sent to the Relay Server through Alexa have a specific structure that looks like a normal URL that the Arduino code translates into actions. That's all a "web request" is--just a URL. There are a couple of parts to the URL:

- The Address to your relay server (for example, ours is http://projects.theconnman.com:3000).
- The API Key (this is a secret key that you stored in your hidden config.h file called API_KEY) as described in step 5 of this post.
- The Client ID, which you also stored in the same hidden config.h file called DST_IP.

So to fill out the fields in the Do Button recipe, enter the following (replacing the pink words with the items discussed above):

#### Type a Recipe title...
Open blinds

#### URL
Address/api/put?apiKey=API Key&clientId=Client ID&payload={"open":true}

#### Method
GET

The rest of the fields are optional, so we'll leave them blank.

TADA! You've got a new way to open the blinds! It should be noted that Alexa will still work to do the same thing, so you've just added a new way to open the blinds.

	5

### Create the "close blinds" button
To make the close blinds button, you'll follow step 3 again, but this time you'll enter the following for the recipe:

#### Type a Recipe title...
Close blinds

#### URL
Address/api/put?apiKey=API Key&clientId=Client ID&payload={"open":false}

#### Method
GET

Excellent. Now we can open and close our blinds again!

	6

### Add Do Button widget to iPhone lock screen

For some extra convenience, you can also add a Do Button widget to your iPhone's lock screen for quick button access.

To do so, first swipe down from the top of your phone, then swipe right to see all widgets. Scroll all the way to the bottom and click "Edit". Here you'll be able to add the Do Button widget. Now you can open and close your blinds even more quickly! Still without having to get up to twist the little rod manually. That's way too much work.

Enjoy your new Do Buttons!

-JMad


text:
<keydef>

The <keydef> element is a convenience element that is used to define
         keys without any of the other effects that occur when using a <topicref>
         element: no content is included in output, no title is included in the table of contents,
         and no linking or other relationships are defined. The <keydef> element
         is not the only way to define keys; its purpose is to simplify the process by defaulting
         several attributes to achieve the described behaviors.

Category: Map group elements


text:
                {{ share().get('text') }}

 1"class="item-counter right">
        {{ share().get('amount') | shortVerboseNumber }}


text:
FactoryGirl.define do
	image = Rails.root.to_s + ('/readme_screenshots/01.png')
  factory :photo do
    caption 'Test image caption'
    image 'fake image'
  end
end


text:
#ifndef _STORE_FACTORY_H_
#define _STORE_FACTORY_H_
#define CLIENT_VERSION "GridDB Client 0.5.0"

#include "Resource.h"
#include "gridstore.h"
#include "Store.h"

#include <map>
#include <string>

using namespace std;

namespace griddb {

	/**
	 * Class GridStoreFactory to contain GSGridStoreFactory object.
	 * This class is implemented as singleton.
	 */
	class StoreFactory : public Resource {

		GSBool mIsAllRelated;

		GSGridStoreFactory* mFactory;

	public:
		~StoreFactory();

		static shared_ptr<StoreFactory> get_default();
		shared_ptr<Store> get_store(const GSPropertyEntry* props, int propsCount);
		void set_properties(const GSPropertyEntry* props, int propsCount);
		string get_version();
		/**
		* Release all GridStore created by this factory and related resources
		*/
		void close();

	private:
		StoreFactory();
		void set_factory(GSGridStoreFactory* factory);

	};
}

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myapp="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/activity_device__action_save"
        android:title="@string/activity_device__action_save"
        myapp:showAsAction="ifRoom|withText" />
    <item
        android:id="@+id/activity_device__action_show_details"
        android:checkable="true"
        android:title="@string/activity_device__action_show_details"
        myapp:showAsAction="never" />
    <item
        android:id="@+id/activity_device__action_delete"
        android:title="@string/activity_device__action_delete"
        myapp:showAsAction="never" />
</menu>


text:
int* f() {
	int *buff = NULL;
	try {
		buff = malloc(SIZE*sizeof(int));
		do_stuff(buff);
		return buff;
	} catch (int do_stuff_exception) {
		if (buff != NULL) {
			free(buff);
		}
		return NULL; //returns NULL on error, having freed any allocated memory
	}
}


text:
package org.jabref.logic.search;

import java.util.Optional;
import java.util.regex.Pattern;

import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class SearchQueryTest {

    @Test
    public void testToString() {
        assertEquals("\"asdf\" (case sensitive, regular expression)", new SearchQuery("asdf", true, true).toString());
        assertEquals("\"asdf\" (case insensitive, plain text)", new SearchQuery("asdf", false, false).toString());
    }

    @Test
    public void testIsContainsBasedSearch() {
        assertTrue(new SearchQuery("asdf", true, false).isContainsBasedSearch());
        assertTrue(new SearchQuery("asdf", true, true).isContainsBasedSearch());
        assertFalse(new SearchQuery("author=asdf", true, false).isContainsBasedSearch());
    }

    @Test
    public void testIsGrammarBasedSearch() {
        assertFalse(new SearchQuery("asdf", true, false).isGrammarBasedSearch());
        assertFalse(new SearchQuery("asdf", true, true).isGrammarBasedSearch());
        assertTrue(new SearchQuery("author=asdf", true, false).isGrammarBasedSearch());
    }

    @Test
    public void testGrammarSearch() {
        BibEntry entry = new BibEntry();
        entry.addKeyword("one two", ',');
        SearchQuery searchQuery = new SearchQuery("keywords=\"one two\"", false, false);
        assertTrue(searchQuery.isMatch(entry));
    }

    @Test
    public void testGrammarSearchFullEntryLastCharMissing() {
        BibEntry entry = new BibEntry();
        entry.setField(StandardField.TITLE, "systematic revie");
        SearchQuery searchQuery = new SearchQuery("title=\"systematic review\"", false, false);
        assertFalse(searchQuery.isMatch(entry));
    }

    @Test
    public void testGrammarSearchFullEntry() {
        BibEntry entry = new BibEntry();
        entry.setField(StandardField.TITLE, "systematic review");
        SearchQuery searchQuery = new SearchQuery("title=\"systematic review\"", false, false);
        assertTrue(searchQuery.isMatch(entry));
    }

    @Test
    public void testSearchingForOpenBraketInBooktitle() {
        BibEntry e = new BibEntry(StandardEntryType.InProceedings);
        e.setField(StandardField.BOOKTITLE, "Super Conference (SC)");

        SearchQuery searchQuery = new SearchQuery("booktitle=\"(\"", false, false);
        assertTrue(searchQuery.isMatch(e));
    }

    @Test
    public void testSearchMatchesSingleKeywordNotPart() {
        BibEntry e = new BibEntry(StandardEntryType.InProceedings);
        e.setField(StandardField.KEYWORDS, "banana, pineapple, orange");

        SearchQuery searchQuery = new SearchQuery("anykeyword==apple", false, false);
        assertFalse(searchQuery.isMatch(e));
    }

    @Test
    public void testSearchMatchesSingleKeyword() {
        BibEntry e = new BibEntry(StandardEntryType.InProceedings);
        e.setField(StandardField.KEYWORDS, "banana, pineapple, orange");

        SearchQuery searchQuery = new SearchQuery("anykeyword==pineapple", false, false);
        assertTrue(searchQuery.isMatch(e));
    }

    @Test
    public void testSearchAllFields() {
        BibEntry e = new BibEntry(StandardEntryType.InProceedings);
        e.setField(StandardField.TITLE, "Fruity features");
        e.setField(StandardField.KEYWORDS, "banana, pineapple, orange");

        SearchQuery searchQuery = new SearchQuery("anyfield==\"fruity features\"", false, false);
        assertTrue(searchQuery.isMatch(e));
    }

    @Test
    public void testSearchAllFieldsNotForSpecificField() {
        BibEntry e = new BibEntry(StandardEntryType.InProceedings);
        e.setField(StandardField.TITLE, "Fruity features");
        e.setField(StandardField.KEYWORDS, "banana, pineapple, orange");

        SearchQuery searchQuery = new SearchQuery("anyfield=fruit and keywords!=banana", false, false);
        assertFalse(searchQuery.isMatch(e));
    }

    @Test
    public void testSearchAllFieldsAndSpecificField() {
        BibEntry e = new BibEntry(StandardEntryType.InProceedings);
        e.setField(StandardField.TITLE, "Fruity features");
        e.setField(StandardField.KEYWORDS, "banana, pineapple, orange");

        SearchQuery searchQuery = new SearchQuery("anyfield=fruit and keywords=apple", false, false);
        assertTrue(searchQuery.isMatch(e));
    }

    @Test
    public void testIsMatch() {
        BibEntry entry = new BibEntry();
        entry.setType(StandardEntryType.Article);
        entry.setField(StandardField.AUTHOR, "asdf");

        assertFalse(new SearchQuery("BiblatexEntryType", true, true).isMatch(entry));
        assertTrue(new SearchQuery("asdf", true, true).isMatch(entry));
        assertTrue(new SearchQuery("author=asdf", true, true).isMatch(entry));
    }

    @Test
    public void testIsValidQueryNotAsRegEx() {
        assertTrue(new SearchQuery("asdf", true, false).isValid());
    }

    @Test
    public void testIsValidQueryContainsBracketNotAsRegEx() {
        assertTrue(new SearchQuery("asdf[", true, false).isValid());
    }

    @Test
    public void testIsNotValidQueryContainsBracketNotAsRegEx() {
        assertTrue(new SearchQuery("asdf[", true, true).isValid());
    }

    @Test
    public void testIsValidQueryAsRegEx() {
        assertTrue(new SearchQuery("asdf", true, true).isValid());
    }

    @Test
    public void testIsValidQueryWithNumbersAsRegEx() {
        assertTrue(new SearchQuery("123", true, true).isValid());
    }

    @Test
    public void testIsValidQueryContainsBracketAsRegEx() {
        assertTrue(new SearchQuery("asdf[", true, true).isValid());
    }

    @Test
    public void testIsValidQueryWithEqualSignAsRegEx() {
        assertTrue(new SearchQuery("author=asdf", true, true).isValid());
    }

    @Test
    public void testIsValidQueryWithNumbersAndEqualSignAsRegEx() {
        assertTrue(new SearchQuery("author=123", true, true).isValid());
    }

    @Test
    public void testIsValidQueryWithEqualSignNotAsRegEx() {
        assertTrue(new SearchQuery("author=asdf", true, false).isValid());
    }

    @Test
    public void testIsValidQueryWithNumbersAndEqualSignNotAsRegEx() {
        assertTrue(new SearchQuery("author=123", true, false).isValid());
    }

    @Test
    public void isMatchedForNormalAndFieldBasedSearchMixed() {
        BibEntry entry = new BibEntry();
        entry.setType(StandardEntryType.Article);
        entry.setField(StandardField.AUTHOR, "asdf");
        entry.setField(StandardField.ABSTRACT, "text");

        assertTrue(new SearchQuery("text AND author=asdf", true, true).isMatch(entry));
    }

    @Test
    public void testSimpleTerm() {
        String query = "progress";

        SearchQuery result = new SearchQuery(query, false, false);
        assertFalse(result.isGrammarBasedSearch());
    }

    @Test
    public void testGetPattern() {
        String query = "progress";
        SearchQuery result = new SearchQuery(query, false, false);
        Pattern pattern = Pattern.compile("(\\Qprogress\\E)");
        //We can't directly compare the pattern objects
        assertEquals(Optional.of(pattern.toString()), result.getPatternForWords().map(Pattern::toString));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using ChainUtils.OpenAsset;
using ChainUtils.Stealth;

namespace ChainUtils
{
	public interface IColoredCoin : ICoin
	{
		AssetId AssetId
		{
			get;
		}
		Coin Bearer
		{
			get;
		}
	}
	public interface ICoin
	{
		Money Amount
		{
			get;
		}
		OutPoint Outpoint
		{
			get;
		}
		TxOut TxOut
		{
			get;
		}
	}

	public class IssuanceCoin : IColoredCoin
	{
		public IssuanceCoin()
		{

		}
		public IssuanceCoin(Coin bearer)
		{
			Bearer = bearer;
		}

		public IssuanceCoin(OutPoint outpoint, TxOut txout)
		{
			Bearer = new Coin(outpoint, txout);
		}

		public AssetId AssetId
		{
			get
			{
				return Bearer.TxOut.ScriptPubKey.Hash.ToAssetId();
			}
		}

		public Uri DefinitionUrl
		{
			get;
			set;
		}

		#region ICoin Members

		public Money Amount
		{
			get
			{
				return Bearer.TxOut.Value;
			}
			set
			{
				Bearer.TxOut.Value = value;
			}
		}

		public TxOut TxOut
		{
			get
			{
				return Bearer.TxOut;
			}
		}

		#endregion

		public Script ScriptPubKey
		{
			get
			{
				return Bearer.TxOut.ScriptPubKey;
			}
		}

		#region IColoredCoin Members

		public Coin Bearer
		{
			get;
			set;
		}

		public OutPoint Outpoint
		{
			get
			{
				return Bearer.Outpoint;
			}
		}

		#endregion
	}

	public class ColoredCoin : IColoredCoin
	{
		public ColoredCoin()
		{

		}
		public ColoredCoin(Asset asset, Coin bearer)
		{
			Asset = asset;
			Bearer = bearer;
		}

		public ColoredCoin(Transaction tx, ColoredEntry entry)
			: this(entry.Asset, new Coin(tx, entry.Index))
		{
		}

		public AssetId AssetId
		{
			get
			{
				return Asset.Id;
			}
		}
		public Asset Asset
		{
			get;
			set;
		}

		public Coin Bearer
		{
			get;
			set;
		}

		public TxOut TxOut
		{
			get
			{
				return Bearer.TxOut;
			}
		}

		#region ICoin Members

		public OutPoint Outpoint
		{
			get
			{
				return Bearer.Outpoint;
			}
		}

		public Script ScriptPubKey
		{
			get
			{
				return Bearer.ScriptPubKey;
			}
		}

		public Money Amount
		{
			get
			{
				return Asset.Quantity;
			}
		}

		#endregion

		public static IEnumerable<ColoredCoin> Find(Transaction tx, ColoredTransaction colored)
		{
			return Find(null, tx, colored);
		}
		public static IEnumerable<ColoredCoin> Find(Uint256 txId, Transaction tx, ColoredTransaction colored)
		{
			if(colored == null)
				throw new ArgumentNullException("colored");
			if(tx == null)
				throw new ArgumentNullException("tx");
			if(txId == null)
				txId = tx.GetHash();
			foreach(var entry in colored.Issuances.Concat(colored.Transfers))
			{
				var txout = tx.Outputs[entry.Index];
				yield return new ColoredCoin(entry.Asset, new Coin(new OutPoint(txId, entry.Index), txout));
			}
		}

		public static IEnumerable<ColoredCoin> Find(Transaction tx, IColoredTransactionRepository repo)
		{
			return Find(null, tx, repo);
		}
		public static IEnumerable<ColoredCoin> Find(Uint256 txId, Transaction tx, IColoredTransactionRepository repo)
		{
			if(txId == null)
				txId = tx.GetHash();
			var colored = tx.GetColoredTransaction(repo);
			return Find(txId, tx, colored);
		}
	}
	public class Coin : ICoin
	{
		public Coin()
		{

		}
		public Coin(Spendable spendable)
		{
			Outpoint = spendable.OutPoint;
			TxOut = spendable.TxOut;
		}
		public Coin(OutPoint fromOutpoint, TxOut fromTxOut)
		{
			Outpoint = fromOutpoint;
			TxOut = fromTxOut;
		}

		public Coin(Transaction fromTx, uint fromOutputIndex)
		{
			Outpoint = new OutPoint(fromTx, fromOutputIndex);
			TxOut = fromTx.Outputs[fromOutputIndex];
		}

		public Coin(Transaction fromTx, TxOut fromOutput)
		{
			var outputIndex = (uint)fromTx.Outputs.FindIndex(r => ReferenceEquals(fromOutput, r));
			Outpoint = new OutPoint(fromTx, outputIndex);
			TxOut = fromOutput;
		}
		public Coin(IndexedTxOut txOut)
		{
			Outpoint = new OutPoint(txOut.Transaction.GetHash(), txOut.N);
			TxOut = txOut.TxOut;
		}

		public Coin(Uint256 fromTxHash, uint fromOutputIndex, Money amount, Script scriptPubKey)
		{
			Outpoint = new OutPoint(fromTxHash, fromOutputIndex);
			TxOut = new TxOut(amount, scriptPubKey);
		}

		public ScriptCoin ToScriptCoin(Script redeemScript)
		{
			if(redeemScript == null)
				throw new ArgumentNullException("redeemScript");
			if(this is ScriptCoin)
				return (ScriptCoin)this;
			return new ScriptCoin(this, redeemScript);
		}

		public ColoredCoin ToColoredCoin(AssetId asset, ulong quantity)
		{
			return ToColoredCoin(new Asset(asset, quantity));
		}
		public ColoredCoin ToColoredCoin(BitcoinAssetId asset, ulong quantity)
		{
			return ToColoredCoin(new Asset(asset, quantity));
		}
		public ColoredCoin ToColoredCoin(Asset asset)
		{
			return new ColoredCoin(asset, this);
		}

		public OutPoint Outpoint
		{
			get;
			set;
		}
		public TxOut TxOut
		{
			get;
			set;
		}

		#region ICoin Members

		public Money Amount
		{
			get
			{
				return TxOut.Value;
			}
			set
			{
				TxOut.Value = value;
			}
		}

		#endregion

		public Script ScriptPubKey
		{
			get
			{
				return TxOut.ScriptPubKey;
			}
		}
	}

	public interface IScriptCoin : ICoin
	{
		Script Redeem
		{
			get;
		}
	}

	public class ScriptCoin : Coin, IScriptCoin
	{
		public ScriptCoin()
		{

		}

		public ScriptCoin(OutPoint fromOutpoint, TxOut fromTxOut, Script redeem)
			: base(fromOutpoint, fromTxOut)
		{
			Redeem = redeem;
			AssertCoherent();
		}

		public ScriptCoin(Transaction fromTx, uint fromOutputIndex, Script redeem)
			: base(fromTx, fromOutputIndex)
		{
			Redeem = redeem;
			AssertCoherent();
		}

		public ScriptCoin(Transaction fromTx, TxOut fromOutput, Script redeem)
			: base(fromTx, fromOutput)
		{
			Redeem = redeem;
			AssertCoherent();
		}
		public ScriptCoin(Coin coin, Script redeem)
			: base(coin.Outpoint, coin.TxOut)
		{
			Redeem = redeem;
			AssertCoherent();
		}

		private void AssertCoherent()
		{
			if(Redeem == null)
				throw new ArgumentException("redeem cannot be null", "redeem");
			var destination = TxOut.ScriptPubKey.GetDestination() as ScriptId;
			if(destination == null)
				throw new ArgumentException("the provided scriptPubKey is not P2SH");
			if(destination.ScriptPubKey != Redeem.Hash.ScriptPubKey)
				throw new ArgumentException("The redeem provided does not match the scriptPubKey of the coin");
		}
		public ScriptCoin(IndexedTxOut txOut, Script redeem)
			: base(txOut)
		{
			Redeem = redeem;
			AssertCoherent();
		}

		public ScriptCoin(Uint256 txHash, uint outputIndex, Money amount, Script redeem)
			: base(txHash, outputIndex, amount, redeem.Hash.ScriptPubKey)
		{
			Redeem = redeem;
			AssertCoherent();
		}

		public Script Redeem
		{
			get;
			set;
		}
	}

	public class StealthCoin : Coin, IScriptCoin
	{
		public StealthCoin()
		{
		}
		public StealthCoin(OutPoint outpoint, TxOut txOut, Script redeem, StealthMetadata stealthMetadata, BitcoinStealthAddress address)
			: base(outpoint, txOut)
		{
			StealthMetadata = stealthMetadata;
			Address = address;
			Redeem = redeem;
		}
		public StealthMetadata StealthMetadata
		{
			get;
			set;
		}

		public BitcoinStealthAddress Address
		{
			get;
			set;
		}

		public Script Redeem
		{
			get;
			set;
		}

		/// <summary>
		/// Scan the Transaction for StealthCoin given address and scan key
		/// </summary>
		/// <param name="tx">The transaction to scan</param>
		/// <param name="address">The stealth address</param>
		/// <param name="scan">The scan private key</param>
		/// <returns></returns>
		public static StealthCoin Find(Transaction tx, BitcoinStealthAddress address, Key scan)
		{
			var payment = address.GetPayments(tx, scan).FirstOrDefault();
			if(payment == null)
				return null;
			var txId = tx.GetHash();
			var txout = tx.Outputs.First(o => o.ScriptPubKey == payment.ScriptPubKey);
			return new StealthCoin(new OutPoint(txId, tx.Outputs.IndexOf(txout)), txout, payment.Redeem, payment.Metadata, address);
		}

		public StealthPayment GetPayment()
		{
			return new StealthPayment(TxOut.ScriptPubKey, Redeem, StealthMetadata);
		}

		public PubKey[] Uncover(PubKey[] spendPubKeys, Key scanKey)
		{
			var pubKeys = new PubKey[spendPubKeys.Length];
			for(var i = 0 ; i < pubKeys.Length ; i++)
			{
				pubKeys[i] = spendPubKeys[i].UncoverReceiver(scanKey, StealthMetadata.EphemKey);
			}
			return pubKeys;
		}

		public Key[] Uncover(Key[] spendKeys, Key scanKey)
		{
			var keys = new Key[spendKeys.Length];
			for(var i = 0 ; i < keys.Length ; i++)
			{
				keys[i] = spendKeys[i].Uncover(scanKey, StealthMetadata.EphemKey);
			}
			return keys;
		}
	}
}


text:
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { EfectosPage } from './efectos';

@NgModule({
  declarations: [
    EfectosPage,
  ],
  imports: [
    IonicPageModule.forChild(EfectosPage),
  ],
  exports: [
    EfectosPage
  ]
})
export class EfectosPageModule {}


text:
<?php

namespace Aivo\Highchart\Test\Tooltip;

use Aivo\Highchart\ChartInterface;
use Aivo\Highchart\Tooltip\Tooltip;
use PHPUnit_Framework_TestCase as TestCase;

class TooltipTest extends TestCase
{

    /**
     * @var ChartInterface
     */
    protected $mockChart;

    public function setUp()
    {
        $this->mockChart = $this->getMock('Aivo\Highchart\ChartInterface');
    }

    /**
     * @return Tooltip
     */
    protected function createTooltip()
    {
        return new Tooltip($this->mockChart);
    }

    public function testChart()
    {
        $tooltip = $this->createTooltip();

        $this->assertSame($this->mockChart, $tooltip->getChart());
    }

    public function testEnabled()
    {
        $tooltip = $this->createTooltip();

        $this->assertTrue($tooltip->isEnabled());
        $this->assertSame($tooltip, $tooltip->setEnabled(false));
        $this->assertFalse($tooltip->isEnabled());
    }

    /**
     * @expectedException \Aivo\Highchart\Exception\InvalidArgumentException
     */
    public function testEnabledInvalidArgumentException()
    {
        $tooltip = $this->createTooltip();

        $tooltip->setEnabled(null);
    }

    public function testStyle()
    {
        $tooltip = $this->createTooltip();

        $this->assertSame(array(), $tooltip->getStyles());
        $this->assertSame($tooltip, $tooltip->setStyle('one', 'One'));
        $this->assertSame(array('one' => 'One'), $tooltip->getStyles());
        $this->assertSame($tooltip, $tooltip->setStyles(array('two' => 'Two', 'three' => 'Three')));
        $this->assertSame(array('two' => 'Two', 'three' => 'Three'), $tooltip->getStyles());
        $this->assertSame('Three', $tooltip->getStyle('three'));
        $this->assertNull($tooltip->getStyle('four'));
    }

}


text:
package ppjc

import (
	"context"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/cs3238-tsuzu/chan-utils"
	"github.com/cs3238-tsuzu/popcon-sc/lib/database"
	"github.com/cs3238-tsuzu/popcon-sc/lib/types"
	"github.com/cs3238-tsuzu/popcon-sc/ppjc/types"
	"github.com/gorilla/websocket"
)

type EmptyReadCloser struct{}

func (e *EmptyReadCloser) Read([]byte) (int, error) {
	return 0, io.EOF
}

func (er *EmptyReadCloser) Close() error {
	return nil
}

func mustParseURL(rawurl string) *url.URL {
	u, err := url.Parse(rawurl)

	if err != nil {
		panic(err)
	}

	return u
}

type Client struct {
	addr, auth string
}

func (client *Client) ContestsRankingCount(cid int64) (int64, error) {
	u := mustParseURL(client.addr)
	u = u.ResolveReference(mustParseURL("v1/contests/" + strconv.FormatInt(cid, 10) + "/rankingCount"))

	req, err := http.NewRequest("GET", u.String(), nil)

	if err != nil {
		return 0, err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return 0, err
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return 0, errors.New(resp.Status)
	}

	b, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return 0, err
	}

	cnt, err := strconv.ParseInt(string(b), 10, 64)

	if err != nil {
		return 0, err
	}

	return cnt, nil
}

func (client *Client) ContestsRanking(cid, limit, offset int64) ([]sctypes.RankingRow, error) {
	u := mustParseURL(client.addr)
	u = u.ResolveReference(mustParseURL("v1/contests/" + strconv.FormatInt(cid, 10) + "/ranking"))

	val := url.Values{}
	val.Add("limit", strconv.FormatInt(limit, 10))
	val.Add("offset", strconv.FormatInt(offset, 10))

	req, err := http.NewRequest("POST", u.String(), strings.NewReader(val.Encode()))

	if err != nil {
		return nil, err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return nil, errors.New("error: " + resp.Status)
	}

	b, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return nil, err
	}

	var rows []sctypes.RankingRow
	if err := json.Unmarshal(b, &rows); err != nil {
		return nil, err
	}

	return rows, nil
}

func (client *Client) ContestsRankingWithUserData(cid, limit, offset int64) ([]sctypes.RankingRowWithUserData, error) {
	u := mustParseURL(client.addr)
	u = u.ResolveReference(mustParseURL("v1/contests/" + strconv.FormatInt(cid, 10) + "/ranking"))

	val := url.Values{}
	val.Add("limit", strconv.FormatInt(limit, 10))
	val.Add("offset", strconv.FormatInt(offset, 10))
	val.Add("with_user_data", "1")

	req, err := http.NewRequest("POST", u.String(), strings.NewReader(val.Encode()))

	if err != nil {
		return nil, err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return nil, errors.New("error: " + resp.Status)
	}

	b, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return nil, err
	}

	var rows []sctypes.RankingRowWithUserData
	if err := json.Unmarshal(b, &rows); err != nil {
		return nil, err
	}

	return rows, nil
}

func (client *Client) ContestsNew(cid int64) error {
	u := mustParseURL(client.addr)

	u = u.ResolveReference(mustParseURL("v1/contests/" + strconv.FormatInt(cid, 10) + "/new"))

	req, err := http.NewRequest("POST", u.String(), nil)

	if err != nil {
		return err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return err
	}

	resp.Body.Close()

	if resp.StatusCode != 200 {
		return errors.New("error: " + resp.Status)
	}

	return nil
}

func (client *Client) ContestsDelete(cid int64) error {
	u := mustParseURL(client.addr)

	u = u.ResolveReference(mustParseURL("v1/contests/" + strconv.FormatInt(cid, 10) + "/delete"))

	req, err := http.NewRequest("POST", u.String(), nil)

	if err != nil {
		return err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return err
	}

	resp.Body.Close()

	if resp.StatusCode != 200 {
		return errors.New("error: " + resp.Status)
	}

	return nil
}

func (client *Client) ContestsProblemsAdd(cid, pid int64) error {
	u := mustParseURL(client.addr)

	u = u.ResolveReference(mustParseURL("v1/contests/" + strconv.FormatInt(cid, 10) + "/problems/add"))

	val := url.Values{}
	val.Add("pid", strconv.FormatInt(pid, 10))

	req, err := http.NewRequest("POST", u.String(), strings.NewReader(val.Encode()))

	if err != nil {
		return err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return err
	}

	resp.Body.Close()

	if resp.StatusCode != 200 {
		return errors.New("error: " + resp.Status)
	}
	return nil
}

func (client *Client) ContestsProblemsDelete(cid, pid int64) error {
	u := mustParseURL(client.addr)
	u = u.ResolveReference(mustParseURL("v1/contests/" + strconv.FormatInt(cid, 10) + "/problems/delete"))

	val := url.Values{}
	val.Add("pid", strconv.FormatInt(pid, 10))

	req, err := http.NewRequest("POST", u.String(), strings.NewReader(val.Encode()))

	if err != nil {
		return err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return err
	}

	resp.Body.Close()

	if resp.StatusCode != 200 {
		return errors.New("error: " + resp.Status)
	}
	return nil
}

func (client *Client) ContestsJoin(cid, iid int64) error {
	u := mustParseURL(client.addr)

	u = u.ResolveReference(mustParseURL("v1/contests/" + strconv.FormatInt(cid, 10) + "/join"))

	val := url.Values{}
	val.Add("iid", strconv.FormatInt(iid, 10))

	req, err := http.NewRequest("POST", u.String(), strings.NewReader(val.Encode()))

	if err != nil {
		return err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return err
	}

	resp.Body.Close()

	if resp.StatusCode != 200 {
		return errors.New("error: " + resp.Status)
	}
	return nil
}

func (client *Client) JudgeSubmit(cid, sid int64) error {
	u := mustParseURL(client.addr)
	u = u.ResolveReference(mustParseURL("v1/judge/submit"))

	val := url.Values{}
	val.Add("cid", strconv.FormatInt(cid, 10))
	val.Add("sid", strconv.FormatInt(sid, 10))

	req, err := http.NewRequest("POST", u.String(), strings.NewReader(val.Encode()))

	if err != nil {
		return err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return err
	}

	resp.Body.Close()

	if resp.StatusCode != 200 {
		return errors.New("error: " + resp.Status)
	}
	return nil
}

func (client *Client) JudgeSubmissionsUpdateCase(cid, sid, jid int64, status string, res database.SubmissionTestCase) error {
	u := mustParseURL(client.addr)

	u = u.ResolveReference(mustParseURL("v1/judge/submissions/updateCase"))

	b, _ := json.Marshal(ppjctypes.JudgeTestcaseResult{
		Cid:      cid,
		Sid:      sid,
		Jid:      jid,
		Testcase: res,
		Status:   status,
	})

	val := url.Values{}
	val.Add("testcase_result", string(b))

	req, err := http.NewRequest("POST", u.String(), strings.NewReader(val.Encode()))

	if err != nil {
		return err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return err
	}

	resp.Body.Close()

	if resp.StatusCode != 200 {
		return errors.New("error: " + resp.Status)
	}
	return nil
}

func (client *Client) JudgeSubmissionsUpdateResult(cid, sid, jid int64, status sctypes.SubmissionStatusType, score int64, time, mem int64, message io.Reader) error {
	u := mustParseURL(client.addr)

	u = u.ResolveReference(mustParseURL("v1/judge/submissions/updateResult"))

	b, _ := json.Marshal(ppjctypes.JudgeSubmissionResult{
		Cid:    cid,
		Sid:    sid,
		Jid:    jid,
		Status: status,
		Score:  score,
		Time:   time,
		Mem:    mem,
	})

	pread, pwrite := io.Pipe()
	writer := multipart.NewWriter(pwrite)
	go func() {
		writer.WriteField("submission_result", string(b))

		if message != nil {
			msg, _ := writer.CreateFormFile("message", "message.txt")
			io.Copy(msg, message)
		}
		writer.Close()
		pwrite.Close()
	}()
	req, err := http.NewRequest("POST", u.String(), pread)

	if err != nil {
		return err
	}
	req.Header.Set(sctypes.InternalHTTPToken, client.auth)
	req.Header.Add("Content-Type", writer.FormDataContentType())

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return err
	}

	resp.Body.Close()

	if resp.StatusCode != 200 {
		return errors.New("error: " + resp.Status)
	}
	return nil
}

func (client *Client) FileDownload(category, name string) (io.ReadCloser, error) {
	if len(name) == 0 {
		return &EmptyReadCloser{}, nil
	}

	u := mustParseURL(client.addr)
	u = u.ResolveReference(mustParseURL("v1/file_download"))

	val := url.Values{}
	val.Add("category", category)
	val.Add("name", name)

	req, err := http.NewRequest("POST", u.String(), strings.NewReader(val.Encode()))

	if err != nil {
		return nil, err
	}

	req.Header.Set(sctypes.InternalHTTPToken, client.auth)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return nil, err
	}

	if resp.StatusCode != 200 {
		resp.Body.Close()
		return nil, errors.New("error: " + resp.Status)
	}
	return resp.Body, nil
}

func (client *Client) StartWorkersWSPolling(parallel int64, judgeInfoChan chan<- ppjctypes.JudgeInformation, ctx context.Context) (<-chan error, func(), error) {
	u := mustParseURL(client.addr)

	u = u.ResolveReference(mustParseURL("v1/workers/ws/polling"))
	if u.Scheme == "https" {
		u.Scheme = "wss"
	} else {
		u.Scheme = "ws"
	}
	conn, _, err := websocket.DefaultDialer.Dial(
		u.String(),
		http.Header{
			"Popcon-Parallel-Judge":   []string{strconv.FormatInt(parallel, 10)},
			sctypes.InternalHTTPToken: []string{client.auth},
		},
	)

	if err != nil {
		return nil, nil, err
	}

	exitChan := make(chan error, 1)
	exited := chanUtils.NewExitedNotifier()
	wg := sync.WaitGroup{}
	wg.Add(1)

	messageSendingTrigger := chanUtils.NewTrigger()
	go func() {
		defer wg.Done()
		for {
			ctx2, canceller := context.WithCancel(context.Background())

			done := make(chan bool, 1)
			go func() {
				defer close(done)
				if err := messageSendingTrigger.WaitWithContext(ctx2); err == nil {
					if err := conn.WriteJSON(ppjctypes.JudgeOneFinished); err != nil {
						logrus.WithError(err).Error("WriteJSON error()")
						return
					}
				}
			}()
			select {
			case <-exited.Channel:
				canceller()
				return

			case <-ctx.Done():
				if err := conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(60*time.Second)); err != nil {
					conn.Close()
				}
				exited.Finish()
				canceller()
				return

			case <-done:
			}
			canceller()
		}
	}()

	ret := func() {
		messageSendingTrigger.Wake()
	}

	go func() {
		defer close(judgeInfoChan)
		var exitError error
		for {
			var info ppjctypes.JudgeInformation
			err := conn.ReadJSON(&info)
			if err != nil {
				exitError = err
				exited.Finish()
				break
			}

			judgeInfoChan <- info

			select {
			case <-exited.Channel:
				return
			default:
			}
		}
		wg.Wait()
		exitChan <- exitError
	}()

	return exitChan, ret, nil
}

// NewClient's addr must be ended with '/'
func NewClient(addr, auth string) (*Client, error) {
	_, err := url.Parse(addr)

	if err != nil {
		return nil, err
	}

	return &Client{
		addr: addr,
		auth: auth,
	}, nil
}


text:
package cgeo.geocaching.geopoint;

import android.test.AndroidTestCase;

public class DistanceParserTest extends AndroidTestCase {

    static private final double MM = 1e-6; // 1mm, in kilometers

    public static void testFormats() {
        assertEquals(1.2, DistanceParser.parseDistance("1200 m", true), MM);
        assertEquals(1.2, DistanceParser.parseDistance("1.2 km", true), MM);
        assertEquals(0.36576, DistanceParser.parseDistance("1200 ft", true), MM);
        assertEquals(1.09728, DistanceParser.parseDistance("1200 yd", true), MM);
        assertEquals(1.9312128, DistanceParser.parseDistance("1.2 mi", true), MM);
    }

    public static void testImplicit() {
        assertEquals(1.2, DistanceParser.parseDistance("1200", true), MM);
        assertEquals(0.36576, DistanceParser.parseDistance("1200", false), MM);
    }

    public static void testComma() {
        assertEquals(1.2, DistanceParser.parseDistance("1,2km", true), MM);
    }

    public static void testCase() {
        assertEquals(0.36576, DistanceParser.parseDistance("1200 FT", true), MM);
    }

}