text:
<?php

namespace Tests\Browser\Pages\Deliveries;

use Laravel\Dusk\Browser;
use Tests\Browser\Pages\Page;
use Tests\Browser\Pages\Deliveries\DetailPage;
use Tests\Browser\Pages\Deliveries\SummaryPage;
use Tests\Browser\Pages\Clients\DetailPage as ClientDetailPage;
use Tests\Browser\Pages\Bills\SummaryPage as BillSummaryPage;

class ListPage extends Page
{
    /**
     * Get the URL for the page.
     *
     * @return string
     */
    public function url() {
        return '/deliveries';
    }

    /**
     * Browse from the list to an existing metal
     *
     * @param  Browser $browser
     * @param  DetailPage $detail_page
     * @param  string  $delivery_id
     *    The Delivery we are browsing to
     */
    public function browseToEditDeliveryFromActions(Browser $browser, DetailPage $detail_page, $delivery_id) {
        $this->clickAction($browser, ".app-delivery-line-{$delivery_id}", ".app-delivery-edit");
        $browser->waitForLocation($detail_page->url());
    }

    /**
     * Browse to the first available Delivery from the list
     *
     * @param  Browser $browser
     */
    public function browseToEditFirstDeliveryFromActions(Browser $browser) {
        $this->clickAction($browser, ".app-delivery-line", ".app-delivery-edit");
    }

    /**
     * Browse from the list to the Delivery Summary
     *
     * @param  Browser $browser
     * @param  SummaryPage $summary_page
     * @param  string  $delivery_id
     *    The Delivery we are browsing to
     */
    public function browseToDeliverySummaryFromList(Browser $browser, SummaryPage $summary_page, $delivery_id) {
        $selector = ".app-delivery-line-{$delivery_id} .app-delivery-summary";
        $browser->click($selector);
        $browser->waitForLocation($summary_page->url());
    }

    /**
     * Browse from the list to the Delivery Summary
     *
     * @param  Browser $browser
     * @param  SummaryPage $summary_page
     * @param  string  $delivery_id
     *    The Delivery we are browsing to
     */
    public function browseToDeliverySummaryFromActions(Browser $browser, SummaryPage $summary_page, $delivery_id) {
        $this->clickAction($browser, ".app-delivery-line-{$delivery_id}", ".app-delivery-summary");
        $browser->waitForLocation($summary_page->url());
    }

    /**
     * Browse from the list to the Delivery Client
     *
     * @param  Browser $browser
     * @param  ClientDetailPage $client_detail_page
     * @param  string  $delivery_id
     *    The Delivery we are browsing to
     */
    public function browseToDeliveryClientFromActions(Browser $browser, ClientDetailPage $client_detail_page, $delivery_id) {
        $this->clickAction($browser, ".app-delivery-line-{$delivery_id}", ".app-client-view");
        $browser->waitForLocation($client_detail_page->url());
    }

    /**
     * Browse from the list to the Delivery Client
     *
     * @param  Browser $browser
     * @param  BillSummaryPage $bill_summary_page
     * @param  string  $delivery_id
     *    The Delivery we are browsing to
     */
    public function browseToDeliveryBillFromActions(Browser $browser, BillSummaryPage $bill_summary_page, $delivery_id) {
        $this->clickAction($browser, ".app-delivery-line-{$delivery_id}", ".app-bill-summary");
        $browser->waitForLocation($bill_summary_page->url());
    }

    /**
     * Browse from the list to the creation page
     *
     * @param  Browser    $browser
     * @param  CreatePage $create_page
     */
    public function browseToCreateDelivery(Browser $browser, CreatePage $create_page): void {
        $browser->click('.app-delivery-create-new');
        $browser->waitForLocation($create_page->url());
    }

    /**
     * Search in the list
     *
     * @param Browser $browser
     * @param string  $search_criteria
     *    The search criteria
     */
    public function search(Browser $browser, string $search_criteria, string $client = ''): void {
        $browser->type('search', $search_criteria);
        $browser->select2('.app-client_id', $client);
        $browser->click('.app-submit');
    }

    /**
     * Clear the search
     *
     * Attention, With the current version of the library of
     * roquie/laravel-dusk-select2 V1.1 it is not possible to clear the selection
     *
     * @param Browser $browser
     */
    public function clearSearch(Browser $browser): void {
        $browser->clear('search');
        $browser->click('.app-submit');
    }
}


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

[UnitMenu("Object/Set Parent")]
public class JLSetObjectParent : JLAction
{
    [Parameter(ExpressionType = typeof(Transform))]
    public JLExpression Object;

    [Parameter(ExpressionType = typeof(Transform))]
    public JLExpression Parent;

    protected override IEnumerator<YieldMode> OnExecute(IExecutionContext context)
    {
        Object.GetResult<Transform>(context).parent = Parent.GetResult<Transform>(context);
        yield break;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
	declare(strict_types=1);

	namespace Edde\Common\Template;

	use Edde\Api\Node\INode;
	use Edde\Api\Node\ITreeTraversal;
	use Edde\Api\Template\ICompiler;
	use Edde\Api\Template\IMacro;
	use Edde\Api\Template\MacroException;
	use Edde\Common\Config\ConfigurableTrait;
	use Edde\Common\Node\AbstractTreeTraversal;

	abstract class AbstractCompiler extends AbstractTreeTraversal implements ICompiler {
		use ConfigurableTrait;
		/**
		 * @var IMacro[]
		 */
		protected $macroList;

		/**
		 * @inheritdoc
		 */
		public function registerMacro(string $name, IMacro $macro): ICompiler {
			$this->macroList[$name] = $macro;
			return $this;
		}

		/**
		 * @inheritdoc
		 */
		public function getMacro(string $name, INode $source): IMacro {
			if (isset($this->macroList[$name]) === false) {
				throw new MacroException(sprintf('Unknown macro [%s] on node [%s].', $name, $source->getPath()));
			}
			return $this->macroList[$name];
		}

		/**
		 * @inheritdoc
		 */
		public function select(INode $node, ...$parameters): ITreeTraversal {
			/** @var $compiler ICompiler */
			list($compiler) = $parameters;
			return $compiler->getMacro($node->getName(), $node);
		}
	}


text:
@implementation NSDate (formatting)

- (NSString *)formatWithString:(NSString *)format {
  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateFormat:format];
  NSString *string = [formatter stringFromDate:self];
  return string;
}

- (NSString *)formatWithStyle:(NSDateFormatterStyle)style {
  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateStyle:style];
  NSString *string = [formatter stringFromDate:self];
  return string;
}

- (NSString *)distanceOfTimeInWords {
  return [self distanceOfTimeInWords:[NSDate date]];
}

- (NSString *)distanceOfTimeInWords:(NSDate *)date {
  NSString *Ago      = NSLocalizedString(@"ago", @"Denotes past dates");
  NSString *FromNow  = NSLocalizedString(@"from now", @"Denotes future dates");
  NSString *LessThan = NSLocalizedString(@"less than", @"Indicates a less-than number");
  NSString *About    = NSLocalizedString(@"about", @"Indicates an approximate number");
  NSString *Over     = NSLocalizedString(@"over", @"Indicates an exceeding number");
  NSString *Almost   = NSLocalizedString(@"almost", @"Indicates an approaching number");
  //NSString *Second   = NSLocalizedString(@"second", @"One second in time");
  NSString *Seconds  = NSLocalizedString(@"seconds", @"More than one second in time");
  NSString *Minute   = NSLocalizedString(@"minute", @"One minute in time");
  NSString *Minutes  = NSLocalizedString(@"minutes", @"More than one minute in time");
  NSString *Hour     = NSLocalizedString(@"hour", @"One hour in time");
  NSString *Hours    = NSLocalizedString(@"hours", @"More than one hour in time");
  NSString *Day      = NSLocalizedString(@"day", @"One day in time");
  NSString *Days     = NSLocalizedString(@"days", @"More than one day in time");
  NSString *Month    = NSLocalizedString(@"month", @"One month in time");
  NSString *Months   = NSLocalizedString(@"months", @"More than one month in time");
  NSString *Year     = NSLocalizedString(@"year", @"One year in time");
  NSString *Years    = NSLocalizedString(@"years", @"More than one year in time");

  NSTimeInterval since = [self timeIntervalSinceDate:date];
  NSString *direction = since <= 0.0 ? Ago : FromNow;
  since = fabs(since);

  int seconds   = (int)since;
  int minutes   = (int)round(since / SECONDS_PER_MINUTE);
  int hours     = (int)round(since / SECONDS_PER_HOUR);
  int days      = (int)round(since / SECONDS_PER_DAY);
  int months    = (int)round(since / SECONDS_PER_MONTH);
  int years     = (int)floor(since / SECONDS_PER_YEAR);
  int offset    = (int)round(floor((float)years / 4.0) * 1440.0);
  int remainder = (minutes - offset) % 525600;

  int number;
  NSString *measure;
  NSString *modifier = @"";

  switch (minutes) {
    case 0 ... 1:
      measure = Seconds;
      switch (seconds) {
        case 0 ... 4:
          number = 5;
          modifier = LessThan;
          break;
        case 5 ... 9:
          number = 10;
          modifier = LessThan;
          break;
        case 10 ... 19:
          number = 20;
          modifier = LessThan;
          break;
        case 20 ... 39:
          number = 30;
          modifier = About;
          break;
        case 40 ... 59:
          number = 1;
          measure = Minute;
          modifier = LessThan;
          break;
        default:
          number = 1;
          measure = Minute;
          modifier = About;
          break;
      }
      break;
    case 2 ... 44:
      number = minutes;
      measure = Minutes;
      break;
    case 45 ... 89:
      number = 1;
      measure = Hour;
      modifier = About;
      break;
    case 90 ... 1439:
      number = hours;
      measure = Hours;
      modifier = About;
      break;
    case 1440 ... 2529:
      number = 1;
      measure = Day;
      break;
    case 2530 ... 43199:
      number = days;
      measure = Days;
      break;
    case 43200 ... 86399:
      number = 1;
      measure = Month;
      modifier = About;
      break;
    case 86400 ... 525599:
      number = months;
      measure = Months;
      break;
    default:
      number = years;
      measure = number == 1 ? Year : Years;
      if (remainder < 131400) {
        modifier = About;
      } else if (remainder < 394200) {
        modifier = Over;
      } else {
        ++number;
        measure = Years;
        modifier = Almost;
      }
      break;
  }
  if ([modifier length] > 0) {
    modifier = [modifier stringByAppendingString:@" "];
  }
  return [NSString stringWithFormat:@"%@%d %@ %@", modifier, number, measure, direction];
}

@end


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

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

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

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

<link rel="search" href="search_opensearch.php?v=opensearch.xml" type="application/opensearchdescription+xml" title="Xenomai"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

Xenomai
    3.0.4

Data Fields

sockaddr_can Struct Reference
RTDM » Device Profiles » CAN Devices

Socket address structure for the CAN address family.
 More...

Data Fields

sa_family_t 	can_family

 	CAN address family, must be AF_CAN.

int 	can_ifindex

 	Interface index of CAN controller.  More...

Detailed Description

Socket address structure for the CAN address family.

Examples:

can-rtt.c, rtcanrecv.c, and rtcansend.c.

Field Documentation

◆ can_ifindex

          int sockaddr_can::can_ifindex

Interface index of CAN controller.

See SIOCGIFINDEX.

Examples:

can-rtt.c, rtcanrecv.c, and rtcansend.c.

The documentation for this struct was generated from the following file:

include/rtdm/uapi/can.h

sockaddr_can

Generated by

     1.8.13


text:
package io.strimzi.systemtest.templates.crd;

import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.DeletionPropagation;
import io.fabric8.kubernetes.api.model.Quantity;
import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder;
import io.strimzi.api.kafka.model.CertSecretSourceBuilder;
import io.strimzi.api.kafka.model.KafkaMirrorMaker2;
import io.strimzi.api.kafka.model.KafkaMirrorMaker2Builder;
import io.strimzi.api.kafka.model.KafkaMirrorMaker2ClusterSpec;
import io.strimzi.api.kafka.model.KafkaMirrorMaker2ClusterSpecBuilder;
import io.strimzi.api.kafka.model.KafkaResources;
import io.strimzi.systemtest.Constants;
import io.strimzi.systemtest.Environment;
import io.strimzi.systemtest.resources.ResourceManager;
import io.strimzi.systemtest.resources.crd.KafkaMirrorMaker2Resource;
import io.strimzi.systemtest.utils.kafkaUtils.KafkaUtils;
import io.strimzi.test.TestUtils;
import io.strimzi.test.k8s.KubeClusterResource;

import static io.strimzi.systemtest.resources.ResourceManager.kubeClient;

public class KafkaMirrorMaker2Templates {

    private KafkaMirrorMaker2Templates() {}

    public static KafkaMirrorMaker2Builder kafkaMirrorMaker2(String name, String targetClusterName, String sourceClusterName, int kafkaMirrorMaker2Replicas, boolean tlsListener) {
        KafkaMirrorMaker2 kafkaMirrorMaker2 = getKafkaMirrorMaker2FromYaml(Constants.PATH_TO_KAFKA_MIRROR_MAKER_2_CONFIG);
        return defaultKafkaMirrorMaker2(kafkaMirrorMaker2, name, targetClusterName, sourceClusterName, kafkaMirrorMaker2Replicas, tlsListener);
    }

    public static KafkaMirrorMaker2Builder kafkaMirrorMaker2WithMetrics(String name, String targetClusterName, String sourceClusterName, int kafkaMirrorMaker2Replicas, String sourceNs, String targetNs) {
        KafkaMirrorMaker2 kafkaMirrorMaker2 = getKafkaMirrorMaker2FromYaml(Constants.PATH_TO_KAFKA_MIRROR_MAKER_2_METRICS_CONFIG);
        ConfigMap metricsCm = TestUtils.configMapFromYaml(Constants.PATH_TO_KAFKA_MIRROR_MAKER_2_METRICS_CONFIG, "mirror-maker-2-metrics");
        KubeClusterResource.kubeClient().getClient().configMaps().inNamespace(kubeClient().getNamespace()).createOrReplace(metricsCm);
        return defaultKafkaMirrorMaker2(kafkaMirrorMaker2, name, targetClusterName, sourceClusterName, kafkaMirrorMaker2Replicas, false, sourceNs, targetNs);
    }

    public static KafkaMirrorMaker2Builder kafkaMirrorMaker2WithMetrics(String name, String targetClusterName, String sourceClusterName, int kafkaMirrorMaker2Replicas) {
        KafkaMirrorMaker2 kafkaMirrorMaker2 = getKafkaMirrorMaker2FromYaml(Constants.PATH_TO_KAFKA_MIRROR_MAKER_2_METRICS_CONFIG);
        ConfigMap metricsCm = TestUtils.configMapFromYaml(Constants.PATH_TO_KAFKA_MIRROR_MAKER_2_METRICS_CONFIG, "mirror-maker-2-metrics");
        KubeClusterResource.kubeClient().getClient().configMaps().inNamespace(kubeClient().getNamespace()).createOrReplace(metricsCm);
        return defaultKafkaMirrorMaker2(kafkaMirrorMaker2, name, targetClusterName, sourceClusterName, kafkaMirrorMaker2Replicas, false);
    }

    public static KafkaMirrorMaker2Builder defaultKafkaMirrorMaker2(String name, String targetClusterName, String sourceClusterName, int kafkaMirrorMaker2Replicas, boolean tlsListener) {
        KafkaMirrorMaker2 kafkaMirrorMaker2 = getKafkaMirrorMaker2FromYaml(Constants.PATH_TO_KAFKA_MIRROR_MAKER_2_CONFIG);
        return defaultKafkaMirrorMaker2(kafkaMirrorMaker2, name, targetClusterName, sourceClusterName, kafkaMirrorMaker2Replicas, tlsListener);
    }

    private static KafkaMirrorMaker2Builder defaultKafkaMirrorMaker2(KafkaMirrorMaker2 kafkaMirrorMaker2, String name, String kafkaTargetClusterName, String kafkaSourceClusterName, int kafkaMirrorMaker2Replicas, boolean tlsListener) {
        return defaultKafkaMirrorMaker2(kafkaMirrorMaker2, name, kafkaTargetClusterName, kafkaSourceClusterName, kafkaMirrorMaker2Replicas, tlsListener, null, null);
    }

    private static KafkaMirrorMaker2Builder defaultKafkaMirrorMaker2(KafkaMirrorMaker2 kafkaMirrorMaker2, String name, String kafkaTargetClusterName, String kafkaSourceClusterName, int kafkaMirrorMaker2Replicas, boolean tlsListener, String sourceNs, String targetNs) {

        KafkaMirrorMaker2ClusterSpec targetClusterSpec = new KafkaMirrorMaker2ClusterSpecBuilder()
            .withAlias(kafkaTargetClusterName)
            .withBootstrapServers(targetNs == null ? KafkaResources.plainBootstrapAddress(kafkaTargetClusterName) : KafkaUtils.namespacedPlainBootstrapAddress(kafkaTargetClusterName, targetNs))
            .addToConfig("config.storage.replication.factor", -1)
            .addToConfig("offset.storage.replication.factor", -1)
            .addToConfig("status.storage.replication.factor", -1)
            .build();

        KafkaMirrorMaker2ClusterSpec sourceClusterSpec = new KafkaMirrorMaker2ClusterSpecBuilder()
            .withAlias(kafkaSourceClusterName)
            .withBootstrapServers(sourceNs == null ? KafkaResources.plainBootstrapAddress(kafkaSourceClusterName) : KafkaUtils.namespacedPlainBootstrapAddress(kafkaSourceClusterName, sourceNs))
            .build();

        if (tlsListener) {
            targetClusterSpec = new KafkaMirrorMaker2ClusterSpecBuilder(targetClusterSpec)
                .withBootstrapServers(targetNs == null ? KafkaResources.tlsBootstrapAddress(kafkaTargetClusterName) : KafkaUtils.namespacedTlsBootstrapAddress(kafkaTargetClusterName, targetNs))
                .withNewTls()
                    .withTrustedCertificates(new CertSecretSourceBuilder().withSecretName(KafkaResources.clusterCaCertificateSecretName(kafkaTargetClusterName)).withCertificate("ca.crt").build())
                .endTls()
                .build();

            sourceClusterSpec = new KafkaMirrorMaker2ClusterSpecBuilder(sourceClusterSpec)
                .withBootstrapServers(sourceNs == null ? KafkaResources.tlsBootstrapAddress(kafkaSourceClusterName) : KafkaUtils.namespacedTlsBootstrapAddress(kafkaSourceClusterName, sourceNs))
                .withNewTls()
                    .withTrustedCertificates(new CertSecretSourceBuilder().withSecretName(KafkaResources.clusterCaCertificateSecretName(kafkaSourceClusterName)).withCertificate("ca.crt").build())
                .endTls()
                .build();
        }

        KafkaMirrorMaker2Builder kmm2b = new KafkaMirrorMaker2Builder(kafkaMirrorMaker2)
            .withNewMetadata()
                .withName(name)
                .withNamespace(ResourceManager.kubeClient().getNamespace())
                .withClusterName(kafkaTargetClusterName)
            .endMetadata()
            .editOrNewSpec()
                .withVersion(Environment.ST_KAFKA_VERSION)
                .withReplicas(kafkaMirrorMaker2Replicas)
                .withConnectCluster(kafkaTargetClusterName)
                .withClusters(targetClusterSpec, sourceClusterSpec)
                .editFirstMirror()
                    .withSourceCluster(kafkaSourceClusterName)
                    .withTargetCluster(kafkaTargetClusterName)
                .endMirror()
                .withNewInlineLogging()
                    .addToLoggers("connect.root.logger.level", "DEBUG")
                .endInlineLogging()
            .endSpec();

        if (!Environment.isSharedMemory()) {
            kmm2b.editSpec().withResources(new ResourceRequirementsBuilder()
                // we use such values, because on environments where it is limited to 7Gi, we are unable to deploy
                // Cluster Operator, two Kafka clusters and MirrorMaker/2. Such situation may result in an OOM problem.
                // Using 1Gi is too much and on the other hand 512Mi is causing OOM problem at the start.
                .addToLimits("memory", new Quantity("784Mi"))
                .addToRequests("memory", new Quantity("784Mi"))
                .build());
        }

        return kmm2b;
    }

    public static void deleteKafkaMirrorMaker2WithoutWait(String resourceName) {
        KafkaMirrorMaker2Resource.kafkaMirrorMaker2Client().inNamespace(ResourceManager.kubeClient().getNamespace()).withName(resourceName).withPropagationPolicy(DeletionPropagation.FOREGROUND).delete();
    }
    private static KafkaMirrorMaker2 getKafkaMirrorMaker2FromYaml(String yamlPath) {
        return TestUtils.configFromYaml(yamlPath, KafkaMirrorMaker2.class);
    }
}


text:
require File.dirname(__FILE__) + '/test_helper'

class TypecastingTest < Test::Unit::TestCase
  # Make it easier to call methods in tests
  Parsing::Typecasting.public_instance_methods.each do |method|
    Parsing::Typecasting.send(:module_function, method)
  end

  def test_array_with_one_element_that_is_a_hash
    value = [{'Available' => 'true'}]
    assert_equal [{'available' => true}], Parsing::Typecasting.typecast(value)
  end

  def test_hash_with_one_key_whose_value_is_an_array
    value = {
      'Bucket' =>
        [
          {'Available' => 'true'}
        ]
    }

    expected = {
      'bucket' =>
        [
          {'available' => true}
        ]
    }
    assert_equal expected, Parsing::Typecasting.typecast(value)
  end

end

class XmlParserTest < Test::Unit::TestCase
  def test_bucket_is_always_forced_to_be_an_array_unless_empty
    one_bucket    = Parsing::XmlParser.new(Fixtures::Buckets.bucket_list_with_one_bucket)
    more_than_one = Parsing::XmlParser.new(Fixtures::Buckets.bucket_list_with_more_than_one_bucket)

    [one_bucket, more_than_one].each do |bucket_list|
      assert_kind_of Array, bucket_list['buckets']['bucket']
    end

    no_buckets    = Parsing::XmlParser.new(Fixtures::Buckets.empty_bucket_list)
    assert no_buckets.has_key?('buckets')
    assert_nil no_buckets['buckets']
  end

  def test_bucket_contents_are_forced_to_be_an_array_unless_empty
    one_key       = Parsing::XmlParser.new(Fixtures::Buckets.bucket_with_one_key)
    more_than_one = Parsing::XmlParser.new(Fixtures::Buckets.bucket_with_more_than_one_key)
    [one_key, more_than_one].each do |bucket_with_contents|
      assert_kind_of Array, bucket_with_contents['contents']
    end

    no_keys = Parsing::XmlParser.new(Fixtures::Buckets.empty_bucket)
    assert !no_keys.has_key?('contents')
  end

  def test_policy_grants_are_always_an_array
    policy = Parsing::XmlParser.new(Fixtures::Policies.policy_with_one_grant)
    assert_kind_of Array, policy['access_control_list']['grant']
  end

  def test_empty_xml_response_is_not_parsed
    assert_equal({}, Parsing::XmlParser.new(''))
  end
end


text:
using System;
using System.Reactive.Linq;

namespace Wikiled.Sentiment.Analysis.Processing.Persistency
{
    public class CombinedDataSource : IDataSource
    {
        private readonly IDataSource[] inner;

        public CombinedDataSource(IDataSource[] inner)
        {
            this.inner = inner ?? throw new ArgumentNullException(nameof(inner));
        }

        public IObservable<DataPair> Load()
        {
            var result = Observable.Empty<DataPair>();
            foreach (var processingData in inner)
            {
                result = result.Merge(processingData.Load());
            }

            return result;
        }
    }
}


text:
package org.locationtech.geomesa.kafka09

import java.io.Closeable
import java.util.concurrent.atomic.AtomicLong
import java.{util => ju}

import com.typesafe.scalalogging.LazyLogging
import com.vividsolutions.jts.geom.Envelope
import kafka.producer.{Producer, ProducerConfig}
import org.geotools.data.store.{ContentEntry, ContentFeatureStore}
import org.geotools.data.{FeatureReader, FeatureWriter, Query}
import org.geotools.feature.FeatureCollection
import org.geotools.geometry.jts.ReferencedEnvelope
import org.locationtech.geomesa.features.ScalaSimpleFeature
import org.locationtech.geomesa.kafka.GeoMessage
import org.locationtech.geomesa.kafka09.KafkaDataStore.FeatureSourceFactory
import org.locationtech.geomesa.utils.geotools._
import org.locationtech.geomesa.utils.text.ObjectPoolFactory
import org.opengis.feature.simple.{SimpleFeature, SimpleFeatureType}
import org.opengis.filter.identity.FeatureId
import org.opengis.filter.{Filter, Id}

import scala.collection.JavaConversions._

class KafkaProducerFeatureStore(entry: ContentEntry,
                                sft: SimpleFeatureType,
                                topic: String,
                                broker: String,
                                producer: Producer[Array[Byte], Array[Byte]],
                                q: Query)
  extends ContentFeatureStore(entry, q) with Closeable with LazyLogging {

  private val writerPool = ObjectPoolFactory(getWriterInternal(null, 0).asInstanceOf[KafkaFeatureWriter], 5)

  override def getBoundsInternal(query: Query) =
    ReferencedEnvelope.create(new Envelope(-180, 180, -90, 90), CRS_EPSG_4326)

  override def buildFeatureType(): SimpleFeatureType = sft

  override def addFeatures(featureCollection: FeatureCollection[SimpleFeatureType, SimpleFeature]): ju.List[FeatureId] = {
    writerPool.withResource { fw =>
      val ret = Array.ofDim[FeatureId](featureCollection.size())
      val iter = featureCollection.features()
      var i = 0
      while (iter.hasNext) {
        val sf = iter.next()
        ret(i) = sf.getIdentifier
        fw.write(sf)
        i += 1
      }
      ret.toList
    }
  }

  override def removeFeatures(filter: Filter): Unit = filter match {
    case Filter.INCLUDE => clearFeatures()
    case _              => super.removeFeatures(filter)
  }

  def clearFeatures(): Unit = writerPool.withResource { fw => fw.send(GeoMessage.clear()) }

  override def getWriterInternal(query: Query, flags: Int) = {
    if (query == null || query == Query.ALL || query.getFilter == null || query.getFilter == Filter.INCLUDE) {
      new KafkaFeatureWriterAppend(sft, producer, topic)
    } else {
      new KafkaFeatureWriterModify(sft, producer, topic, query)
    }
  }

  override def getCountInternal(query: Query): Int = 0
  override def getReaderInternal(query: Query): FeatureReader[SimpleFeatureType, SimpleFeature] = null

  override def close(): Unit = producer.close()
}

abstract class KafkaFeatureWriter(sft: SimpleFeatureType, producer: Producer[Array[Byte], Array[Byte]], topic: String)
    extends FeatureWriter[SimpleFeatureType, SimpleFeature] with LazyLogging {

  protected val msgEncoder = new KafkaGeoMessageEncoder(sft)

  private [kafka09] def write(sf: SimpleFeature): Unit = send(GeoMessage.createOrUpdate(sf))

  private [kafka09] def send(msg: GeoMessage): Unit = {
    logger.debug("sending message: {}", msg)
    producer.send(msgEncoder.encodeMessage(topic, msg))
  }

  override def getFeatureType: SimpleFeatureType = sft
  override def close(): Unit = {}
}

class KafkaFeatureWriterAppend(sft: SimpleFeatureType, producer: Producer[Array[Byte], Array[Byte]], topic: String)
    extends KafkaFeatureWriter(sft, producer, topic) {

  protected val reuse = new ScalaSimpleFeature("", sft)

  protected def nextId: String = KafkaProducerFeatureStoreFactory.FeatureIds.getAndIncrement().toString

  // always return false as we're appending, per the geotools API
  override def hasNext: Boolean = false

  override def next(): SimpleFeature = {
    reuse.setId(nextId)
    reuse.getUserData.clear()
    var i = 0
    while (i < reuse.values.length) {
      reuse.values(i) = null
      i += 1
    }
    reuse
  }

  override def write(): Unit = write(reuse)

  override def remove(): Unit = throw new NotImplementedError("Remove called on FeatureWriterAppend")
}

class KafkaFeatureWriterModify(sft: SimpleFeatureType, producer: Producer[Array[Byte], Array[Byte]], topic: String, query: Query)
    extends KafkaFeatureWriterAppend(sft, producer, topic) {

  private val ids = query.getFilter match {
    case ids: Id => ids.getIDs.iterator
    case _ => throw new NotImplementedError("Only modify by ID is supported")
  }

  override protected def nextId: String = ids.next.toString

  override def hasNext: Boolean = ids.hasNext

  override def remove(): Unit = send(GeoMessage.delete(reuse.getID))
}

object KafkaProducerFeatureStoreFactory {

  private [kafka09] val FeatureIds = new AtomicLong(0L)

  def apply(broker: String): FeatureSourceFactory = {

    val config = {
      val props = new ju.Properties()
      props.put(KafkaUtils09.brokerParam, broker)
      props.put("serializer.class", "kafka.serializer.DefaultEncoder")
      new ProducerConfig(props)
    }

    (entry: ContentEntry, query: Query, schemaManager: KafkaDataStoreSchemaManager) => {
      val fc = schemaManager.getFeatureConfig(entry.getTypeName)
      val kafkaProducer = new Producer[Array[Byte], Array[Byte]](config)
      new KafkaProducerFeatureStore(entry, fc.sft, fc.topic, broker, kafkaProducer, query)
    }
  }
}


text:
using System;
using System.Collections.Generic;
using MindTouch.Dream.Services.PubSub;
using MindTouch.Xml;

namespace MindTouch.Dream.Test.PubSub {
    public class MockDispatcher : IPubSubDispatcher {

        public static int Instantiations;

        public MockDispatcher() {
            Instantiations++;
        }

        public PubSubSubscriptionSet CombinedSet {
            get { throw new NotImplementedException(); }
        }

        public PubSubSubscriptionSet this[string location] {
            get { throw new NotImplementedException(); }
        }

        public IEnumerable<PubSubSubscriptionSet> GetAllSubscriptionSets() {
            throw new NotImplementedException();
        }

        public Tuplet<PubSubSubscriptionSet, bool> RegisterSet(string location, XDoc setDoc, string accessKey) {
            throw new NotImplementedException();
        }

        public void Dispatch(DispatcherEvent ev) {
            throw new NotImplementedException();
        }

        public PubSubSubscriptionSet ReplaceSet(string location, XDoc setDoc, string accessKey) {
            throw new NotImplementedException();
        }

        public bool RemoveSet(string location) {
            throw new NotImplementedException();
        }

        public event EventHandler<EventArgs> CombinedSetUpdated;
    }
}


text:
<?php

/**
 * This file is part of the ValueMatcher library.
 *
 * @author Łukasz Makuch <kontakt@lukaszmakuch.pl>
 * @license MIT http://opensource.org/licenses/MIT
 */

namespace lukaszmakuch\ValueMatcher\String;

/**
 * Performs strict comparison (===) of two strings.
 *
 * @author Łukasz Makuch <kontakt@lukaszmakuch.pl>
 */
class StrictStringMatcher extends StringMatcherTpl
{
    /**
     * Performs strict comparison (===) of two strings.
     *
     * @param mixed $someValue
     *
     * @return boolean true if the values are === equal
     * @throws \InvalidArgumentException when the value is not a string
     */
    protected function matchesImpl($someValue)
    {
        return $someValue === $this->pattern;
    }
}


text:
import * as R from "ramda";

import {UI_Ball} from "./Simple_UI";
import {CanvasWidth, CanvasHeight } from "../../main/Main";
import {Stream, Transaction, CellLoop} from "sodiumjs";
import { SelfDisposingContainer } from "../../../lib/display/SelfDisposingContainer";

const SPEED = 10;
const RADIUS = 50;

interface Motion {
    x:number;
    v:number;
}

export class Ball extends SelfDisposingContainer {
    private unlistener:() => void;

    constructor(private sTicks:Stream<number>) {
        super();
        this.addChild(UI_Ball(RADIUS));
        this.y = CanvasHeight/2;

        Transaction.run((): void => {
            const cMotion = new CellLoop<Motion>();
            const sUpdate = sTicks.snapshot(cMotion, (dt, motion) => this.getMotion(dt, motion));
            cMotion.loop(sUpdate.hold({
                x: 0,
                v: SPEED
            }));
            this.unlistener = cMotion.listen(motion => this.x = motion.x);
        });
    }

    getMotion(dt:number, _motion:Motion):Motion {
        const xMin = RADIUS;
        const xMax = CanvasWidth - RADIUS;
        const xUpdate = R.clamp(xMin, xMax, _motion.x + dt * _motion.v);
        const motion = R.set(R.lensProp("x"), xUpdate, _motion);

        if(motion.x == xMin || motion.x == xMax) {
            motion.v *= -1;
        }

        return motion;
    }

    dispose() {
       this.unlistener();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Scientifique de la France et de la Belgique 19: 303 (1888)

#### Original name
Entomophthora carpentieri Giard

### Remarks
null


text:
import React, { useRef, useState } from 'react';
import { Box, Button, Drop, DropButton, Layer, TextInput } from 'grommet';

const alignRight = { left: 'right' };
const alignLeft = { right: 'left' };

const MultipleDrop = () => {
  const [showDrop, setShowDrop] = useState(false);
  const [showLayer, setShowLayer] = useState(false);
  const targetRef = useRef();

  return (
    // Uncomment <Grommet> lines when using outside of storybook
    // <Grommet theme={...}>
    <Box gap="medium" fill align="center" justify="center">
      <DropButton
        label="drop button"
        dropAlign={alignLeft}
        dropContent={
          <Box pad="large">
            <TextInput
              value=""
              onChange={() => {}}
              suggestions={['one', 'two']}
            />
          </Box>
        }
      />
      <Button
        ref={targetRef}
        label="button"
        onClick={() => setShowDrop(true)}
      />
      {showDrop && (
        <Drop
          align={alignRight}
          target={targetRef.current}
          onClickOutside={() => setShowDrop(false)}
        >
          <Box pad="large">
            <TextInput
              value=""
              onChange={() => {}}
              suggestions={['one', 'two']}
            />
          </Box>
        </Drop>
      )}
      <Button label="layer" onClick={() => setShowLayer(!showLayer)} />
      {showLayer && (
        <Layer
          onEsc={() => setShowLayer(!showLayer)}
          position="left"
          modal={false}
        >
          <Box gap="small" pad="large" border>
            <TextInput
              value=""
              onChange={() => {}}
              suggestions={['one', 'two']}
            />
            <Button
              alignSelf="end"
              label="Close Layer"
              onClick={() => setShowLayer(!showLayer)}
            />
          </Box>
        </Layer>
      )}
    </Box>
    // </Grommet>
  );
};

export const Multiple = () => <MultipleDrop />;
Multiple.parameters = {
  chromatic: { disable: true },
};
Multiple.args = {
  full: true,
};

export default {
  title: 'Controls/Drop/Multiple',
};


text:
<resources>

    <style name="AppTheme" parent="android:style/Theme.Holo.Light">
        <!-- Customize your theme here. -->
    </style>

</resources>


text:
all:
	pdflatex presentation.tex
	#>/dev/null


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

<suite name="test_assert_list_content_for_combo" xmlns="http://github.com/srec" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://github.com/srec srec.xsd">
    <test_case name="1">
        <window_activate locator="TestForm"/>
        <assert_list_content locator="calculationCB" content="Current Value, Future Value, Wrong Value"/>
        <close locator="TestForm"/>
    </test_case>
</suite>


text:
import jm.JMC;
import jm.music.data.*;
import jm.music.tools.*;
import jm.util.*;

import java.io.*;
import java.util.Properties;
import java.util.Random;
import java.lang.Math;

//MIDI Controller features
import javax.sound.midi.*;
import javax.swing.*;

import jargs.gnu.CmdLineParser;
import org.apache.log4j.Logger;

public class Text2Midi implements JMC {

  private static Logger log = Logger.getLogger(Text2Midi.class);

  private static Boolean verbose = false;
  private static String FILENAME = "";
  private static String MUSICALSCALE = "";
  private static String SPEED = "";
  private static String RANGE_MIN = "";
  private static String RANGE_MAX = "";

  public Text2Midi(Properties properties)
  {
	   String aLine = "";
	   String bLine = "";
	   double value=0;
	   //double value0=0;
	   //double max=value;
	   //double min=value;
	   //double slope=0;
	   int intvalue=(int)value;
	   int n_of_notes=0;
	   //double nextvalue=value;
	   String tot_message="";
	   String language_selector="";

   	   //////////////////////////////////
	   // Reading ASCII text from file //
   	   //////////////////////////////////

	   String filename = properties.getProperty("FILENAME");
   	   try {
		//calculate scale factor and normalization
	       int cnt=0;
	       FileInputStream fin =  new FileInputStream(filename);
	       BufferedReader myInput = new BufferedReader (new InputStreamReader(fin));
	       while ((aLine = myInput.readLine()) != null)
	          tot_message=tot_message+removeSpaces(aLine);
	    } catch( Exception e ) { e.printStackTrace(); }

	   int max_number_of_notes=tot_message.length();

	   log.info("\n\n...[ Database acquired ]...");
	   log.info("Message = " + tot_message);
           log.info("String length = " + tot_message.length() + "\n");

           //////////////////////////////////
           // MUSICAL SETTINGS
           // SET HERE THE MUSICAL SCALE
           // 0 = dodecafonic
           // 1 = diatonic
           // 2 = blues
           // 3 = pentatonic
           // 4 = whole tones
           //////////////////////////////////
           //int musicalscale = 1;
           int musicalscale = Integer.parseInt(properties.getProperty("MUSICALSCALE"));
	   if (musicalscale==0) log.info ("Selected the following Musical Scale => [ DODECAFONIC ] ");
	   if (musicalscale==1) log.info ("Selected the following Musical Scale => [ DIATONIC ] ");
	   if (musicalscale==2) log.info ("Selected the following Musical Scale => [ BLUES ] ");
	   if (musicalscale==3) log.info ("Selected the following Musical Scale => [ PENTATONIC ] ");
	   if (musicalscale==4) log.info ("Selected the following Musical Scale => [ WHOLE TONES ] ");

           //////////////////////////////////
           // SET HERE THE SPEED
           // 1 = fast
           // 2 = slow
           //int speed = 2;
           int speed = Integer.parseInt(properties.getProperty("SPEED"));
	   if (speed==1) log.info ("Selected the following Speed => [ FAST ] ");
	   else log.info ("Selected the following Speed => [ SLOW ] ");
           /////////////////////////////////

           //min=1;
           int min = Integer.parseInt(properties.getProperty("RANGE_MIN"));
           //max=255;
           int max = Integer.parseInt(properties.getProperty("RANGE_MAX"));

           n_of_notes=tot_message.length();
           int[] pitches = new int[n_of_notes];
           Note[] notes = new Note[n_of_notes];
           int[] values = new int[n_of_notes];

           //convert the message lowecase
           //tot_message=tot_message.toLowerCase();

   	   try {
		//calculate scale factor and normalization
	        int cnt=0;
        	int sw=-1;

	        while (cnt<tot_message.length())
		{
	            char letter=tot_message.charAt(cnt);
             	    value=(int)letter;
	            value=(int)value*2;
        	    values[cnt]=(int)letter;
	            log.info("char="+letter);
        	    int midiPitch=0;
	            int randInt;

         	    intvalue=(int)letter;
	            if (musicalscale==0) {
            	    // DODECAFONIC //
	            midiPitch=(int)((value-(max+min)/2)*(65-0)/(max-min))+65;
           	    }

                    else if (musicalscale==1) {
	            // DIATONIC //
        	    switch (intvalue % 7) {
	                 case 0: midiPitch=(int) 60;
                         break;
        	         case 1: midiPitch=(int) 62;
                         break;
	                 case 2: midiPitch=(int) 64;
                         break;
        	         case 3: midiPitch=(int) 65;
                         break;
	                 case 4: midiPitch=(int) 67;
                         break;
        	         case 5: midiPitch=(int) 69;
                         break;
                	 case 6: midiPitch=(int) 71;
                         break;
	                 default: midiPitch=(int) 0;
        	    }

	            log.info("midiPitch: " + midiPitch);
	            //randInt = (int) (Math.random() * 2) + 1;
        	    //System.out.println("random: "+randInt);
	            //midiPitch=(int)(midiPitch+(int)12*(randInt-2));
           	    }

		    else if (musicalscale==2) {
	            // BLUES //
               	    switch (intvalue % 6) {
	                 case 0: midiPitch=(int) 60;
                         break;
        	         case 1: midiPitch=(int) 63;
                         break;
                	 case 2: midiPitch=(int) 65;
                         break;
	                 case 3: midiPitch=(int) 66;
                         break;
        	         case 4: midiPitch=(int) 67;
                         break;
                	 case 5: midiPitch=(int) 70;
                         break;
	                 default: midiPitch=(int) 0;
        	    }

	            log.info("midiPitch: " + midiPitch);
        	    randInt = (int) (Math.random() * 2) + 1;
	            //System.out.println("random: "+randInt);
        	    midiPitch=(int)(midiPitch+(int)12*(randInt-2));

	            //sw=sw*(-1);
         	   //midiPitch=(int)(midiPitch+12*sw);
           	   }

		   else if (musicalscale==3) {
	           // PENTATONIC //
               	   switch (intvalue % 5) {
	                 case 0: midiPitch=(int) 61;
                         break;
        	         case 1: midiPitch=(int) 63;
                         break;
                	 case 2: midiPitch=(int) 66;
                         break;
	                 case 3: midiPitch=(int) 68;
                         break;
        	         case 4: midiPitch=(int) 78;
                         break;
                	 default: midiPitch=(int) 0;
               	   }

               	   log.info("midiPitch: " + midiPitch);
                   randInt = (int) (Math.random() * 2) + 1;
                   //System.out.println("random: "+randInt);
                   midiPitch=(int)(midiPitch+(int)12*(randInt-2));
           	   }

		   else if (musicalscale==4) {
	           // WHOLE TONE //
               	   switch (intvalue % 6) {
	                 case 0: midiPitch=(int) 60;
                         break;
        	         case 1: midiPitch=(int) 62;
                         break;
                	 case 2: midiPitch=(int) 64;
                         break;
	                 case 3: midiPitch=(int) 66;
                         break;
        	         case 4: midiPitch=(int) 68;
                         break;
                	 case 5: midiPitch=(int) 70;
                         break;
	                 default: midiPitch=(int) 0;
               	   }

        	   log.info("midiPitch: " + midiPitch);
	           randInt = (int) (Math.random() * 2) + 1;
	           //System.out.println("random: "+randInt);
	           midiPitch=(int)(midiPitch+(int)12*(randInt-2));
           	   }

            	   log.info("midiPitch = " + midiPitch);
	           if (midiPitch<0) midiPitch=0;
        	   if (midiPitch>127) midiPitch=0;
	           pitches[cnt]=midiPitch;

        	   cnt++;
          } //end while
      } catch( Exception e ) { e.printStackTrace(); } //end catch

      ////////////////////////
      // Creating MIDI file //
      ////////////////////////

      log.info("\n\n...[ Creating MIDI file ]...");
      log.info("Note processed:" + n_of_notes);
          for (int i = 0; i < notes.length; i++) {
           // notes[i] = new Note(pitches[i], DEMI_SEMI_QUAVER * 4 * speed);
           if ((values[i]==65)  ||  (values[i]==69)  || (values[i]==73)  || (values[i]==79)  ||
               (values[i]==85)  ||  (values[i]==89)  || (values[i]==97)  || (values[i]==101) ||
               (values[i]==105) ||  (values[i]==111) || (values[i]==117) || (values[i]==121))
                notes[i] = new Note(pitches[i], DEMI_SEMI_QUAVER * 4 * speed);
           else
		notes[i] = new Note(pitches[i], DEMI_SEMI_QUAVER * 2 * speed);
          }

         // A phrase is made up of notes
         Phrase phrase = new Phrase(notes);
         Part pianoPart = new Part("Piano", PIANO);
         //Part pianoPart = new Part("Flute", FLUTE);
         // A part is made up of phrases
         pianoPart.add(phrase);
         // A score is made up of part(s)
         int tempo = 120;
         Score Text2Midi = new Score("Score from wyp2005 messages sonification. (c) D. Vicinanza", tempo, pianoPart);
         // In key of C: 0 flat
         Text2Midi.setKeySignature(0);
         // In 4/4 time
         Text2Midi.setNumerator(4);
         Text2Midi.setDenominator(4);
         // Display score in standard musical notation
         //View.notate(Text2Midi);
         // Write out score to MIDI file
         Write.midi(Text2Midi, "messages.mid");
  }

  static String removeSpaces(String withSpaces) {

	java.util.StringTokenizer t = new java.util.StringTokenizer(withSpaces, " ");
        StringBuffer result = new StringBuffer("");

	while (t.hasMoreTokens())
            result.append(t.nextToken());

	return result.toString();
  }

  int dodecafonic(double value, double max, double min) {

       int midiPitch;
       midiPitch=(int)((value-(max+min)/2)*(65-0)/(max-min))+65;

       return midiPitch;
  }

  private byte[] ConvertStringToByte(String str) {

	int i;
	byte[] byteStr = new byte[str.length()];

	str.getBytes(0,str.length(),byteStr,0);

	return byteStr;
  }

  private static void printUsage() {

	System.err.println(
        "Usage: Text2Midi [options]\n" +
        "\nAvailable [options] are:\n" +
        "[ -v,--verbose ]\n" +
        "[ {-f,--filename} the filename with the ASCII file to be processed ]\n" +
        "[ {-m,--musicalscale} the music scale to be used (0, 'Dodecatonic'; 1, 'Diatonic'; 2, 'Blues'; 3, 'Pentatonic'; 4, 'Whole Tones')]\n" +
        "[ {-s,--speed} the speed to be used (1, 'fast'; 2, 'slow']\n" +
        "[ {-a,--rangemin} the range min ]\n" +
        "[ {-z,--rangemax} the range max ]\n"
        );
  }

  public static void main(String[] args)
  {
        CmdLineParser parser                = new CmdLineParser();
	CmdLineParser.Option o_filename     = parser.addStringOption ('f', "filename");
	CmdLineParser.Option o_musicalscale = parser.addIntegerOption  ('m', "musicalscale");
	CmdLineParser.Option o_speed        = parser.addIntegerOption  ('s', "speed");
	CmdLineParser.Option o_rangemin     = parser.addIntegerOption  ('a', "rangemin");
	CmdLineParser.Option o_rangemax     = parser.addIntegerOption  ('z', "rangemax");
	CmdLineParser.Option o_verbose      = parser.addBooleanOption ('v', "verbose");

	try {
	      if ((args == null) || (args.length < 10) || (args.length > 11)) {
	        printUsage();
		System.exit(2);
	      } else parser.parse(args);
	} catch ( CmdLineParser.OptionException e ) {
	      //log.error(e.getMessage());
	      printUsage();
	      System.exit(2);
	} catch (Exception exc){ System.out.println (exc.toString()); }

        verbose = (Boolean) parser.getOptionValue(o_verbose, Boolean.FALSE);
	if (verbose) log.setLevel(org.apache.log4j.Level.INFO);
	log.info("Verbose level \t = " + verbose);

        FILENAME = (String) parser.getOptionValue(o_filename);
        if(FILENAME != null && FILENAME.length() > 0)
	log.info("ASCII File \t\t = " + FILENAME);
	else FILENAME="message2.txt";

	MUSICALSCALE = (String) parser.getOptionValue(o_musicalscale).toString();
        log.info("Musical Scale \t = " + MUSICALSCALE);

	SPEED = (String) parser.getOptionValue(o_speed).toString();
        log.info("Music Speed \t\t = " + SPEED);

	RANGE_MIN = (String) parser.getOptionValue(o_rangemin).toString();
        log.info("Min Range \t\t = " + RANGE_MIN);

	RANGE_MAX = (String) parser.getOptionValue(o_rangemax).toString();
        log.info("Max Range \t\t = " + RANGE_MAX);

	Properties properties = new Properties();
        properties.setProperty("FILENAME", FILENAME);
        properties.setProperty("MUSICALSCALE", MUSICALSCALE);
        properties.setProperty("SPEED", SPEED);
        properties.setProperty("RANGE_MIN", RANGE_MIN);
        properties.setProperty("RANGE_MAX", RANGE_MAX);
        new Text2Midi(properties);
  }
} //end of global class


text:
tensorpack.callbacks package
============================

.. automodule:: tensorpack.callbacks
    :members:
    :no-undoc-members:
    :show-inheritance:


text:
package org.apache.kerby.kerberos.kerb.client.impl;

import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.ClientUtil;
import org.apache.kerby.kerberos.kerb.client.KrbSetting;
import org.apache.kerby.kerberos.kerb.client.request.AsRequest;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
import org.apache.kerby.kerberos.kerb.client.request.TgsRequest;
import org.apache.kerby.kerberos.kerb.transport.KrbNetwork;
import org.apache.kerby.kerberos.kerb.transport.KrbTransport;
import org.apache.kerby.kerberos.kerb.transport.TransportPair;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * A default krb client implementation.
 */
public class DefaultInternalKrbClient extends AbstractInternalKrbClient {
    private static final Logger LOG = LoggerFactory.getLogger(DefaultInternalKrbClient.class);

    private DefaultKrbHandler krbHandler;
    private KrbTransport transport;

    public DefaultInternalKrbClient(KrbSetting krbSetting) {
        super(krbSetting);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void init() throws KrbException {
        super.init();

        this.krbHandler = new DefaultKrbHandler();
        krbHandler.init(getContext());
    }

    private void doRequest(KdcRequest request) throws KrbException {    //NOPMD

        String realm = getSetting().getKdcRealm();
        PrincipalName serverPrincipalName = request.getServerPrincipal();
        if (serverPrincipalName != null && serverPrincipalName.getRealm() != null) {
            realm = serverPrincipalName.getRealm();
        }
        List<String> kdcList = ClientUtil.getKDCList(realm, getSetting());

        // tempKdc may include the port number
        Iterator<String> tempKdc = kdcList.iterator();
        if (!tempKdc.hasNext()) {
            throw new KrbException("Cannot get kdc for realm " + getSetting().getKdcRealm());
        }

        try {
            sendIfPossible(request, tempKdc.next(), getSetting(), false);
            LOG.info("Send to kdc success.");
        } catch (Exception first) {
            boolean ok = false;
            while (tempKdc.hasNext()) {
                try {
                    sendIfPossible(request, tempKdc.next(), getSetting(), true);
                    ok = true;
                    LOG.info("Send to kdc success.");
                    break;
                } catch (Exception ignore) {
                    LOG.info("ignore this kdc");
                }
            }
            if (!ok) {
                if (first instanceof KrbException) {
                    throw (KrbException) first;
                }
                throw new KrbException("The request failed " + first.getMessage(), first);
            }
        } finally {
            if (transport != null) {
                transport.release();
            }
        }

    }

    private void sendIfPossible(KdcRequest request, String kdcString, KrbSetting setting,
                                boolean tryNextKdc)
        throws KrbException, IOException {

        TransportPair tpair = ClientUtil.getTransportPair(setting, kdcString);
        KrbNetwork network = new KrbNetwork();
        network.setSocketTimeout(setting.getTimeout());
        transport = network.connect(tpair);
        request.setSessionData(transport);
        krbHandler.handleRequest(request, tryNextKdc);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected TgtTicket doRequestTgt(AsRequest tgtTktReq) throws KrbException {
        doRequest(tgtTktReq);

        return tgtTktReq.getTicket();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected SgtTicket doRequestSgt(TgsRequest ticketReq) throws KrbException {
        doRequest(ticketReq);

        return ticketReq.getSgt();
    }

}


text:
<?php

namespace Yoast\WP\SEO\Repositories;

use Psr\Log\LoggerInterface;
use wpdb;
use Yoast\WP\Lib\Model;
use Yoast\WP\Lib\ORM;
use Yoast\WP\SEO\Builders\Indexable_Builder;
use Yoast\WP\SEO\Helpers\Current_Page_Helper;
use Yoast\WP\SEO\Helpers\Indexable_Helper;
use Yoast\WP\SEO\Loggers\Logger;
use Yoast\WP\SEO\Models\Indexable;
use Yoast\WP\SEO\Services\Indexables\Indexable_Version_Manager;

/**
 * Class Indexable_Repository.
 */
class Indexable_Repository {

	/**
	 * The indexable builder.
	 *
	 * @var Indexable_Builder
	 */
	private $builder;

	/**
	 * Represents the hierarchy repository.
	 *
	 * @var Indexable_Hierarchy_Repository
	 */
	protected $hierarchy_repository;

	/**
	 * The current page helper.
	 *
	 * @var Current_Page_Helper
	 */
	protected $current_page;

	/**
	 * The logger object.
	 *
	 * @var LoggerInterface
	 */
	protected $logger;

	/**
	 * The WordPress database.
	 *
	 * @var wpdb
	 */
	protected $wpdb;

	/**
	 * Represents the indexable helper.
	 *
	 * @var Indexable_Helper
	 */
	protected $indexable_helper;

	/**
	 * Checks if Indexables are up to date.
	 *
	 * @var Indexable_Version_Manager
	 */
	protected $version_manager;

	/**
	 * Returns the instance of this class constructed through the ORM Wrapper.
	 *
	 * @param Indexable_Builder              $builder              The indexable builder.
	 * @param Current_Page_Helper            $current_page         The current post helper.
	 * @param Logger                         $logger               The logger.
	 * @param Indexable_Hierarchy_Repository $hierarchy_repository The hierarchy repository.
	 * @param wpdb                           $wpdb                 The WordPress database instance.
	 * @param Indexable_Version_Manager      $version_manager      The indexable version manager.
	 */
	public function __construct(
		Indexable_Builder $builder,
		Current_Page_Helper $current_page,
		Logger $logger,
		Indexable_Hierarchy_Repository $hierarchy_repository,
		wpdb $wpdb,
		Indexable_Version_Manager $version_manager
	) {
		$this->builder              = $builder;
		$this->current_page         = $current_page;
		$this->logger               = $logger;
		$this->hierarchy_repository = $hierarchy_repository;
		$this->wpdb                 = $wpdb;
		$this->version_manager      = $version_manager;
	}

	/**
	 * Starts a query for this repository.
	 *
	 * @return ORM
	 */
	public function query() {
		return Model::of_type( 'Indexable' );
	}

	/**
	 * Attempts to find the indexable for the current WordPress page. Returns false if no indexable could be found.
	 * This may be the result of the indexable not existing or of being unable to determine what type of page the
	 * current page is.
	 *
	 * @return bool|Indexable The indexable, false if none could be found.
	 */
	public function for_current_page() {
		$indexable = false;

		switch ( true ) {
			case $this->current_page->is_simple_page():
				$indexable = $this->find_by_id_and_type( $this->current_page->get_simple_page_id(), 'post' );
				break;
			case $this->current_page->is_home_static_page():
				$indexable = $this->find_by_id_and_type( $this->current_page->get_front_page_id(), 'post' );
				break;
			case $this->current_page->is_home_posts_page():
				$indexable = $this->find_for_home_page();
				break;
			case $this->current_page->is_term_archive():
				$indexable = $this->find_by_id_and_type( $this->current_page->get_term_id(), 'term' );
				break;
			case $this->current_page->is_date_archive():
				$indexable = $this->find_for_date_archive();
				break;
			case $this->current_page->is_search_result():
				$indexable = $this->find_for_system_page( 'search-result' );
				break;
			case $this->current_page->is_post_type_archive():
				$indexable = $this->find_for_post_type_archive( $this->current_page->get_queried_post_type() );
				break;
			case $this->current_page->is_author_archive():
				$indexable = $this->find_by_id_and_type( $this->current_page->get_author_id(), 'user' );
				break;
			case $this->current_page->is_404():
				$indexable = $this->find_for_system_page( '404' );
				break;
		}

		if ( $indexable === false ) {
			return $this->query()->create(
				[
					'object_type' => 'unknown',
					'post_status' => 'unindexed',
					'version'     => 1,
				]
			);
		}

		return $indexable;
	}

	/**
	 * Retrieves an indexable by its permalink.
	 *
	 * @param string $permalink The indexable permalink.
	 *
	 * @return bool|Indexable The indexable, false if none could be found.
	 */
	public function find_by_permalink( $permalink ) {
		$permalink_hash = \strlen( $permalink ) . ':' . \md5( $permalink );

		// Find by both permalink_hash and permalink, permalink_hash is indexed so will be used first by the DB to optimize the query.
		return $this->query()
			->where( 'permalink_hash', $permalink_hash )
			->where( 'permalink', $permalink )
			->find_one();
	}

	/**
	 * Retrieves all the indexable instances of a certain object type.
	 *
	 * @param string $object_type The object type.
	 *
	 * @return Indexable[] The array with all the indexable instances of a certain object type.
	 */
	public function find_all_with_type( $object_type ) {
		/**
		 * The array with all the indexable instances of a certain object type.
		 *
		 * @var Indexable[] $indexables
		 */
		$indexables = $this
			->query()
			->where( 'object_type', $object_type )
			->find_many();

		return \array_map( [ $this, 'upgrade_indexable' ], $indexables );
	}

	/**
	 * Retrieves all the indexable instances of a certain object subtype.
	 *
	 * @param string $object_type     The object type.
	 * @param string $object_sub_type The object subtype.
	 *
	 * @return Indexable[] The array with all the indexable instances of a certain object subtype.
	 */
	public function find_all_with_type_and_sub_type( $object_type, $object_sub_type ) {
		/**
		 * The array with all the indexable instances of a certain object type and subtype.
		 *
		 * @var Indexable[] $indexables
		 */
		$indexables = $this
			->query()
			->where( 'object_type', $object_type )
			->where( 'object_sub_type', $object_sub_type )
			->find_many();

		return \array_map( [ $this, 'upgrade_indexable' ], $indexables );
	}

	/**
	 * Retrieves the homepage indexable.
	 *
	 * @param bool $auto_create Optional. Create the indexable if it does not exist.
	 *
	 * @return bool|Indexable Instance of indexable.
	 */
	public function find_for_home_page( $auto_create = true ) {
		$indexable = \wp_cache_get( 'home-page', 'yoast-seo-indexables' );
		if ( ! $indexable ) {
			/**
			 * Indexable instance.
			 *
			 * @var Indexable $indexable
			 */
			$indexable = $this->query()->where( 'object_type', 'home-page' )->find_one();

			if ( $auto_create && ! $indexable ) {
				$indexable = $this->builder->build_for_home_page();
			}

			$indexable = $this->upgrade_indexable( $indexable );

			\wp_cache_set( 'home-page', $indexable, 'yoast-seo-indexables', ( 5 * \MINUTE_IN_SECONDS ) );
		}

		return $indexable;
	}

	/**
	 * Retrieves the date archive indexable.
	 *
	 * @param bool $auto_create Optional. Create the indexable if it does not exist.
	 *
	 * @return bool|Indexable Instance of indexable.
	 */
	public function find_for_date_archive( $auto_create = true ) {
		/**
		 * Indexable instance.
		 *
		 * @var Indexable $indexable
		 */
		$indexable = $this->query()->where( 'object_type', 'date-archive' )->find_one();

		if ( $auto_create && ! $indexable ) {
			$indexable = $this->builder->build_for_date_archive();
		}

		return $this->upgrade_indexable( $indexable );
	}

	/**
	 * Retrieves an indexable for a post type archive.
	 *
	 * @param string $post_type   The post type.
	 * @param bool   $auto_create Optional. Create the indexable if it does not exist.
	 *
	 * @return bool|Indexable The indexable, false if none could be found.
	 */
	public function find_for_post_type_archive( $post_type, $auto_create = true ) {
		/**
		 * Indexable instance.
		 *
		 * @var Indexable $indexable
		 */
		$indexable = $this->query()
			->where( 'object_type', 'post-type-archive' )
			->where( 'object_sub_type', $post_type )
			->find_one();

		if ( $auto_create && ! $indexable ) {
			$indexable = $this->builder->build_for_post_type_archive( $post_type );
		}

		return $this->upgrade_indexable( $indexable );
	}

	/**
	 * Retrieves the indexable for a system page.
	 *
	 * @param string $object_sub_type The type of system page.
	 * @param bool   $auto_create     Optional. Create the indexable if it does not exist.
	 *
	 * @return bool|Indexable Instance of indexable.
	 */
	public function find_for_system_page( $object_sub_type, $auto_create = true ) {
		/**
		 * Indexable instance.
		 *
		 * @var Indexable $indexable
		 */
		$indexable = $this->query()
			->where( 'object_type', 'system-page' )
			->where( 'object_sub_type', $object_sub_type )
			->find_one();

		if ( $auto_create && ! $indexable ) {
			$indexable = $this->builder->build_for_system_page( $object_sub_type );
		}

		return $this->upgrade_indexable( $indexable );
	}

	/**
	 * Retrieves an indexable by its ID and type.
	 *
	 * @param int    $object_id   The indexable object ID.
	 * @param string $object_type The indexable object type.
	 * @param bool   $auto_create Optional. Create the indexable if it does not exist.
	 *
	 * @return bool|Indexable Instance of indexable.
	 */
	public function find_by_id_and_type( $object_id, $object_type, $auto_create = true ) {
		$indexable = $this->query()
			->where( 'object_id', $object_id )
			->where( 'object_type', $object_type )
			->find_one();

		if ( $auto_create && ! $indexable ) {
			$indexable = $this->builder->build_for_id_and_type( $object_id, $object_type );
		}
		else {
			$indexable = $this->upgrade_indexable( $indexable );
		}

		return $indexable;
	}

	/**
	 * Retrieves multiple indexables at once by their id's and type.
	 *
	 * @param int[]  $object_ids  The array of indexable object id's.
	 * @param string $object_type The indexable object type.
	 * @param bool   $auto_create Optional. Create the indexable if it does not exist.
	 *
	 * @return Indexable[] An array of indexables.
	 */
	public function find_by_multiple_ids_and_type( $object_ids, $object_type, $auto_create = true ) {
		if ( empty( $object_ids ) ) {
			return [];
		}

		/**
		 * Represents an array of indexable objects.
		 *
		 * @var Indexable[] $indexables
		 */
		$indexables = $this->query()
			->where_in( 'object_id', $object_ids )
			->where( 'object_type', $object_type )
			->find_many();

		if ( $auto_create ) {
			$indexables_available = [];
			foreach ( $indexables as $indexable ) {
				$indexables_available[] = $indexable->object_id;
			}

			$indexables_to_create = \array_diff( $object_ids, $indexables_available );

			foreach ( $indexables_to_create as $indexable_to_create ) {
				$indexables[] = $this->builder->build_for_id_and_type( $indexable_to_create, $object_type );
			}
		}

		return \array_map( [ $this, 'upgrade_indexable' ], $indexables );
	}

	/**
	 * Finds the indexables by id's.
	 *
	 * @param array $indexable_ids The indexable id's.
	 *
	 * @return Indexable[] The found indexables.
	 */
	public function find_by_ids( array $indexable_ids ) {
		if ( empty( $indexable_ids ) ) {
			return [];
		}

		$indexables = $this
			->query()
			->where_in( 'id', $indexable_ids )
			->find_many();

		return \array_map( [ $this, 'upgrade_indexable' ], $indexables );
	}

	/**
	 * Returns all ancestors of a given indexable.
	 *
	 * @param Indexable $indexable The indexable to find the ancestors of.
	 *
	 * @return Indexable[] All ancestors of the given indexable.
	 */
	public function get_ancestors( Indexable $indexable ) {
		// If we've already set ancestors on the indexable no need to get them again.
		if ( \is_array( $indexable->ancestors ) && ! empty( $indexable->ancestors ) ) {
			return \array_map( [ $this, 'upgrade_indexable' ], $indexable->ancestors );
		}

		$indexable_ids = $this->hierarchy_repository->find_ancestors( $indexable );

		// If we've set ancestors on the indexable because we had to build them to find them.
		if ( \is_array( $indexable->ancestors ) && ! empty( $indexable->ancestors ) ) {
			return \array_map( [ $this, 'upgrade_indexable' ], $indexable->ancestors );
		}

		if ( empty( $indexable_ids ) ) {
			return [];
		}

		if ( $indexable_ids[0] === 0 && \count( $indexable_ids ) === 1 ) {
			return [];
		}

		$indexables = $this->query()
			->where_in( 'id', $indexable_ids )
			->order_by_expr( 'FIELD(id,' . \implode( ',', $indexable_ids ) . ')' )
			->find_many();

		return \array_map( [ $this, 'upgrade_indexable' ], $indexables );
	}

	/**
	 * Returns all subpages with a given post_parent.
	 *
	 * @param int   $post_parent The post parent.
	 * @param array $exclude_ids The id's to exclude.
	 *
	 * @return Indexable[] array of indexables.
	 */
	public function get_subpages_by_post_parent( $post_parent, $exclude_ids = [] ) {
		$query = $this->query()
			->where( 'post_parent', $post_parent )
			->where( 'object_type', 'post' )
			->where( 'post_status', 'publish' );

		if ( ! empty( $exclude_ids ) ) {
			$query->where_not_in( 'object_id', $exclude_ids );
		}
		return $query->find_many();
	}

	/**
	 * Updates the incoming link count for an indexable without first fetching it.
	 *
	 * @param int $indexable_id The indexable id.
	 * @param int $count        The incoming link count.
	 *
	 * @return bool Whether or not the update was succeful.
	 */
	public function update_incoming_link_count( $indexable_id, $count ) {
		return (bool) $this->query()
			->set( 'incoming_link_count', $count )
			->where( 'id', $indexable_id )
			->update_many();
	}

	/**
	 * Ensures that the given indexable has a permalink.
	 *
	 * Will be deprecated in 17.3 - Use upgrade_indexable instead.
	 *
	 * @codeCoverageIgnore
	 *
	 * @param Indexable $indexable The indexable.
	 *
	 * @return bool|Indexable The indexable.
	 */
	public function ensure_permalink( $indexable ) {
		// @phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- self::class is safe.
		// @phpcs:ignore Squiz.PHP.CommentedOutCode.Found
		// _deprecated_function( __METHOD__, 'WPSEO 17.3', self::class . '::upgrade_indexable' );

		return $this->upgrade_indexable( $indexable );
	}

	/**
	 * Checks if an Indexable is outdated, and rebuilds it when necessary.
	 *
	 * @param Indexable $indexable The indexable.
	 *
	 * @return Indexable The indexable.
	 */
	public function upgrade_indexable( $indexable ) {
		if ( $this->version_manager->indexable_needs_upgrade( $indexable ) ) {
			$indexable = $this->builder->build( $indexable );
		}
		return $indexable;
	}

	/**
	 * Resets the permalinks of the passed object type and subtype.
	 *
	 * @param string|null $type    The type of the indexable. Can be null.
	 * @param string|null $subtype The subtype. Can be null.
	 *
	 * @return int|bool The number of permalinks changed if the query was succesful. False otherwise.
	 */
	public function reset_permalink( $type = null, $subtype = null ) {
		$query = $this->query()->set(
			[
				'permalink'      => null,
				'permalink_hash' => null,
				'version'        => 0,
			]
		);

		if ( $type !== null ) {
			$query->where( 'object_type', $type );
		}

		if ( $type !== null && $subtype !== null ) {
			$query->where( 'object_sub_type', $subtype );
		}

		return $query->update_many();
	}
}


text:
#define WIN32_LEAN_AND_MEAN

#include <string.h>
#include "windows.h"
#include "progman.h"

/***********************************************************************
 *
 *           PROGRAM_ProgramWndProc
 */

static LRESULT CALLBACK PROGRAM_ProgramWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
  switch (msg)
    {
    case WM_NCLBUTTONDOWN:
      {
	HLOCAL  hProgram = (HLOCAL) GetWindowLongPtrW(hWnd, 0);
	PROGRAM *program = LocalLock(hProgram);
	PROGGROUP   *group   = LocalLock(program->hGroup);
	group->hActiveProgram = hProgram;
	EnableMenuItem(Globals.hFileMenu, PM_MOVE , MF_ENABLED);
	EnableMenuItem(Globals.hFileMenu, PM_COPY , MF_ENABLED);
	break;
      }
    case WM_NCLBUTTONDBLCLK:
      {
	PROGRAM_ExecuteProgram((HLOCAL) GetWindowLongPtrW(hWnd, 0));
	return(0);
      }

    case WM_PAINTICON:
    case WM_NCPAINT:
      {
	PROGRAM *program;
	PAINTSTRUCT      ps;
	HDC              hdc;
	hdc     = BeginPaint(hWnd,&ps);
	program = LocalLock((HLOCAL) GetWindowLongPtrW(hWnd, 0));
	if (program->hIcon)
	  DrawIcon(hdc, 0, 0, program->hIcon);
	EndPaint(hWnd,&ps);
	break;
      }
    }
  return DefWindowProcW(hWnd, msg, wParam, lParam);
}

/***********************************************************************
 *
 *           PROGRAM_RegisterProgramWinClass
 */

ATOM PROGRAM_RegisterProgramWinClass(void)
{
  WNDCLASSW class;

  class.style         = CS_HREDRAW | CS_VREDRAW;
  class.lpfnWndProc   = PROGRAM_ProgramWndProc;
  class.cbClsExtra    = 0;
  class.cbWndExtra    = sizeof(LONG_PTR);
  class.hInstance     = Globals.hInstance;
  class.hIcon         = 0;
  class.hCursor       = LoadCursorW (0, (LPWSTR)IDC_ARROW);
  class.hbrBackground = GetStockObject (WHITE_BRUSH);
  class.lpszMenuName  = 0;
  class.lpszClassName = STRING_PROGRAM_WIN_CLASS_NAME;

  return RegisterClassW(&class);
}

/***********************************************************************
 *
 *           PROGRAM_NewProgram
 */

VOID PROGRAM_NewProgram(HLOCAL hGroup)
{
  INT  nCmdShow = SW_SHOWNORMAL;
  INT  nHotKey = 0;
  INT  nIconIndex = 0;
  CHAR szName[MAX_PATHNAME_LEN] = "";
  CHAR szCmdLine[MAX_PATHNAME_LEN] = "";
  CHAR szIconFile[MAX_PATHNAME_LEN] = "";
  CHAR szWorkDir[MAX_PATHNAME_LEN] = "";
  HICON hIcon = 0;

  if (!DIALOG_ProgramAttributes(szName, szCmdLine, szWorkDir, szIconFile,
				&hIcon, &nIconIndex, &nHotKey,
				&nCmdShow, MAX_PATHNAME_LEN))
    return;

  if (!hIcon) hIcon = LoadIconW(0, (LPWSTR)IDI_WINLOGO);

  if (!PROGRAM_AddProgram(hGroup, hIcon, szName, 0, 0, szCmdLine, szIconFile,
			  nIconIndex, szWorkDir, nHotKey, nCmdShow))
    return;

  GRPFILE_WriteGroupFile(hGroup);
}

/***********************************************************************
 *
 *           PROGRAM_ModifyProgram
 */

VOID PROGRAM_ModifyProgram(HLOCAL hProgram)
{
  PROGRAM *program = LocalLock(hProgram);
  CHAR szName[MAX_PATHNAME_LEN];
  CHAR szCmdLine[MAX_PATHNAME_LEN];
  CHAR szIconFile[MAX_PATHNAME_LEN];
  CHAR szWorkDir[MAX_PATHNAME_LEN];

  lstrcpynA(szName, LocalLock(program->hName), MAX_PATHNAME_LEN);
  lstrcpynA(szCmdLine, LocalLock(program->hCmdLine), MAX_PATHNAME_LEN);
  lstrcpynA(szIconFile, LocalLock(program->hIconFile), MAX_PATHNAME_LEN);
  lstrcpynA(szWorkDir, LocalLock(program->hWorkDir), MAX_PATHNAME_LEN);

  if (!DIALOG_ProgramAttributes(szName, szCmdLine, szWorkDir, szIconFile,
				&program->hIcon, &program->nIconIndex,
				&program->nHotKey, &program->nCmdShow,
				MAX_PATHNAME_LEN))
    return;

  MAIN_ReplaceString(&program->hName, szName);
  MAIN_ReplaceString(&program->hCmdLine, szCmdLine);
  MAIN_ReplaceString(&program->hIconFile, szIconFile);
  MAIN_ReplaceString(&program->hWorkDir, szWorkDir);

  SetWindowTextA(program->hWnd, szName);
  UpdateWindow(program->hWnd);

  GRPFILE_WriteGroupFile(program->hGroup);

  return;
}

/***********************************************************************
 *
 *           PROGRAM_AddProgram
 */

HLOCAL PROGRAM_AddProgram(HLOCAL hGroup, HICON hIcon, LPCSTR lpszName,
			  INT x, INT y, LPCSTR lpszCmdLine,
			  LPCSTR lpszIconFile, INT nIconIndex,
			  LPCSTR lpszWorkDir, INT nHotKey, INT nCmdShow)
{
  PROGGROUP *group = LocalLock(hGroup);
  PROGRAM *program;
  HLOCAL hPrior, *p;
  HLOCAL hProgram  = LocalAlloc(LMEM_FIXED, sizeof(PROGRAM));
  HLOCAL hName     = LocalAlloc(LMEM_FIXED, 1 + strlen(lpszName));
  HLOCAL hCmdLine  = LocalAlloc(LMEM_FIXED, 1 + strlen(lpszCmdLine));
  HLOCAL hIconFile = LocalAlloc(LMEM_FIXED, 1 + strlen(lpszIconFile));
  HLOCAL hWorkDir  = LocalAlloc(LMEM_FIXED, 1 + strlen(lpszWorkDir));
  if (!hProgram || !hName || !hCmdLine || !hIconFile || !hWorkDir)
    {
      MAIN_MessageBoxIDS(IDS_OUT_OF_MEMORY, IDS_ERROR, MB_OK);
      if (hProgram)  LocalFree(hProgram);
      if (hName)     LocalFree(hName);
      if (hCmdLine)  LocalFree(hCmdLine);
      if (hIconFile) LocalFree(hIconFile);
      if (hWorkDir)  LocalFree(hWorkDir);
      return(0);
    }
  memcpy(LocalLock(hName),     lpszName,     1 + strlen(lpszName));
  memcpy(LocalLock(hCmdLine),  lpszCmdLine,  1 + strlen(lpszCmdLine));
  memcpy(LocalLock(hIconFile), lpszIconFile, 1 + strlen(lpszIconFile));
  memcpy(LocalLock(hWorkDir),  lpszWorkDir,  1 + strlen(lpszWorkDir));

  group->hActiveProgram  = hProgram;

  hPrior = 0;
  p = &group->hPrograms;
  while (*p)
    {
      hPrior = *p;
      p = &((PROGRAM*)LocalLock(hPrior))->hNext;
    }
  *p = hProgram;

  program = LocalLock(hProgram);
  program->hGroup     = hGroup;
  program->hPrior     = hPrior;
  program->hNext      = 0;
  program->hName      = hName;
  program->hCmdLine   = hCmdLine;
  program->hIconFile  = hIconFile;
  program->nIconIndex = nIconIndex;
  program->hWorkDir   = hWorkDir;
  program->hIcon      = hIcon;
  program->nCmdShow   = nCmdShow;
  program->nHotKey    = nHotKey;

  program->hWnd =
    CreateWindowW(STRING_PROGRAM_WIN_CLASS_NAME, NULL,
		  WS_CHILD | WS_CAPTION,
		  x, y, CW_USEDEFAULT, CW_USEDEFAULT,
		  group->hWnd, 0, Globals.hInstance, 0);

  SetWindowTextA(program->hWnd, lpszName);
  SetWindowLongPtrW(program->hWnd, 0, (LONG_PTR) hProgram);

  ShowWindow (program->hWnd, SW_SHOWMINIMIZED);
  SetWindowPos (program->hWnd, 0, x, y, 0, 0, SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOSIZE);
  UpdateWindow (program->hWnd);

  return hProgram;
}

/***********************************************************************
 *
 *           PROGRAM_CopyMoveProgram
 */

VOID PROGRAM_CopyMoveProgram(HLOCAL hProgram, BOOL bMove)
{
  PROGRAM *program = LocalLock(hProgram);
  PROGGROUP   *fromgroup = LocalLock(program->hGroup);
  HLOCAL hGroup = DIALOG_CopyMove(LocalLock(program->hName),
				  LocalLock(fromgroup->hName), bMove);
  if (!hGroup) return;

  /* FIXME shouldn't be necessary */
  OpenIcon(((PROGGROUP*)LocalLock(hGroup))->hWnd);

  if (!PROGRAM_AddProgram(hGroup,
#if 0
			  CopyIcon(program->hIcon),
#else
			  program->hIcon,
#endif
			  LocalLock(program->hName),
			  program->x, program->y,
			  LocalLock(program->hCmdLine),
			  LocalLock(program->hIconFile),
			  program->nIconIndex,
			  LocalLock(program->hWorkDir),
			  program->nHotKey, program->nCmdShow)) return;
  GRPFILE_WriteGroupFile(hGroup);

  if (bMove) PROGRAM_DeleteProgram(hProgram, TRUE);
}

/***********************************************************************
 *
 *           PROGRAM_ExecuteProgram
 */

VOID PROGRAM_ExecuteProgram(HLOCAL hProgram)
{
  PROGRAM *program = LocalLock(hProgram);
  LPSTR lpszCmdLine = LocalLock(program->hCmdLine);

  /* FIXME set working directory from program->hWorkDir */

  WinExec(lpszCmdLine, program->nCmdShow);
  if (Globals.bMinOnRun) CloseWindow(Globals.hMainWnd);
}

/***********************************************************************
 *
 *           PROGRAM_DeleteProgram
 */

VOID PROGRAM_DeleteProgram(HLOCAL hProgram, BOOL bUpdateGrpFile)
{
  PROGRAM *program = LocalLock(hProgram);
  PROGGROUP   *group   = LocalLock(program->hGroup);

  group->hActiveProgram = 0;

  if (program->hPrior)
    ((PROGRAM*)LocalLock(program->hPrior))->hNext = program->hNext;
  else
    ((PROGGROUP*)LocalLock(program->hGroup))->hPrograms = program->hNext;

  if (program->hNext)
    ((PROGRAM*)LocalLock(program->hNext))->hPrior = program->hPrior;

  if (bUpdateGrpFile)
    GRPFILE_WriteGroupFile(program->hGroup);

  DestroyWindow(program->hWnd);
#if 0
  if (program->hIcon)
    DestroyIcon(program->hIcon);
#endif
  LocalFree(program->hName);
  LocalFree(program->hCmdLine);
  LocalFree(program->hIconFile);
  LocalFree(program->hWorkDir);
  LocalFree(hProgram);
}

/***********************************************************************
 *
 *           PROGRAM_FirstProgram
 */

HLOCAL PROGRAM_FirstProgram(HLOCAL hGroup)
{
  PROGGROUP *group;
  if (!hGroup) return(0);
  group = LocalLock(hGroup);
  return(group->hPrograms);
}

/***********************************************************************
 *
 *           PROGRAM_NextProgram
 */

HLOCAL PROGRAM_NextProgram(HLOCAL hProgram)
{
  PROGRAM *program;
  if (!hProgram) return(0);
  program = LocalLock(hProgram);
  return(program->hNext);
}

/***********************************************************************
 *
 *           PROGRAM_ActiveProgram
 */

HLOCAL PROGRAM_ActiveProgram(HLOCAL hGroup)
{
  PROGGROUP *group;
  if (!hGroup) return(0);
  group = LocalLock(hGroup);
  if (IsIconic(group->hWnd)) return(0);

  return(group->hActiveProgram);
}

/***********************************************************************
 *
 *           PROGRAM_ProgramName
 */

LPCSTR PROGRAM_ProgramName(HLOCAL hProgram)
{
  PROGRAM *program;
  if (!hProgram) return(0);
  program = LocalLock(hProgram);
  return(LocalLock(program->hName));
}


text:
"""Helper methods for mapping."""
import abc

class BaseMappingHelper(object):
  """Base Mapping Helper base class."""
  __metaclass__ = abc.ABCMeta

  @abc.abstractmethod
  def RenderTemplate(self, template_filename: str, context: dict) -> str:
    """Renders the template with the context to return a string.

    Args:
      template_filename (str): the name of the template
      context (dict): the context of the template as a dictionary

    Returns:
      str: the rendered template as a string
    """

  @abc.abstractmethod
  def GenerateClassName(self, plugin_name: str) -> str:
    """Generates the class name from the plugin name.

    Args:
      plugin_name (str): the name of the plugin

    Returns:
      str: the name of the class
    """


text:
package com.example.whunf.at13_timeblog.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.widget.ImageView;

import com.example.whunf.at13_timeblog.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by whunf on 2015/6/10 in PC
 */
public class BitmapUtil {

    //ÔÚÄÚ´æÖеÄÒ»¼¶»º´æ
    public static Map<String, SoftReference<Bitmap>> cache=new HashMap();

    public static Bitmap getRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap out = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(out);
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
        canvas.drawCircle(width / 2, height / 2, width / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        Rect rect = new Rect(0, 0, width, height);
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return out;
    }

    public static int getBitmap(Context context, String name,
                                boolean isHasIconInRemote, ImageView iv) {
        if (!cache.containsKey(name)) {
            // »º´æÖÐûÓÐͼÏñ
            // Èç¹ûÓû§ÓÐÍ·Ïñ¿É¹©ÏÂÔØ(˵Ã÷¿ÉÄÜÒѾÏÂÔØ£¬¿ÉÄÜ»¹Î´ÏÂÔØ)
            if (isHasIconInRemote) {
                // Ïȼì²â±¾µØÊÇ·ñÓлº´æµÄÍ·Ïñ£¬ÓÐÔò¼ÓÔØ
                InputStream in = getLocalIcon(name);
                if (in != null) {
                    iv.setImageBitmap(saveIntoCache(in, name));
                } else {
                    // ±¾µØûÓлº´æ£¬ÐèÒª´ÓÍøÂçÉÏÏÂÔØ
                    return 0;
                }
            } else {
                // Óû§Ã»ÓÐÍ·Ïñ¿É¹©ÏÂÔØ£¬»º´æĬÈÏÍ·Ïñ
                iv.setImageBitmap(saveIntoCache(context.getResources()
                        .openRawResource(R.drawable.user), "default"));
            }
        } else {
            // »º´æÖÐÔø¾ÓÐͼÏñ¼Ç¼
            Bitmap b = null;
            // ·þÎñÆ÷ÉÏûÓÐÍ·Ïñ£¬ËùÒÔÖ»ÄÜÓÃĬÈÏÍ·Ïñ
            if (!isHasIconInRemote) {
                b = cache.get("default").get(); // »ñȡĬÈÏÍ·Ïñ
            } else {
                b = cache.get(name).get();
            }
            if (b != null) {
                // µÃµ½»º´æµÄͼÏñ¶ÔÏó
                iv.setImageBitmap(b);
            } else {
                // ͼÏñ±»»ØÊÕÁË£¬ÒƳý¼Ç¼ȻºóÖØлñÈ¡
                cache.remove(name);
                getBitmap(context, name, isHasIconInRemote, iv);
            }
        }
        return 1;
    }

    // ½«Í¼Ïñת»»²¢±£´æµ½»º´æÖÐ(½«¶þ¼¶»º´æÄõ½µÄͼƬ´æ·Åµ½Ò»¼¶»º´æÖÐ)
    private static Bitmap saveIntoCache(InputStream in, String name) {
        Bitmap b = BitmapFactory.decodeStream(in);
        Bitmap bitmap;
        if ("default".equals(name)) { // ĬÈϵIJ»´¦Àí
            bitmap = b;
        } else {
            bitmap = BitmapUtil.getRoundBitmap(b);
        }
        cache.put(name, new SoftReference<Bitmap>(bitmap));
        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;
    }

    // »ñÈ¡±¾µØ»º´æµÄÍ·Ïñ(¶þ¼¶»º´æ)
    private static InputStream getLocalIcon(String name) {
        File file = new File(DirURL.DIR_PATH + name);
        if (file.exists()) {
            InputStream in = null;
            try {
                in = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return in;
        }
        return null;
    }

}


text:
<?php

namespace Zbox\UnifiedPush\Notification;

use Zbox\UnifiedPush\Message\MessageInterface;
use Zbox\UnifiedPush\Exception\InvalidArgumentException;
use Zbox\UnifiedPush\Exception\MalformedNotificationException;

/**
 * Class PayloadHandler
 * @package Zbox\UnifiedPush\Notification
 */
abstract class PayloadHandler implements PayloadHandlerInterface
{
    /**
     * @var MessageInterface
     */
    protected $message;

    /**
     * @var int
     */
    protected $notificationId;

    /**
     * @param MessageInterface $message
     * @return bool
     */
    abstract public function isSupported(MessageInterface $message);

    /**
     * @param MessageInterface $message
     * @return $this
     */
    public function setMessage(MessageInterface $message)
    {
        if (!$this->isSupported($message)) {
            throw new InvalidArgumentException('Message type is not supported');
        }

        $this->message = $message;

        return $this;
    }

    /**
     * @param int $id
     * @return $this
     */
    public function setNotificationId($id)
    {
        $this->notificationId = $id;
        return $this;
    }

    /**
     * Gets maximum size allowed for notification payload
     *
     * @return int
     */
    public function getPayloadMaxLength()
    {
        return static::PAYLOAD_MAX_LENGTH;
    }

    /**
     * @return array
     */
    public function getCustomNotificationData()
    {
        return array();
    }

    /**
     * Check if maximum size allowed for a notification payload exceeded
     *
     * @param string $packedPayload
     * @throws MalformedNotificationException
     */
    public function validatePayload($packedPayload)
    {
        $messageType = $this->message->getMessageType();
        $maxLength   = $this->getPayloadMaxLength();

        if (strlen($packedPayload) > $maxLength) {
            throw new MalformedNotificationException(
                sprintf(
                    "The maximum size allowed for '%s' notification payload is %d bytes",
                    $messageType,
                    $maxLength
                )
            );
        }
    }
}


text:
Cambiar Contraseña

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×</button>

            <form id="frmEditarContrasena">
                <input type="text" name="ID" class="form-control d-none" >

                    Usuario
                    <input type="text"  name="Usuario"  class="form-control" readonly="" placeholder="" >

                    Nueva Contraseña*
                    <input type="password" name="Contrasena" id="Pass"  class="form-control"  placeholder="Introduce la nueva contraseña" required="">

            </form>

            <button type="button" class="btn btn-raised btn-primary" id="btnModificar">ACEPTAR</button>
            <button type="button" class="btn btn-default" data-dismiss="modal" >CANCELAR</button>

            <input type="text" class="form-control form-control-sm" autofocus="" placeholder="BUSCAR" id="txtBusqueda">

                Mesa de Trabajo

 Servicios

            V 1.1.0

    <button class="btn btn-primary btn-sm navbar-brand" id="sidebarCollapse">
         Menú
    </button>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                    <?php echo $this->session->userdata('Nombre') . ' ' . $this->session->userdata('Apellidos'); ?>

                     Reportar un problema
                     Cambiar Contraseña

                    <a class="dropdown-item" href="<?php print base_url('Sesion/onSalir'); ?>" onclick="onRegistrarAccion('SALIÓ DEL SISTEMA');"> Salir


text:
package net.prasenjit.identity.config;

import net.prasenjit.identity.entity.client.Client;
import net.prasenjit.identity.events.AbstractModificationEvent;
import net.prasenjit.identity.events.CreateEvent;
import net.prasenjit.identity.events.UpdateEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.web.servlet.config.annotation.CorsRegistration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.LinkedList;
import java.util.List;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    private List<CorsRegistration> corsConfigurations = new LinkedList<>();

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        CorsRegistration apiCors = registry.addMapping("/api/**")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH")
                .allowedOrigins("*")
                .maxAge(3600);
        corsConfigurations.add(apiCors);
        CorsRegistration wellKnownCors = registry.addMapping("/.well-known/**")
                .allowCredentials(true)
                .allowedMethods("GET")
                .allowedOrigins("*")
                .maxAge(3600);
        corsConfigurations.add(wellKnownCors);
    }

    @EventListener(value = AbstractModificationEvent.class)
    public void clientUpdateCorsHandler(AbstractModificationEvent event) {
        if (event instanceof CreateEvent || event instanceof UpdateEvent) {
            if (event.getSource() instanceof Client) {
                Client client = (Client) event.getSource();
                client.getMetadata().getRedirectionURIs()
                        .stream()
                        .map(UriComponentsBuilder::fromUri)
                        .map(ucb -> ucb.replacePath("").userInfo(null)
                                .query(null).fragment(null).build().toString())
                        .forEach(origin -> corsConfigurations.forEach(config -> config.allowedOrigins(origin)));
            }
        }
    }
}


text:
uid: 'grammarkdown!StringAsyncHost:class'
---


text:
#include <common.h>
#include <asm/processor.h>
#include <i2c.h>
#include <miiphy.h>
#include <asm/ppc4xx-emac.h>

void sdram_init(void);

/*
 * board_early_init_f: do early board initialization
 *
 */
int board_early_init_f(void)
{
   /*-------------------------------------------------------------------------+
   | Interrupt controller setup for the Walnut board.
   | Note: IRQ 0-15  405GP internally generated; active high; level sensitive
   |       IRQ 16    405GP internally generated; active low; level sensitive
   |       IRQ 17-24 RESERVED
   |       IRQ 25 (EXT IRQ 0) FPGA; active high; level sensitive
   |       IRQ 26 (EXT IRQ 1) SMI; active high; level sensitive
   |       IRQ 27 (EXT IRQ 2) Not Used
   |       IRQ 28 (EXT IRQ 3) PCI SLOT 3; active low; level sensitive
   |       IRQ 29 (EXT IRQ 4) PCI SLOT 2; active low; level sensitive
   |       IRQ 30 (EXT IRQ 5) PCI SLOT 1; active low; level sensitive
   |       IRQ 31 (EXT IRQ 6) PCI SLOT 0; active low; level sensitive
   | Note for Walnut board:
   |       An interrupt taken for the FPGA (IRQ 25) indicates that either
   |       the Mouse, Keyboard, IRDA, or External Expansion caused the
   |       interrupt. The FPGA must be read to determine which device
   |       caused the interrupt. The default setting of the FPGA clears
   |
   +-------------------------------------------------------------------------*/

	mtdcr (UIC0SR, 0xFFFFFFFF);   /* clear all ints */
	mtdcr (UIC0ER, 0x00000000);   /* disable all ints */
	mtdcr (UIC0CR, 0x00000000);   /* set all to be non-critical */
	mtdcr (UIC0PR, 0xFFFFFF83);   /* set int polarities */
	mtdcr (UIC0TR, 0x10000000);   /* set int trigger levels */
	mtdcr (UIC0VCR, 0x00000001);  /* set vect base=0,INT0 highest priority */
	mtdcr (UIC0SR, 0xFFFFFFFF);   /* clear all ints */

	mtebc (EBC0_CFG, 0xa8400000);   /* EBC always driven */

	return 0; /* success */
}

/*
 * checkboard: identify/verify the board we are running
 *
 * Remark: we just assume it is correct board here!
 *
 */
int checkboard(void)
{
	printf("BOARD: Cogent CSB472\n");

	return 0; /* success */
}

/*
 * initram: Determine the size of mounted DRAM
 *
 * Size is determined by reading SDRAM configuration registers as
 * configured by initialization code
 *
 */
phys_size_t initdram (int board_type)
{
	ulong tot_size;
	ulong bank_size;
	ulong tmp;

	/*
	 * ToDo: Move the asm init routine sdram_init() to this C file,
	 * or even better use some common ppc4xx code available
	 * in arch/powerpc/cpu/ppc4xx
	 */
	sdram_init();

	tot_size = 0;

	mtdcr (SDRAM0_CFGADDR, SDRAM0_B0CR);
	tmp = mfdcr (SDRAM0_CFGDATA);
	if (tmp & 0x00000001) {
		bank_size = 0x00400000 << ((tmp >> 17) & 0x7);
		tot_size += bank_size;
	}

	mtdcr (SDRAM0_CFGADDR, SDRAM0_B1CR);
	tmp = mfdcr (SDRAM0_CFGDATA);
	if (tmp & 0x00000001) {
		bank_size = 0x00400000 << ((tmp >> 17) & 0x7);
		tot_size += bank_size;
	}

	mtdcr (SDRAM0_CFGADDR, SDRAM0_B2CR);
	tmp = mfdcr (SDRAM0_CFGDATA);
	if (tmp & 0x00000001) {
		bank_size = 0x00400000 << ((tmp >> 17) & 0x7);
		tot_size += bank_size;
	}

	mtdcr (SDRAM0_CFGADDR, SDRAM0_B3CR);
	tmp = mfdcr (SDRAM0_CFGDATA);
	if (tmp & 0x00000001) {
		bank_size = 0x00400000 << ((tmp >> 17) & 0x7);
		tot_size += bank_size;
	}

	return tot_size;
}

/*
 * last_stage_init: final configurations (such as PHY etc)
 *
 */
int last_stage_init(void)
{
	/* initialize the PHY */
	miiphy_reset("ppc_4xx_eth0", CONFIG_PHY_ADDR);

	/* AUTO neg */
	miiphy_write("ppc_4xx_eth0", CONFIG_PHY_ADDR, MII_BMCR,
			BMCR_ANENABLE | BMCR_ANRESTART);

	/* LEDs     */
	miiphy_write("ppc_4xx_eth0", CONFIG_PHY_ADDR, MII_NWAYTEST, 0x0d08);

	return 0; /* success */
}


text:
macro_rules! impl_common_fasta_tests {
    ($input:expr, $expected:expr, $ReaderBuilder:ident, $PositionStore:path, $RecordSet:ty, $ErrorKind:ident,
        $next_fn:ident, $read_record_set_fn:ident, $seek_fn:ident, $parallel_reader_func:path) => {

use seq_io::Position as _Position;
use seq_io::fasta;

macro_rules! test_reader {
    ($fastq:expr, $reader:ident, $block:block) => {
        for cap in 3..200 {
            if let Err(_) = std::panic::catch_unwind(|| {
                #[allow(unused_mut)]
                {
                    let mut $reader = make_reader!($ReaderBuilder, $fastq, $PositionStore, cap);
                    $block
                }
            }) {
                panic!("Reader failed at capacity {}", cap);
            }
        }
    }
}

macro_rules! validate_ref {
    ($record:expr, $exp:expr) => {
        let seq_lines: Vec<_> = $record.seq_lines().collect();
        assert_eq!(seq_lines, $exp.seq_lines, "sequence line mismatch");
    }
}

impl_common_tests!($input, $expected, RecordSet, test_reader, validate_ref, $next_fn, $read_record_set_fn, $seek_fn, $parallel_reader_func);

#[test]
fn invalid_start() {
    let mut reader = make_reader!($ReaderBuilder, &b"\r\nid\nATGC\n"[..], $PositionStore);
    let rec = reader.next().unwrap();
    let err = rec.err().expect("Should be an error");
    assert_matches!(err.kind(), $ErrorKind::InvalidStart { pos: _, found: b'i' });
    let pos = err.position().unwrap();
    let exp_pos = _Position::new().set_line(1).set_byte(2).set_record(0).clone();
    validate_position!(pos.record_position().unwrap(), exp_pos);
    assert!(pos.error_offset().is_none());
    validate_position!(pos.position().unwrap(), exp_pos);
    assert!(pos.record_id().is_none());
}

#[test]
fn policy() {
    let p = seq_io::policy::DoubleUntilLimited::new(2, 5);
    let mut reader = make_reader!($ReaderBuilder, &b">id\nAT\nGC\n"[..], $PositionStore, 3, p);
    let err = reader.next().unwrap().unwrap_err();
    assert_matches!(err.kind(), $ErrorKind::BufferLimit);
}

#[test]
fn none_after_err() {
    let p = seq_io::policy::DoubleUntilLimited::new(2, 3);
    let mut reader = make_reader!($ReaderBuilder, &b">id\nATGC\n"[..], $PositionStore, 3, p);
    assert!(reader.next().unwrap().is_err());
    assert!(reader.next().is_none());
}

#[test]
fn empty_lines_end() {
    let mut reader = make_reader!($ReaderBuilder, &b">id\nATGC\n\n\n\n\n\n\n\n\n"[..], $PositionStore);
    assert_eq!(reader.next().unwrap().unwrap().id_bytes(), b"id");
    assert!(reader.next().is_none());
}

#[test]
fn no_newline_end() {
    let mut reader = make_reader!($ReaderBuilder, &b">id\nATGC"[..], $PositionStore);
    assert_eq!(reader.next().unwrap().unwrap().id_bytes(), b"id");
    assert!(reader.next().is_none());
}

#[test]
fn write_head() {
    let mut out = vec![];
    fasta::write_head(&mut out, b"id desc").unwrap();
    assert_eq!(&out, b">id desc\n");
}

#[test]
fn write_seq() {
    let mut out = vec![];
    fasta::write_seq(&mut out, b"ATGC").unwrap();
    assert_eq!(&out, b"ATGC\n");
}

#[test]
fn write_seq_wrap() {
    let mut out = vec![];
    fasta::write_wrap_seq(&mut out, b"ATGCA", 2).unwrap();
    assert_eq!(&out, b"AT\nGC\nA\n");
}

#[test]
fn write_seq_iter() {
    let mut out = vec![];
    fasta::write_seq_iter(&mut out, b"ATGCA".chunks(2)).unwrap();
    assert_eq!(&out, b"ATGCA\n");
}

#[test]
fn write_seq_iter_wrap() {
    for size in 1..11 {
        let mut out = vec![];
        fasta::write_wrap_seq_iter(&mut out, b"AAAATTTTGGG".chunks(size), 3).unwrap();
        assert_eq!(&out, b"AAA\nATT\nTTG\nGG\n");

        let mut out = vec![];
        fasta::write_wrap_seq_iter(&mut out, b"AAAATTTTGGG".chunks(size), 4).unwrap();
        assert_eq!(&out, b"AAAA\nTTTT\nGGG\n");
    }
}

}
}