text:
define(['jquery'], function() {

	var xhr = new XMLHttpRequest();

	xhr.onreadystatechange = function() {
		console.log(xhr.readyState, xhr.status);
		if (xhr.readyState === 4 && xhr.status === 200) {
			console.log(xhr.responseText);
		}
	};

	xhr.open("GET", "/api/widgets");
	xhr.send();

	$.ajax("/api/widgets").success(function(result) {
		console.dir(result);
	});

	//request("/api/widgets").then(function() {
	//	console.dir(arguments);
	//});

});

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.bandeira.sidnei.appleitor.ExcluirColetasActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/lnTitulo"
        >
        <TextView
            android:id="@+id/txtCodigo"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:textSize="20dp"
            android:text="Código"
            android:textColor="#ffa602"
            android:layout_marginLeft="4dp" />

        <TextView
            android:id="@+id/txtTitulo"
            android:layout_width="293dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:textSize="20dp"
            android:text="Descrição da Coleta"
            android:textColor="#ffa602"
            android:layout_marginLeft="4dp" />

    </LinearLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listagemColetas"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/lnTitulo"/>

</LinearLayout>


text:
package java6.instructions;

public class LookupSwitch {

    public static void main(String[] args) {
        switch (args.length) {
            case -100: System.out.println("-100"); break;
            case 0: System.out.println("0"); break;
            case 3: System.out.println("3"); break;
            case 5: System.out.println("5"); break;
            default: System.out.println("default");
        }
    }

}


text:
package eagle.jfaster.org.cluster;

import eagle.jfaster.org.config.common.MergeConfig;
import eagle.jfaster.org.rpc.Request;
import eagle.jfaster.org.spi.Scope;
import eagle.jfaster.org.spi.Spi;

/**
 *
 * ha策略
 *
 * Created by fangyanpeng1 on 2017/8/4.
 */
@Spi(scope = Scope.PROTOTYPE)
public interface HaStrategy<T> {

    void setConfig(MergeConfig config);

    Object call(Request request, LoadBalance<T> loadBalance);
}


text:
namespace WinApiNet.Tests
{
    using System.IO;
    using NUnit.Framework;
    using WinApiNet.Handles;

    #pragma warning disable 618

    [TestFixture]
    public class WinHandleTests
    {
        [Test]
        public void CloseHandle()
        {
            var f = File.OpenRead(this.GetType().Assembly.Location);

            bool result = WinHandle.CloseHandle(f.Handle);

            Assert.That(result, Is.True);
        }

        [Test]
        public void CloseSafeHandle()
        {
            var f = File.OpenRead(this.GetType().Assembly.Location);

            bool result = WinHandle.CloseHandle(f.SafeFileHandle);

            Assert.That(result, Is.True);
        }
    }
}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Queue;
using Orleans.Providers;
using Orleans.Providers.Streams.AzureQueue;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Streams;
using Orleans.TestingHost;
using Xunit;
using Xunit.Abstractions;

namespace UnitTests.StorageTests
{
    public class AzureQueueAdapterTests : IDisposable
    {
        private readonly ITestOutputHelper output;
        private const int NumBatches = 20;
        private const int NumMessagesPerBatch = 20;
        private string deploymentId;
        public static readonly string AZURE_QUEUE_STREAM_PROVIDER_NAME = "AQAdapterTests";

        private static readonly SafeRandom Random = new SafeRandom();

        public AzureQueueAdapterTests(ITestOutputHelper output)
        {
            this.output = output;
            this.deploymentId = MakeDeploymentId();
            LogManager.Initialize(new NodeConfiguration());
            BufferPool.InitGlobalBufferPool(new MessagingConfiguration(false));
            SerializationManager.InitializeForTesting();
        }

        public void Dispose()
        {
            AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(AZURE_QUEUE_STREAM_PROVIDER_NAME, deploymentId, StorageTestConstants.DataConnectionString).Wait();
        }

        [Fact, TestCategory("Functional"), TestCategory("Halo"), TestCategory("Azure"), TestCategory("Streaming")]
        public async Task SendAndReceiveFromAzureQueue()
        {
            var properties = new Dictionary<string, string>
                {
                    {AzureQueueAdapterFactory.DataConnectionStringPropertyName, StorageTestConstants.DataConnectionString},
                    {AzureQueueAdapterFactory.DeploymentIdPropertyName, deploymentId}
                };
            var config = new ProviderConfiguration(properties, "type", "name");

            var adapterFactory = new AzureQueueAdapterFactory();
            adapterFactory.Init(config, AZURE_QUEUE_STREAM_PROVIDER_NAME, LogManager.GetLogger("AzureQueueAdapter", LoggerType.Application), null);
            await SendAndReceiveFromQueueAdapter(adapterFactory, config);
        }

        private async Task SendAndReceiveFromQueueAdapter(IQueueAdapterFactory adapterFactory, IProviderConfiguration config)
        {
            IQueueAdapter adapter = await adapterFactory.CreateAdapter();
            IQueueAdapterCache cache = adapterFactory.GetQueueAdapterCache();

            // Create receiver per queue
            IStreamQueueMapper mapper = adapterFactory.GetStreamQueueMapper();
            Dictionary<QueueId, IQueueAdapterReceiver> receivers = mapper.GetAllQueues().ToDictionary(queueId => queueId, adapter.CreateReceiver);
            Dictionary<QueueId, IQueueCache> caches = mapper.GetAllQueues().ToDictionary(queueId => queueId, cache.CreateQueueCache);

            await Task.WhenAll(receivers.Values.Select(receiver => receiver.Initialize(TimeSpan.FromSeconds(5))));

            // test using 2 streams
            Guid streamId1 = Guid.NewGuid();
            Guid streamId2 = Guid.NewGuid();

            int receivedBatches = 0;
            var streamsPerQueue = new ConcurrentDictionary<QueueId, HashSet<IStreamIdentity>>();

            // reader threads (at most 2 active queues because only two streams)
            var work = new List<Task>();
            foreach( KeyValuePair<QueueId, IQueueAdapterReceiver> receiverKvp in receivers)
            {
                QueueId queueId = receiverKvp.Key;
                var receiver = receiverKvp.Value;
                var qCache = caches[queueId];
                Task task = Task.Factory.StartNew(() =>
                {
                    while (receivedBatches < NumBatches)
                    {
                        var messages = receiver.GetQueueMessagesAsync(CloudQueueMessage.MaxNumberOfMessagesToPeek).Result.ToArray();
                        if (!messages.Any())
                        {
                            continue;
                        }
                        foreach (AzureQueueBatchContainer message in messages.Cast<AzureQueueBatchContainer>())
                        {
                            streamsPerQueue.AddOrUpdate(queueId,
                                id => new HashSet<IStreamIdentity> { new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString()) },
                                (id, set) =>
                                {
                                    set.Add(new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString()));
                                    return set;
                                });
                            output.WriteLine("Queue {0} received message on stream {1}", queueId,
                                message.StreamGuid);
                            Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<int>().Count());  // "Half the events were ints"
                            Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<string>().Count());  // "Half the events were strings"
                        }
                        Interlocked.Add(ref receivedBatches, messages.Length);
                        qCache.AddToCache(messages);
                    }
                });
                work.Add(task);
            }

            // send events
            List<object> events = CreateEvents(NumMessagesPerBatch);
            work.Add(Task.Factory.StartNew(() => Enumerable.Range(0, NumBatches)
                .Select(i => i % 2 == 0 ? streamId1 : streamId2)
                .ToList()
                .ForEach(streamId =>
                    adapter.QueueMessageBatchAsync(streamId, streamId.ToString(),
                        events.Take(NumMessagesPerBatch).ToArray(), null, RequestContext.Export()).Wait())));
            await Task.WhenAll(work);

            // Make sure we got back everything we sent
            Assert.Equal(NumBatches, receivedBatches);

            // check to see if all the events are in the cache and we can enumerate through them
            StreamSequenceToken firstInCache = new EventSequenceToken(0);
            foreach (KeyValuePair<QueueId, HashSet<IStreamIdentity>> kvp in streamsPerQueue)
            {
                var receiver = receivers[kvp.Key];
                var qCache = caches[kvp.Key];

                foreach (IStreamIdentity streamGuid in kvp.Value)
                {
                    // read all messages in cache for stream
                    IQueueCacheCursor cursor = qCache.GetCacheCursor(streamGuid, firstInCache);
                    int messageCount = 0;
                    StreamSequenceToken tenthInCache = null;
                    StreamSequenceToken lastToken = firstInCache;
                    while (cursor.MoveNext())
                    {
                        Exception ex;
                        messageCount++;
                        IBatchContainer batch = cursor.GetCurrent(out ex);
                        output.WriteLine("Token: {0}", batch.SequenceToken);
                        Assert.True(batch.SequenceToken.CompareTo(lastToken) >= 0, $"order check for event {messageCount}");
                        lastToken = batch.SequenceToken;
                        if (messageCount == 10)
                        {
                            tenthInCache = batch.SequenceToken;
                        }
                    }
                    output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid);
                    Assert.Equal(NumBatches / 2, messageCount);
                    Assert.NotNull(tenthInCache);

                    // read all messages from the 10th
                    cursor = qCache.GetCacheCursor(streamGuid, tenthInCache);
                    messageCount = 0;
                    while (cursor.MoveNext())
                    {
                        messageCount++;
                    }
                    output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid);
                    const int expected = NumBatches / 2 - 10 + 1; // all except the first 10, including the 10th (10 + 1)
                    Assert.Equal(expected, messageCount);
                }
            }
        }

        private List<object> CreateEvents(int count)
        {
            return Enumerable.Range(0, count).Select(i =>
            {
                if (i % 2 == 0)
                {
                    return Random.Next(int.MaxValue) as object;
                }
                return Random.Next(int.MaxValue).ToString(CultureInfo.InvariantCulture);
            }).ToList();
        }

        internal static string MakeDeploymentId()
        {
            const string DeploymentIdFormat = "deployment-{0}";
            string now = DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm-ss-ffff");
            return String.Format(DeploymentIdFormat, now);
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 95(3): 559 (2003)

#### Original name
Gomphidius pseudoflavipes O.K. Mill. & F.J. Camacho, 2003

### Remarks
null


text:
<?php
namespace App;
use \Illuminate\Database\Eloquent\Model;

class VotoDetalleMesa extends Model {
    protected $table = 'votos_detalle_mesas';
	protected $primaryKey='id_votos_detalle';
	public $timestamps = false;
    //Ejemplo de definir campos
    //protected $fillable = ['username','email','password'];

}


text:
/* Datei Actor.java                  E.Ammann    */
/* Klasse fuer die Actor-Threads                 */

class Actor extends Thread {
    private Shared shared;
    private int delta;

    public Actor(Shared shared, int delta) {
        this.shared = shared;
        this.delta = delta;
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            shared.change_counter(delta);
            System.out.println(shared.get_counter());
            yield();
        }
    }
}


text:
// This file is automatically generated.

package adila.db;

/*
 * ZTE Z998
 *
 * DEVICE: coeus
 * MODEL: Z998
 */
final class coeus_z998 {
    public static final String DATA = "ZTE|Z998|";
}


text:
[![NPM version][meta-img-npm]][meta-url-npm]
[![Build status][meta-img-travis]][meta-url-travis]
[![Coveralls status][meta-img-coveralls]][meta-url-coveralls]
[![Support us][meta-img-gratipay]][meta-url-gratipay]

Expands variable placeholders in objects.

## Installation

This module can be installed easily with [npm][url-npm]:

```sh
$ npm install expands
```

## Usage

These examples show you how `expands` works:

```js
var assert = require('assert');
var expand = require('expands');

// Expands string
assert.deepEqual(expand({
  message: 'Welcome {name}!',
  name: 'intruder'
}), {
  message: 'Welcome intruder!',
  name: 'intruder'
});

// Expands array
assert.deepEqual(expand({
  messages: [
    'Welcome {name}!',
    'You are {age} years old.',
    12345
  ],
  name: 'intruder',
  age: 1000
}), {
  messages: [
    'Welcome intruder!',
    'You are 1000 years old.',
    12345
  ],
  name: 'intruder',
  age: 1000
});

// Expands deep path
assert.deepEqual(expand({
  foo: {
    bar: {
      one: '1',
      two: '2'
    },
    message: 'One is {foo.bar.one} and two is {foo.bar.two}.'
  }
}), {
  foo: {
    bar: {
      one: '1',
      two: '2'
    },
    message: 'One is 1 and two is 2.'
  }
});

// Expands circle dependency
assert.deepEqual(expand({
  a: 'from {b}', // expanding is top-down so `a` will be expanded first
  b: 'from {c}',
  c: 'from {a}', // `a` is not expanded completely, resolved to 'from ',
}), {
  a: 'from from from from ',
  b: 'from from from ',
  c: 'from from '
});
```

## Contributing

Before [create a pull request][repo-url-pull-request], make sure that you:

* Followed coding convention as described in
**[.editorconfig][repo-editorconfig]** or **[.jshintrc][repo-jshintrc]** file
(more information can be found at [editorconfig.org][url-editorconfig] and
[www.jshint.com/docs][url-jshint-docs], respectively).

* Added tests for your code.

* Passed all tests!

To execute all tests, simply run:

    $ npm test

### Contributors

* **Author**: [Meo][url-meoguru]

## License

This module is released under [MIT license][repo-license].

[//]: # (Site URLs)
[url-node]: http://nodejs.org
[url-npm]: https://www.npmjs.org/
[url-editorconfig]: http://editorconfig.org
[url-jshint-docs]: http://www.jshint.com/docs

[//]: # (Repository URLs and resources)
[repo-url-new-issue]: https://github.com/meoguru/expands/issues/new
[repo-url-pull-request]: https://github.com/meoguru/expands/pulls
[repo-license]: https://github.com/meoguru/expands/blob/master/LICENSE
[repo-editorconfig]: https://github.com/meoguru/expands/blob/master/.editorconfig
[repo-jshintrc]: https://github.com/meoguru/expands/blob/master/.jshintrc

[//]: # (Repository meta information)
[meta-url-npm]: https://npmjs.org/package/expands
[meta-img-npm]: https://img.shields.io/npm/v/expands.svg?style=flat
[meta-url-travis]: https://travis-ci.org/meoguru/expands
[meta-img-travis]: https://img.shields.io/travis/meoguru/expands.svg?style=flat
[meta-url-coveralls]: https://coveralls.io/r/meoguru/expands
[meta-img-coveralls]: https://img.shields.io/coveralls/meoguru/expands/master.svg?style=flat
[meta-url-gratipay]: https://gratipay.com/meoguru
[meta-img-gratipay]: https://img.shields.io/gratipay/meoguru.svg?style=flat

[//]: # (Authors and contributors URLs)
[url-meoguru]: http://meo.guru


text:
{{'i_am_a_phrase' | translate}}

I am a full sentence, with commas and a period.

  <md-button class="md-raised md-primary" type="submit" ng-click="continue()">Word</md-button>

{{loadingMsg}}

clear
star
<md-icon class="md-raised md-primary" type="submit" ng-click="continue()">up_arrow</md-icon>
i_am_a_phrase
i_am_a_phrase_without_a_key
i_am_a_phrase
I am just a word


text:
namespace AForge.Genetic
{
    using System;
    using System.Collections;
    using System.Collections.Generic;

    /// <summary>
    /// Elite selection method.
    /// </summary>
    ///
    /// <remarks>Elite selection method selects specified amount of
    /// best chromosomes to the next generation.</remarks>
    ///
    public class EliteSelection : ISelectionMethod
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="EliteSelection"/> class.
        /// </summary>
        public EliteSelection( ) { }

        /// <summary>
        /// Apply selection to the specified population.
        /// </summary>
        ///
        /// <param name="chromosomes">Population, which should be filtered.</param>
        /// <param name="size">The amount of chromosomes to keep.</param>
        ///
        /// <remarks>Filters specified population keeping only specified amount of best
        /// chromosomes.</remarks>
        ///
        public void ApplySelection( List<IChromosome> chromosomes, int size )
        {
            // sort chromosomes
            chromosomes.Sort( );

            // remove bad chromosomes
            chromosomes.RemoveRange( size, chromosomes.Count - size );
        }
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BenchmarkDotNet.Extensions;

namespace BenchmarkDotNet.Validators
{
    public class DeferredExecutionValidator : IValidator
    {
        public static readonly IValidator DontFailOnError = new DeferredExecutionValidator(false);
        public static readonly IValidator FailOnError = new DeferredExecutionValidator(true);

        private DeferredExecutionValidator(bool failOnError) => TreatsWarningsAsErrors = failOnError;

        public bool TreatsWarningsAsErrors { get; }

        public IEnumerable<ValidationError> Validate(ValidationParameters validationParameters)
            => validationParameters.Benchmarks
                .Where(benchmark => IsDeferredExecution(benchmark.Descriptor.WorkloadMethod.ReturnType))
                .Select(benchmark =>
                    new ValidationError(
                        TreatsWarningsAsErrors,
                        $"Benchmark {benchmark.Descriptor.Type.Name}.{benchmark.Descriptor.WorkloadMethod.Name} returns a deferred execution result ({benchmark.Descriptor.WorkloadMethod.ReturnType.GetCorrectCSharpTypeName(false, false)}). " +
                        "You need to either change the method declaration to return a materialized result or consume it on your own. You can use .Consume() extension method to do that.",
                        benchmark));

        private bool IsDeferredExecution(Type returnType)
        {
            if (returnType.IsByRef && !returnType.IsGenericType)
                return IsDeferredExecution(returnType.GetElementType());

            if (returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(Task<>) || returnType.GetGenericTypeDefinition() == typeof(ValueTask<>)))
                return IsDeferredExecution(returnType.GetGenericArguments().Single());

            if (returnType == typeof(IEnumerable) || returnType == typeof(IQueryable))
                return true;

            if (!returnType.IsGenericType)
                return false;

            return returnType.GetGenericTypeDefinition() == typeof(IEnumerable<>)
                || returnType.GetGenericTypeDefinition() == typeof(IQueryable<>)
                || returnType.GetGenericTypeDefinition() == typeof(Lazy<>);
        }
    }
}


text:
void test01()
{
  bool test __attribute__((unused)) = true;
  using std::tr1::add_reference;
  using std::tr1::is_same;
  using namespace __gnu_test;

  VERIFY( (is_same<add_reference<int>::type, int&>::value) );
  VERIFY( (is_same<add_reference<int&>::type, int&>::value) );
  VERIFY( (is_same<add_reference<const int>::type, const int&>::value) );
  VERIFY( (is_same<add_reference<int*>::type, int*&>::value) );
  VERIFY( (is_same<add_reference<ClassType&>::type, ClassType&>::value) );
  VERIFY( (is_same<add_reference<ClassType>::type, ClassType&>::value) );

  VERIFY( (is_same<add_reference<void>::type, void>::value) );
  VERIFY( (is_same<add_reference<const void>::type, const void>::value) );
}

int main()
{
  test01();
  return 0;
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CONTENT_RENDERER_PEPPER_PEPPER_DEVICE_ENUMERATION_HOST_HELPER_H_
#define CONTENT_RENDERER_PEPPER_PEPPER_DEVICE_ENUMERATION_HOST_HELPER_H_

#include <stdint.h>

#include <memory>
#include <vector>

#include "base/callback_forward.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
#include "ppapi/c/dev/ppb_device_ref_dev.h"
#include "ppapi/host/host_message_context.h"
#include "url/gurl.h"

namespace ppapi {
struct DeviceRefData;

namespace host {
class ResourceHost;
}

}  // namespace ppapi

namespace IPC {
class Message;
}

namespace content {

// Resource hosts that support device enumeration can use this class to filter
// and process PpapiHostMsg_DeviceEnumeration_* messages.
// TODO(yzshen): Refactor ppapi::host::ResourceMessageFilter to support message
// handling on the same thread, and then derive this class from the filter
// class.
class CONTENT_EXPORT PepperDeviceEnumerationHostHelper {
 public:
  class Delegate {
   public:
    virtual ~Delegate() {}

    using DevicesCallback = base::RepeatingCallback<void(
        const std::vector<ppapi::DeviceRefData>& /* devices */)>;
    using DevicesOnceCallback = base::OnceCallback<void(
        const std::vector<ppapi::DeviceRefData>& /* devices */)>;

    // Enumerates devices of the specified type.
    virtual void EnumerateDevices(PP_DeviceType_Dev type,
                                  DevicesOnceCallback callback) = 0;

    // Starts monitoring devices of the specified |type|. Returns a
    // subscription ID that must be used to stop monitoring for the device
    // |type|. Does not invoke |callback| synchronously. |callback| is invoked
    // when device changes of the specified |type| occur.
    virtual size_t StartMonitoringDevices(PP_DeviceType_Dev type,
                                          const DevicesCallback& callback) = 0;

    // Stops monitoring devices of the specified |type|. The
    // |subscription_id| is the return value of StartMonitoringDevices.
    virtual void StopMonitoringDevices(PP_DeviceType_Dev type,
                                       size_t subscription_id) = 0;
  };

  // |resource_host| and |delegate| must outlive this object.
  PepperDeviceEnumerationHostHelper(ppapi::host::ResourceHost* resource_host,
                                    base::WeakPtr<Delegate> delegate,
                                    PP_DeviceType_Dev device_type,
                                    const GURL& document_url);
  ~PepperDeviceEnumerationHostHelper();

  // Returns true if the message has been handled.
  bool HandleResourceMessage(const IPC::Message& msg,
                             ppapi::host::HostMessageContext* context,
                             int32_t* result);

 private:
  class ScopedEnumerationRequest;
  class ScopedMonitoringRequest;

  // Has a different signature than HandleResourceMessage() in order to utilize
  // message dispatching macros.
  int32_t InternalHandleResourceMessage(
      const IPC::Message& msg,
      ppapi::host::HostMessageContext* context,
      bool* handled);

  int32_t OnEnumerateDevices(ppapi::host::HostMessageContext* context);
  int32_t OnMonitorDeviceChange(ppapi::host::HostMessageContext* context,
                                uint32_t callback_id);
  int32_t OnStopMonitoringDeviceChange(
      ppapi::host::HostMessageContext* context);

  void OnEnumerateDevicesComplete(
      const std::vector<ppapi::DeviceRefData>& devices);
  void OnNotifyDeviceChange(uint32_t callback_id,
                            const std::vector<ppapi::DeviceRefData>& devices);

  // Non-owning pointers.
  ppapi::host::ResourceHost* resource_host_;
  base::WeakPtr<Delegate> delegate_;

  PP_DeviceType_Dev device_type_;

  std::unique_ptr<ScopedEnumerationRequest> enumerate_;
  std::unique_ptr<ScopedMonitoringRequest> monitor_;

  ppapi::host::ReplyMessageContext enumerate_devices_context_;

  DISALLOW_COPY_AND_ASSIGN(PepperDeviceEnumerationHostHelper);
};

}  // namespace content

#endif  // CONTENT_RENDERER_PEPPER_PEPPER_DEVICE_ENUMERATION_HOST_HELPER_H_


text:
PubDate: 1805-09-30
Slug: letters/thomas-jefferson/to-thomas-jefferson-september-30-1805
Title: To Thomas Jefferson September 30, 1805
Date: Mon Aug  4 09:08:56 EDT 2014

   From the original letter at the Library of Congress.

   New Rochelle (N.Y) Sep 30 '05

   Dear Sir

   I write you this letter entirely on my own account, and I begin it without
   ceremony.

   In the year 84 or 5 a motion was made in the legislature of Virginia for
   making an acknowledgement to me for voluntary services during the
   revolution. The bill, as I am informed, for that purpose, passed two
   readings and was lost on the third reading by three votes. The
   acknowledgement proposed to be given was a tract of land, called, as I
   have been told, the secretary's tract, which I suppose is since disposed
   of, but I wish the matter to be brought over again and I think it ought to
   be.

   After the State of Rhode Island had refused complying with the five per
   cent duty recommended by Congress and the State of Virginia had repealed
   the Act she had passed to grant it, I saw no possibility of going on
   otherwise than by authorizing Congress to make laws for the Union in all
   cases that were to extend equally over all the states, and I wrote to
   Chancellor Livingston, minister for foreign affairs, and Robert Morris
   minister of finance in the winter of 81-2 on the subject. The proposal
   in the letter, was, to add a continental legislature to Congress. The Idea
   took with them at once. But as this would be called encreasing the power
   of Congress, and as I intended taking up the subject when I should see the
   Country wrong enough to be put right, it was best, on that account, to
   leave it to the States individually to make me what acknowledgement they
   pleased, and it was on this ground that the state of New York made me a
   present of a farm worth at that time about a thousand pound (York
   currency) and the state of Pennsylvania voted me five hundred pounds, but
   the state of Virginia having negatived the grant she had proposed to make
   me, on the recommendation of Genl Washington, the matter went no
   further with any of the States.

   I suggest another Idea, which is, that as only two of the states have made
   me any acknowledgement, that Congress take up the subject for the whole (I
   suppose the two States who have made me an acknowledgement will not object
   to this) and grant me a tract of land that I can make something of. Had it
   not been for the economy and extreme frugality with which I have lived I
   should at this time of life be in an unpleasant situation. But I wish you
   to be assured that whatever event this proposal may take it will make no
   alteration in my principles or my conduct. I have been a volunteer to the
   world for thirty years without taking profits from anything I have
   published in America or in Europe. I have relinquished all profits that
   those publications might come cheap among the people for whom they were
   intended.

   Yours in friendship

   Thomas Paine

   P. S. If any further explanation be wanted I will communicate it


text:
<?php
class home_main_post_right_list_scroll extends AQ_Block {

	//set and create block
	function __construct() {
		$block_options = array(
		  'name' => esc_attr__('Home post with right post scroll', 'jelly_text_main'),
			'size' => 'span12',
		);

		//create the block
		parent::__construct('home_main_post_right_list_scroll', $block_options);
	}

	//create form
	function form($instance) {
        $titles = isset($instance['titles']) ? esc_attr($instance['titles']) : 'Home with right post scroll';
        $number_show = isset($instance['number_show']) ? absint($instance['number_show']) : 5;
		$number_offset = isset($instance['number_offset']) ? absint($instance['number_offset']) : 0;
    $css_class_builder = isset($instance['css_class_builder']) ? esc_attr($instance['css_class_builder']) : 'color-3';
        ?>

<label for="<?php echo esc_attr($this->get_field_id('titles')); ?>"><?php esc_attr_e('Title:', 'jelly_text_main'); ?>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('titles')); ?>" name="<?php echo esc_attr($this->get_field_name('titles')); ?>" type="text" value="<?php echo esc_attr($titles); ?>" />

<label for="<?php echo esc_attr($this->get_field_id('css_class_builder')); ?>"><?php esc_attr_e('CSS class','jelly_text_main'); ?>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('css_class_builder')); ?>" name="<?php echo esc_attr($this->get_field_name('css_class_builder')); ?>" type="text" value="<?php echo esc_attr($css_class_builder); ?>" />

<label for="<?php echo esc_attr($this->get_field_id('number_show')); ?>"><?php esc_attr_e('Number of posts to show:', 'jelly_text_main'); ?>
            <input id="<?php echo esc_attr($this->get_field_id('number_show')); ?>" name="<?php echo esc_attr($this->get_field_name('number_show')); ?>" type="text" value="<?php echo esc_attr($number_show); ?>" size="3" />

<label for="<?php echo esc_attr($this->get_field_id('number_offset')); ?>"><?php esc_attr_e('Offset posts:', 'jelly_text_main'); ?>
            <input id="<?php echo esc_attr($this->get_field_id('number_offset')); ?>" name="<?php echo esc_attr($this->get_field_name('number_offset')); ?>" type="text" value="<?php echo esc_attr($number_offset); ?>" size="3" />

            <label for="<?php echo esc_attr($this->get_field_id('cats')); ?>"><?php esc_attr_e('Choose your category:', 'jelly_text_main'); ?>

                <?php
                $categories = get_categories('hide_empty=0');
                echo "
";
                foreach ($categories as $cat) {
                    $option = '<input type="checkbox" id="' . $this->get_field_id('cats') . '[]" name="' . $this->get_field_name('cats') . '[]"';
                    if (isset($instance['cats'])) {
                        foreach ($instance['cats'] as $cats) {
                            if ($cats == $cat->term_id) {
                                $option = $option . ' checked="checked"';
                            }
                        }
                    }
                    $option .= ' value="' . $cat->term_id . '" />';
                    $option .= ' ';
                    $option .= 'term_id.'">'.$cat->cat_name.'';
                    $option .= '
';
                    echo $option;
                }
                ?>

		<?php

	}

	//create block
	function block($instance) {

		extract($instance);

        $titles = apply_filters('widget_title', empty($instance['titles']) ? 'Recent Posts' : $instance['titles'], $instance, $this->id_base);

        if (!$number_show = absint($instance['number_show'])){$number_show = 4;}
		if (isset($instance['number_offset'])==''){$number_offset = 0;}else{$number_offset = absint($instance['number_offset']);}
        if (!isset($instance["cats"])) { $cats = '';}

        // array to call recent posts.

        $jellywp_args = array(
            'showposts' => $number_show,
            'category__in' => $cats,
			'ignore_sticky_posts' => 1,
			'offset' => $number_offset
        );

        $jellywp_widget = null;
        $jellywp_widget = new WP_Query($jellywp_args);
        // Widget title

        // Post list in widget

        $i = 0;?>
        <div class="widget main_post_style main_right_post_style_list_scroll clearfix <?php echo esc_attr($instance['css_class_builder']);?>">
        <?php if (!empty($instance['titles'])) {?>

<?php echo esc_attr($instance["titles"]);?>

<?php }?>

        <?php
        while ($jellywp_widget->have_posts()) {
            $jellywp_widget->the_post();
			$post_id = get_the_ID();
            //get all post categories
            $categories = get_the_category(get_the_ID());
            $i++;
	        if ($i == 1) {

                ?>
<div class="feature-two-column left-post-display-content margin-left-post main-post-right-list <?php if(!of_get_option('disable_css_animation')==1){echo esc_attr("appear_animation");}?> feature-custom">

                   <a href="<?php the_permalink(); ?>" class="feature-link" title="<?php the_title_attribute(); ?>">
<?php if ( has_post_thumbnail()) {the_post_thumbnail('medium-feature');}
else{echo '';} ?>
<?php echo jelly_post_type(); ?>

<?php echo jelly_total_score_post_front_small_circle(get_the_ID());?>

<?php  if(of_get_option('disable_post_category') !=1){
          if ($categories) {
            echo '';
            foreach( $categories as $tag) {
              $tag_link = get_category_link($tag->term_id);
              $titleColor = jelly_categorys_title_color($tag->term_id, "category", false);
             echo ''.$tag->name.'';
            }
            echo "";
            }
       }?>
<?php echo jelly_post_like_meta(get_the_ID());?>

<a href="<?php the_permalink(); ?>"><?php the_title()?>

 <?php echo jelly_post_meta(get_the_ID()); ?>

<?php echo jelly_post_excerpt(get_the_excerpt('')); ?>

  <?php echo jelly_post_meta_footer(get_the_ID()); ?>

            <?php
			}else{?>

<a  href="<?php the_permalink(); ?>" class="feature-image-link image_post" title="<?php the_title_attribute(); ?>">
<?php if ( has_post_thumbnail()) {the_post_thumbnail('small-feature');}
else{echo '';} ?>
<?php echo jelly_post_type(); ?>

    <?php  if(of_get_option('disable_post_category') !=1){
          if ($categories) {
            echo '';
            foreach( $categories as $tag) {
              $tag_link = get_category_link($tag->term_id);
              $titleColor = jelly_categorys_title_color($tag->term_id, "category", false);
             echo ''.$tag->name.'';
            }
            echo "";
            }
       }?>
<?php echo jelly_total_score_post_front_small_list(get_the_ID());?>

<a href="<?php the_permalink(); ?>"><?php the_title()?>

<?php echo jelly_post_meta(get_the_ID()); ?>

         <?php }}?>

        <?php
        wp_reset_query();

    }

	    function update($new_instance, $old_instance) {
        return $new_instance;
    }

}


text:
struct AppOptions
{
    // Verbosity level.  0 -- quiet, 1 -- normal, 2 -- verbose, 3 -- very verbose.
    int verbosity;

    // The first (and only) argument of the program is stored here.
    seqan::CharString inputFile;

    // maximal number of reads to analyse, exit as if the file contained only the first #maxReads
    __uint64 maxReads;

    // output dirname
    seqan::CharString outdir;

    // haystack size for sequence duplication finder
    __uint64 dupHaystackSize;

    // dump a human readable representation into a given output stream
    void out(std::ostream & os);

    AppOptions() :
        verbosity(1),
        maxReads(ULONG_MAX)
    {}
};


text:
namespace World404.Core
{
    public enum Mode
    {
        Passive,
        Normal,
        Aggresive
    }
}


text:
Spyre
=========

Spyre is a Web Application Framework for providing a simple user interface for Python data projects.

Requirements
----
Spyre runs on the minimalist python web framework, **[cherrypy]**, with **[jinja2]** templating. Spyre is all about data and data visualization, so you'll also need **[pandas]** and **[matplotlib]**.

Installation
----
```bash
    $ pip install dataspyre
```

The Simplest of Examples
----
Here's a very simple spyre example that shows the primary components of a spyre app
```python
from spyre import server

class SimpleApp(server.App):
	title = "Simple App"
	inputs = [{ "type":"text",
				"key":"words",
				"label":"write words here",
				"value":"hello world",
				"action_id":"simple_html_output"}]

	outputs = [{"type":"html",
				"id":"simple_html_output"}]

	def getHTML(self, params):
		words = params["words"]
		return "Here's what you wrote in the textbox: <b>%s</b>" % words

app = SimpleApp()
app.launch()
```

The SimpleApp class inherits server.App which includes a few methods that you can override to generate outputs. In this case we want our app to display HTML (just text for now) so we'll overide the getHTML method. This method should return a string.

We also need to specify the attributes of our inputs and outputs which we can do by defining the App's inputs and outputs variables.

### inputs ###
This is a list of dictionaries, one dictionary for each input element. In our simple example above, there's only one input, of type "text". We give it a label and initial value with the keys "label" and "value".  The value from this input will be used as an input parameter when generating the outputs (html in this case), so we need to also give it a key that we can reference in the getHTML method. "action_id" is an optional variable that equals id from either an output or a control element (we'll get to controls in the next example). When action_id is defined, a change in the input will result in either an update to the referenced output or a call to the functions connected to the referenced control.

### outputs ###
An output's `type` can be "plot", "image", "table", "html", or "download". In addition to the type, we also need to provide a unique id (must start with a letter). If this output is suppose to get updated on execution of one of the controls specified in the list of controls, we need to also specify the control_id of that controller (which we'll see in the next example). All outputs get generated on page load by default. If we want an output *not* to load on the page load, we can also specify an "on_page_load" attribute and set it to False.

### controls ###
Controls are one mechanism by which a spyre app can update its outputs. A control's `id` can be referenced by either an input or an output. When an output references the control's id, executing the control updates that output. When an input references the controld's id (via the "action_id"), updating the input executes the control. The two control `type` options are "button" and "hidden". "button" will add a button to the left panel. No control is added to the left-panel for control_types "hidden" (this is useful for linking a single input action to multiple outputs).

### generating an output ###
Let's get back to our getHTML method. Notice that it takes a single argument: params. params is a dictionary containing:

1. all of the input values (where the key is specified in the input dictionary)
2. the output_id for the output that needs to get created. You usually don't need to do anything with this.

With the exception of the input type "checkboxgroup", the value of each of the params elements is a string. The string returned by getHTML will be displayed in the right panel of our Spyre app.

### launching the app ###
To launch our app we just need to create an instance of our SimpleApp class and call the launch method. Assuming you name this file "simple_sine_example.py" you can launch this app from the command line with:
```bash
    $ python simple_sine_example.py
```
The output will indicate where the app is being served (http://127.0.0.1:8080 by default)

If all goes smoothly your spyre app should look like this:

![simple sine example screenshot](https://raw.githubusercontent.com/adamhajari/spyre/master/examples/screenshots/simple_sine_screenshot.png)

Example 2: Tabs and Tables
----
Let's look at another example to introduce controls, tabs, and a second output type, tables. Many apps will require multiple outputs. In these cases, it's often cleaner to put each output in a separte tab.

In the example below we'll show historical stock data in a line graph and a table, each in it's own tab.  Since inputs can only have a single action_id (and we have two outputs), we'll need to introduce a button control in order to update both outputs.

```python
from spyre import server

import pandas as pd
import urllib2
import json

class StockExample(server.App):
	title = "Historical Stock Prices"

	inputs = [{		"type":'dropdown',
					"label": 'Company',
					"options" : [ {"label": "Google", "value":"GOOG"},
								  {"label": "Yahoo", "value":"YHOO"},
								  {"label": "Apple", "value":"AAPL"}],
					"key": 'ticker',
					"action_id": "update_data"}]

	controls = [{	"type" : "hidden",
					"id" : "update_data"}]

	tabs = ["Plot", "Table"]

	outputs = [{ "type" : "plot",
					"id" : "plot",
					"control_id" : "update_data",
					"tab" : "Plot"},
				{ "type" : "table",
					"id" : "table_id",
					"control_id" : "update_data",
					"tab" : "Table",
					"on_page_load" : True }]

	def getData(self, params):
		ticker = params['ticker']
		# make call to yahoo finance api to get historical stock data
		api_url = 'https://chartapi.finance.yahoo.com/instrument/1.0/{}/chartdata;type=quote;range=3m/json'.format(ticker)
		result = urllib2.urlopen(api_url).read()
		data = json.loads(result.replace('finance_charts_json_callback( ','')[:-1])  # strip away the javascript and load json
		self.company_name = data['meta']['Company-Name']
		df = pd.DataFrame.from_records(data['series'])
		df['Date'] = pd.to_datetime(df['Date'],format='%Y%m%d')
		return df

	def getPlot(self, params):
		df = self.getData(params).set_index('Date').drop(['volume'],axis=1)
		plt_obj = df.plot()
		plt_obj.set_ylabel("Price")
		plt_obj.set_title(self.company_name)
		fig = plt_obj.get_figure()
		return fig

app = StockExample()
app.launch(port=9093)

```
There's a few things to point out here:

1. This app uses a dropdown input type. It still has a label and variable_name (that's common to all input types), but you now also need to enumerate all of the options for the dropdown menu. For each of the options, "label" is displayed in the menu and "value" is value of that input variable when that option is selected.
2. The tabs variable is a list of tab names. These names are used as labels for the tabs as well as html ids so they can't contain any spaces.
3. There's a "table" output type that requires all of the same attribute types as the plot output type.
4. Additionally, we need to specify a "tabs" attribute for each output. This should match the name of one of the items listed in the tabs list.
5. The control variable has control_type, label, and control_id attributes. Each output has an optional control_id attribute which can be used to reference a control. When a control action is taken (such as clicking a button), every output that references that control will be updated.

We're also overriding getData, a method which should fetch or generate the data that will go into the table.  Just like getPlot, it takes a params argument which is a dictionary containing all of our input variables. getData should return a pandas DataFrame.

Launch the app just as you did in the previous example. The app now has two tabs.

### Plot tab ###
![stocks graph tab example screenshot](https://raw.githubusercontent.com/adamhajari/spyre/master/examples/screenshots/stocks_graph_screenshot.png)

### Table tab ###
![stocks table tab example screenshot](https://raw.githubusercontent.com/adamhajari/spyre/master/examples/screenshots/stocks_table_screenshot.png)

License
----

MIT

Acknowledgements
----

Much of the work that went into creating Spyre happened during hack weeks at **[Next Big Sound]**. If you're a talented engineer or data scientist looking for a great place to work, check out their about page for job openings!

[cherrypy]:http://docs.cherrypy.org/en/latest/install.html
[jinja2]:http://jinja.pocoo.org/docs/dev/intro/#installation
[pandas]:http://pandas.pydata.org/pandas-docs/stable/install.html#recommended-dependencies
[matplotlib]:http://matplotlib.org/users/installing.html
[simple sine example screenshot]:https://raw.githubusercontent.com/adamhajari/spyre/master/examples/screenshots/simple_sine_screenshot.png
[Next Big Sound]: https://www.nextbigsound.com/about


text:
import { deviceHasTouch, deviceHasMouse, mouseEvents, touchEvents, passiveEventSupport,
  dummyEvent } from './constants';

// list of callbacks that are called every time the event fires
// only one callback function per eventType b/c notifyOfAll is only used by inputTracker
// {
//   eventType: callback,
//   eventA: cbFunctionA,
//   eventB: cbFunctionB,
// }
const notifyOfAllSubs = {};

// list of callbacks that are called only for the next event and then deleted
// {
//   eventType: [{ id, callback }, { id, callback }, ...],
//   eventA: [{ id: 1, callback: cbFunctionA }, { id: 2, callback: cbFunctionB }],
//   eventB: [{ id: 3, callback: cbFunctionC }, { id: 4, callback: cbFunctionD }],
// }
const notifyOfNextSubs = {};

// list of sub IDs with corresponding index in notifyOfNextSubs array for easy cancelation of sub
// {
//   eventType: { id: indexInNotifyOfNextSubsArray },
//   eventA: { 1: 0, 2: 1 },
//   eventB: { 3: 0, 4: 1 },
// }
const subsIDs = {};

// generate unique ID
let idPlace = 0;
function nextID(eType) {
  if (idPlace === Number.MAX_SAFE_INTEGER) idPlace = 0;
  idPlace++;
  if (subsIDs[eType][idPlace] === undefined) return idPlace;
  return nextID(eType);
}

// subscribe to notifyOfNext, returns the ID of the subscription so it can be canceled
export function notifyOfNext(eType, callback) {
  const id = nextID(eType);
  subsIDs[eType][id] = notifyOfNextSubs[eType].push({ id, callback }) - 1;
  return id;
}

// cancel an already existing subscription
const blankFunction = () => {};
export function cancelNotifyOfNext(eType, id) {
  if (subsIDs[eType][id] !== 'undefined') {
    notifyOfNextSubs[eType][subsIDs[eType][id]].callback = blankFunction;
    delete subsIDs[eType][id];
  }
}

// subscribe to notifyOfAll, only used by inputTracker
export function notifyOfAll(eTypes, callback) {
  eTypes.forEach((eType) => {
    notifyOfAllSubs[eType] = callback;
  });
}

// notify all when event comes in
function handleNotifyAll(e) {
  notifyOfAllSubs[e.type](e);
}

// notify next when event comes, if the callback returns 'reNotifyOfNext', then re-subscribe
// using the same id
function handleNotifyNext(e) {
  if (notifyOfNextSubs[e.type].length === 0) return;
  e.persist = blankFunction;
  const reNotifyOfNext = [];
  const reNotifyOfNextIDs = {};
  notifyOfNextSubs[e.type].forEach((sub) => {
    if (sub.callback(e) === 'reNotifyOfNext') {
      reNotifyOfNextIDs[sub.id] = reNotifyOfNext.push(sub) - 1;
    }
  });
  notifyOfNextSubs[e.type] = reNotifyOfNext;
  subsIDs[e.type] = reNotifyOfNextIDs;
}

function handleNotifyAllAndNext(e) {
  handleNotifyAll(e);
  handleNotifyNext(e);
}

// setup event listeners and notification system for events
function setupEvent(element, eType, handler, capture) {
  notifyOfNextSubs[eType] = [];
  subsIDs[eType] = {};
  element.addEventListener(eType, handler, passiveEventSupport ? {
    capture,
    // don't set click listener as passive because syntheticClick may call preventDefault
    passive: eType !== 'click',
  } : capture);
}

if (deviceHasTouch) {
  // set up click listener for use with syntheticClick on touch devices
  setupEvent(window, 'click', handleNotifyAll, true);

  // if the device has touch, then setup event listeners for touch events
  Object.keys(touchEvents).forEach((eType) => {
    setupEvent(document, eType,
      eType === 'touchstart' ? handleNotifyAllAndNext : handleNotifyAll,
      true,
    );
  });
}

// if the device has a mouse, then setup event listeners for mouse events,
// see manageNotifyOfNext and handleNotifyOfNext in index.js for more info
// on why a specific listener is set
if (deviceHasMouse) {
  Object.keys(mouseEvents).forEach((eType) => {
    setupEvent(document, eType,
      eType === 'mouseenter' ? handleNotifyAllAndNext : handleNotifyAll,
      // don't use capture for enter/leave so the event only fires when the mouse leaves the doc
      !(eType === 'mouseenter' || eType === 'mouseleave'),
    );
  });

  setupEvent(document, 'dragstart', handleNotifyNext, true);

  if (passiveEventSupport) {
    setupEvent(document, 'scroll', handleNotifyNext, true);
  }

  notifyOfNextSubs.mutation = [];
  subsIDs.mutation = {};
  const mutationEvent = dummyEvent('mutation');
  const mo = new MutationObserver(handleNotifyNext.bind(null, mutationEvent));
  mo.observe(document, { childList: true, attributes: true, subtree: true, characterData: true });
}

// always set focus/blur listener on the window so know when leave/enter the app/window/tab
['focus', 'blur'].forEach((eType) => {
  setupEvent(window, eType, handleNotifyNext, false);
});

// always set keydown listener for enter key events for form submission
setupEvent(document, 'keydown', handleNotifyAll, true);


text:
/*
Package detour provides a net.Conn interface to dial another dialer if a site fails to connect directly.
It maintains three states of a connection: initial, direct and detoured
along with a temporary whitelist across connections.
It also add a blocked site to permanent whitelist.

The action taken and state transistion in each phase is as follows:
+-------------------------+-----------+-------------+-------------+-------------+-------------+
|                         | no error  |   timeout*  | conn reset/ | content     | other error |
|                         |           |             | dns hijack  | hijack      |             |
+-------------------------+-----------+-------------+-------------+-------------+-------------+
| dial (intial)           | noop      | detour      | detour      | n/a         | noop        |
| first read (intial)     | direct    | detour(buf) | detour(buf) | detour(buf) | noop        |
|                         |           | add to tl   | add to tl   | add to tl   |             |
| follow-up read (direct) | direct    | add to tl   | add to tl   | add to tl   | noop        |
| follow-up read (detour) | noop      | rm from tl  | rm from tl  | rm from tl  | rm from tl  |
| close (direct)          | noop      | n/a         | n/a         | n/a         | n/a         |
| close (detour)          | add to wl | n/a         | n/a         | n/a         | n/a         |
+-------------------------+-----------+-------------+-------------+-------------+-------------+
| next dial/read(in tl)***| noop      | rm from tl  | rm from tl  | rm from tl  | rm from tl  |
| next close(in tl)       | add to wl | n/a         | n/a         | n/a         | n/a         |
+-------------------------+-----------+-------------+-------------+-------------+-------------+
(buf) = resend buffer
tl = temporary whitelist
wl = permanent whitelist

*   The timeout for first read is firstReadTimeoutToDetour, otherwise it's based
    on system default or caller supplied deadline.
**  DNS hijacking is only checked at dial time.
*** Connection is always detoured if the site is in tl or wl.
*/
package detour

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"net"
	"sync"
	"sync/atomic"
	"time"

	"github.com/getlantern/golog"
)

var (
	log = golog.LoggerFor("detour")

	firstReadTimeoutToDetour = 3 * time.Second

	// instance of Detector
	blockDetector atomic.Value

	zeroTime time.Time
)

func init() {
	blockDetector.Store(detectorByCountry(""))
}

type dialFunc func(ctx context.Context, network, addr string) (net.Conn, error)

type Conn struct {
	// keep track of the total bytes read in this connection
	// Keep it at the top to make sure 64-bit alignment, see
	// https://golang.org/pkg/sync/atomic/#pkg-note-BUG
	readBytes int64

	muConn sync.RWMutex
	// the actual connection, will change so protect it
	// can't user atomic.Value as the concrete type may vary
	conn net.Conn

	// don't access directly, use inState() and setState() instead
	state uint32

	// the function to dial detour if the site fails to connect directly
	dialDetour dialFunc

	muLocalBuffer sync.Mutex
	// localBuffer keep track of bytes sent through direct connection
	// in initial state so we can resend them when detour
	localBuffer bytes.Buffer

	network, addr  string
	_readDeadline  atomic.Value
	_writeDeadline atomic.Value
}

// Wrapped exposes the underlying connection.
func (dc *Conn) Wrapped() net.Conn {
	dc.muConn.RLock()
	defer dc.muConn.RUnlock()
	return dc.conn
}

const (
	stateInitial = iota
	stateDirect
	stateDetour
	stateClosed
)

var statesDesc = []string{
	"initially",
	"directly",
	"detoured",
	"closed",
}

// SetCountry sets the ISO 3166-1 alpha-2 country code
// to load country specific detection rules
func SetCountry(country string) {
	blockDetector.Store(detectorByCountry(country))
}

// Dialer returns a function with same signature of net.Dialer.DialContext().
func Dialer(directDialer dialFunc, detourDialer dialFunc) dialFunc {
	return func(ctx context.Context, network, addr string) (
		conn net.Conn, err error,
	) {
		dc := &Conn{dialDetour: detourDialer, network: network, addr: addr}
		if !whitelisted(addr) {
			log.Tracef("Attempting direct connection for %v", addr)
			detector := blockDetector.Load().(*Detector)
			dc.setState(stateInitial)
			// Always try direct connection first. The caller may choose a
			// deadline shorter than the context passed in.
			dc.conn, err = directDialer(ctx, network, addr)
			if err == nil {
				if !detector.DNSPoisoned(dc.conn) {
					log.Tracef("Dial %s to %s succeeded", dc.stateDesc(), addr)
					return dc, nil
				}
				log.Debugf("Dial %s to %s, dns hijacked, try detour", dc.stateDesc(), addr)
				if err := dc.conn.Close(); err != nil {
					log.Debugf("Unable to close connection: %v", err)
				}
			} else if detector.TamperingSuspected(err) {
				log.Debugf("Dial %s to %s failed, try detour: %s", dc.stateDesc(), addr, err)
			} else {
				log.Debugf("Dial %s to %s failed: %s", dc.stateDesc(), addr, err)
				return dc, err
			}
		}
		log.Tracef("Detouring %v", addr)
		// if whitelisted or dial directly failed, try detour
		dc.setState(stateDetour)
		dc.conn, err = dc.dialDetour(ctx, network, addr)
		if err != nil {
			log.Errorf("Dial %s failed: %s", dc.stateDesc(), err)
			return nil, err
		}
		log.Tracef("Dial %s to %s succeeded", dc.stateDesc(), addr)
		if !whitelisted(addr) {
			log.Tracef("Add %s to whitelist", addr)
			AddToWl(dc.addr, false)
		}
		return dc, err
	}
}

// Read() implements the function from net.Conn
func (dc *Conn) Read(b []byte) (n int, err error) {
	if !dc.inState(stateInitial) {
		return dc.followUpRead(b)
	}
	// state will always be settled after first read, safe to clear buffer at end of it
	defer dc.resetLocalBuffer()
	start := time.Now()
	readDeadline := dc.readDeadline()
	if !readDeadline.IsZero() && readDeadline.Sub(start) < 2*firstReadTimeoutToDetour {
		log.Tracef("no time left to test %s, read %s", dc.addr, statesDesc[stateDirect])
		dc.setState(stateDirect)
		return dc.countedRead(b)
	}
	// wait for at most firstReadTimeoutToDetour to read
	if err := dc.getConn().SetReadDeadline(start.Add(firstReadTimeoutToDetour)); err != nil {
		log.Debugf("Unable to set read deadline: %v", err)
	}
	n, err = dc.countedRead(b)
	if err := dc.getConn().SetReadDeadline(readDeadline); err != nil {
		log.Debugf("Unable to set read deadline: %v", err)
	}

	detector := blockDetector.Load().(*Detector)
	if err != nil {
		log.Debugf("Error while read from %s %s: %s", dc.addr, dc.stateDesc(), err)
		if detector.TamperingSuspected(err) {
			// to avoid double submitting, we only resend Idempotent requests
			// but return error directly to application for other requests.
			if dc.isIdempotentRequest() {
				log.Debugf("Detour HTTP GET request to %s", dc.addr)
				return dc.detour(b)
			} else {
				log.Debugf("Not HTTP GET request, add to whitelist")
				AddToWl(dc.addr, false)
			}
		}
		return
	}
	// Hijacked content is usualy encapsulated in one IP packet,
	// so just check it in one read rather than consecutive reads.
	if detector.FakeResponse(b) {
		log.Tracef("Read %d bytes from %s %s, response is hijacked, detour", n, dc.addr, dc.stateDesc())
		return dc.detour(b)
	}
	log.Tracef("Read %d bytes from %s %s, set state to direct", n, dc.addr, dc.stateDesc())
	dc.setState(stateDirect)
	return
}

// followUpRead is called by Read() if a connection's state already settled
func (dc *Conn) followUpRead(b []byte) (n int, err error) {
	detector := blockDetector.Load().(*Detector)
	if n, err = dc.countedRead(b); err != nil {
		if err == io.EOF {
			log.Tracef("Read %d bytes from %s %s, EOF", n, dc.addr, dc.stateDesc())
			return
		}
		log.Tracef("Read from %s %s failed: %s", dc.addr, dc.stateDesc(), err)
		switch {
		case dc.inState(stateDirect) && detector.TamperingSuspected(err):
			// to prevent a slow or unstable site from been treated as blocked,
			// we only check first 4K bytes, which roughly equals to the payload of 3 full packets on Ethernet
			if atomic.LoadInt64(&dc.readBytes) <= 4096 {
				log.Tracef("Seems %s still blocked, add to whitelist so will try detour next time", dc.addr)
				AddToWl(dc.addr, false)
			}
		case dc.inState(stateDetour) && wlTemporarily(dc.addr):
			log.Tracef("Detoured route is not reliable for %s, not whitelist it", dc.addr)
			RemoveFromWl(dc.addr)
		}
		return
	}
	// Hijacked content is usualy encapsulated in one IP packet,
	// so just check it in one read rather than consecutive reads.
	if dc.inState(stateDirect) && detector.FakeResponse(b) {
		log.Tracef("%s still content hijacked, add to whitelist so will try detour next time", dc.addr)
		AddToWl(dc.addr, false)
		return
	}
	log.Tracef("Read %d bytes from %s %s", n, dc.addr, dc.stateDesc())
	return
}

// detour sets up a detoured connection and try read again from it
func (dc *Conn) detour(b []byte) (n int, err error) {
	if err = dc.setupDetour(); err != nil {
		log.Errorf("Error while dialing detoured connection: %s", err)
		return
	}
	if _, err = dc.resend(); err != nil {
		err = fmt.Errorf("Error while resend buffer to %s: %s", dc.addr, err)
		log.Error(err)
		return
	}
	dc.setState(stateDetour)
	if n, err = dc.countedRead(b); err != nil {
		log.Debugf("Read from %s %s still failed: %s", dc.addr, dc.stateDesc(), err)
		return
	}
	log.Tracef("Read %d bytes from %s %s, add to whitelist", n, dc.addr, dc.stateDesc())
	AddToWl(dc.addr, false)
	return
}

func (dc *Conn) resend() (int, error) {
	dc.muLocalBuffer.Lock()
	// we have to hold the lock until bytes written
	// as Buffer.Bytes is subject to change through Buffer.Write()
	defer dc.muLocalBuffer.Unlock()
	b := dc.localBuffer.Bytes()
	if len(b) == 0 {
		return 0, nil
	}
	log.Tracef("Resending %d bytes from local buffer to %s", len(b), dc.addr)
	n, err := dc.getConn().Write(b)
	return n, err
}

func (dc *Conn) setupDetour() error {
	c, err := dc.dialDetour(context.Background(), dc.network, dc.addr)
	if err != nil {
		return err
	}
	log.Tracef("Dialed a new detour connection to %s", dc.addr)
	dc.setConn(c)
	return nil
}

// Write implements the function from net.Conn
func (dc *Conn) Write(b []byte) (n int, err error) {
	if dc.inState(stateInitial) {
		if n, err = dc.writeLocalBuffer(b); err != nil {
			return n, fmt.Errorf("Unable to write local buffer: %s", err)
		}
	}
	if n, err = dc.getConn().Write(b); err != nil {
		log.Debugf("Error while write %d bytes to %s %s: %s", len(b), dc.addr, dc.stateDesc(), err)
		return
	}
	log.Tracef("Wrote %d bytes to %s %s", len(b), dc.addr, dc.stateDesc())
	return
}

// Close implements the function from net.Conn
func (dc *Conn) Close() error {
	log.Tracef("Closing %s connection to %s", dc.stateDesc(), dc.addr)
	if atomic.LoadInt64(&dc.readBytes) > 0 {
		if dc.inState(stateDetour) && wlTemporarily(dc.addr) {
			log.Tracef("no error found till closing, add %s to permanent whitelist", dc.addr)
			AddToWl(dc.addr, true)
		}
	}
	dc.setState(stateClosed)
	conn := dc.getConn()
	if conn == nil {
		return nil
	}
	return conn.Close()
}

// LocalAddr implements the function from net.Conn
func (dc *Conn) LocalAddr() net.Addr {
	return dc.getConn().LocalAddr()
}

// RemoteAddr implements the function from net.Conn
func (dc *Conn) RemoteAddr() net.Addr {
	return dc.getConn().RemoteAddr()
}

// SetDeadline implements the function from net.Conn
func (dc *Conn) SetDeadline(t time.Time) error {
	if err := dc.SetReadDeadline(t); err != nil {
		log.Debugf("Unable to set read deadline: %v", err)
	}
	if err := dc.SetWriteDeadline(t); err != nil {
		log.Debugf("Unable to set write deadline: %v", err)
	}
	return nil
}

// SetReadDeadline implements the function from net.Conn
func (dc *Conn) SetReadDeadline(t time.Time) error {
	dc._readDeadline.Store(t)
	if err := dc.getConn().SetReadDeadline(t); err != nil {
		log.Debugf("Unable to set read deadline: %v", err)
	}
	return nil
}

func (dc *Conn) readDeadline() time.Time {
	d := dc._readDeadline.Load()
	if d == nil {
		return zeroTime
	}
	return d.(time.Time)
}

// SetWriteDeadline implements the function from net.Conn
func (dc *Conn) SetWriteDeadline(t time.Time) error {
	dc._writeDeadline.Store(t)
	if err := dc.getConn().SetWriteDeadline(t); err != nil {
		log.Debugf("Unable to set write deadline", err)
	}
	return nil
}

func (dc *Conn) writeDeadline() time.Time {
	d := dc._writeDeadline.Load()
	if d == nil {
		return zeroTime
	}
	return d.(time.Time)
}

func (dc *Conn) writeLocalBuffer(b []byte) (n int, err error) {
	dc.muLocalBuffer.Lock()
	n, err = dc.localBuffer.Write(b)
	dc.muLocalBuffer.Unlock()
	return
}

func (dc *Conn) resetLocalBuffer() {
	dc.muLocalBuffer.Lock()
	dc.localBuffer.Reset()
	dc.muLocalBuffer.Unlock()
}

var nonIdempotentMethods = [][]byte{
	[]byte("POST "),
	[]byte("PATCH "),
}

// ref section 9.1.2 of https://www.ietf.org/rfc/rfc2616.txt.
// checks against non-idemponent methods actually,
// as we consider the https handshake phase to be idemponent.
func (dc *Conn) isIdempotentRequest() bool {
	dc.muLocalBuffer.Lock()
	defer dc.muLocalBuffer.Unlock()
	b := dc.localBuffer.Bytes()
	if len(b) > 4 {
		for _, m := range nonIdempotentMethods {
			if bytes.HasPrefix(b, m) {
				return false
			}
		}
	}
	return true
}

func (dc *Conn) countedRead(b []byte) (n int, err error) {
	n, err = dc.getConn().Read(b)
	atomic.AddInt64(&dc.readBytes, int64(n))
	return
}

func (dc *Conn) getConn() (c net.Conn) {
	dc.muConn.RLock()
	defer dc.muConn.RUnlock()
	return dc.conn
}

func (dc *Conn) setConn(c net.Conn) {
	dc.muConn.Lock()
	oldConn := dc.conn
	dc.conn = c
	dc.muConn.Unlock()
	if err := dc.conn.SetReadDeadline(dc.readDeadline()); err != nil {
		log.Debugf("Unable to set read deadline: %v", err)
	}
	if err := dc.conn.SetWriteDeadline(dc.writeDeadline()); err != nil {
		log.Debugf("Unable to set write deadline: %v", err)
	}
	log.Tracef("Replaced connection to %s from direct to detour and closing old one", dc.addr)
	if err := oldConn.Close(); err != nil {
		log.Debugf("Unable to close old connection: %v", err)
	}
}

func (dc *Conn) stateDesc() string {
	return statesDesc[atomic.LoadUint32(&dc.state)]
}

func (dc *Conn) inState(s uint32) bool {
	return atomic.LoadUint32(&dc.state) == s
}

func (dc *Conn) setState(s uint32) {
	atomic.StoreUint32(&dc.state, s)
}


text:
module Thinreports
  module Core
    module Shape
      module Base
        # @abstract
        class Internal
          include Utils
          extend  Forwardable

          def self.format_delegators(*args)
            def_delegators :format, *args
          end
          private_class_method :format_delegators

          attr_reader :parent
          attr_reader :format
          attr_writer :style
          attr_accessor :states

          def initialize(parent, format)
            @parent = parent
            @format = format
            @states = {}
            @style = nil

            @finalized_attributes = nil
          end

          def style
            raise NotImplementedError
          end

          def copy(new_parent, &block)
            new_internal = self.class.new(new_parent, format)
            new_internal.style = style.copy
            new_internal.states = deep_copy(states)

            block.call(new_internal) if block_given?
            new_internal
          end

          def type_of?
            raise NotImplementedError
          end
        end
      end
    end
  end
end


text:
namespace formulate.app.Configuration
{
    using System.Collections.Generic;

    using formulate.app.Templates;

    /// <summary>
    /// The formulate config.
    /// </summary>
    internal sealed class FormulateConfig : IFormulateConfig
    {
        /// <summary>
        /// Gets or sets the version.
        /// </summary>
        public string Version { get; set; }

        /// <summary>
        /// Gets or sets the persistence configuration.
        /// </summary>
        public PersistenceConfig Persistence { get; set; }

        /// <summary>
        /// Gets or sets the templates configuration.
        /// </summary>
        public IEnumerable<TemplateConfigItem> Templates { get; set; }

        /// <summary>
        /// Gets or sets the buttons configuration.
        /// </summary>
        public IEnumerable<ButtonConfigItem> Buttons { get; set; }

        /// <summary>
        /// Gets or sets the email configuration.
        /// </summary>
        public EmailConfig Email { get; set; }

        /// <summary>
        /// Gets or sets the submissions configuration.
        /// </summary>
        public SubmissionsConfig Submissions { get; set; }

        /// <summary>
        /// Gets or sets the field categories configuration.
        /// </summary>
        /// <summary>
        /// Gets or sets the field categories in this configuration section.
        /// </summary>
        public IEnumerable<FieldCategoryConfigItem> FieldCategories { get; set; }
    }
}


text:
require 'optparse'
require 'yaml'

module Pmux
  class Application
    OPTS = {}

    def run options=OPTS
      optparser = optparse options
      optparser.parse!
      load_config options
      options[:program_name] = optparser.program_name
      options[:user] ||=
        (ENV['USER'] || ENV['LOGNAME'] || Etc.getlogin || Etc.getpwuid.name)

      root_dir = (options[:root_dir] ||=
                  File.expand_path "~/.#{options[:program_name]}")
      tmp_dir = (options[:tmp_dir] ||= root_dir + '/tmp')
      log_dir = (options[:log_dir] ||= root_dir + '/log')
      [root_dir, tmp_dir, log_dir].each {|dir|
        Dir.mkdir dir unless File.exist? dir
      }

      Plugin.load_plugins unless options[:disable_plugins]
      addrs = (options[:hosts] || '').split(',').map {|host| getaddr host}

      case
      when options[:server]
        (options[:sock_path] ||= '/tmp/.pmuxsock') << ".#{$$}"
        run_server options
      when options[:status]
        show_status addrs, options
      when options[:lookup]
        lookup addrs, options
      when options[:show_joblog]
        show_joblog options
      else
        run_mr addrs, options
      end
    end

    def load_config options
      path = File.expand_path(options[:config_file] || "~/.pmux/config.yml")
      if File.file? path
        conf = YAML.load_file path
        if conf.kind_of? Hash
          for k, v in conf
            options[k.intern] ||= v
          end
        end
      end
    end

    def getaddr host
      sa = Socket.pack_sockaddr_in 0, host
      port, addr = Socket.unpack_sockaddr_in sa
      addr
    end

    def run_server options
      STDOUT.sync = true
      server = MR::Server.new
      handler = Pmux::Handler.new server, options
      pipe_transport = MR::PipeTransport.new STDIN, STDOUT, STDERR
      server.listen pipe_transport, handler
      unix_transport = MR::UNIXServerTransport.new options[:sock_path]
      server.listen unix_transport, handler
      server.run
    rescue SystemCallError
    ensure
      File.unlink options[:sock_path] rescue nil
    end

    alias :putline :puts

    def show_joblog options
      log_dir = options[:log_dir]
      if (job_id = options[:show_joblog]) == true
        joblogs = Dir.glob(log_dir + '/*.yml').map {|path|
          obj = YAML.load_file path
        }
        for h in joblogs.sort_by {|obj| obj[:invoked_at].to_f}
          t = (h[:invoked_at] || h[:start_time]).strftime("%m/%d %H:%M")
          line = format '%-10s %s "%s"', h[:id], t, h[:mapper]
          putline line
        end
      else
        path = File.join log_dir, "#{job_id}.yml"
        els = {}
        open(path) {|io|
          s = YAML.load_stream io
          header, tasks, footer = s[0], s[1], s[2]
          if tasks
            for task_id, task in tasks.sort_by {|k, v| k}
              line = format '%5d %s %g',
                task_id, task['node_addr'], task['welapse']
              putline line
              node_addr = task['node_addr']
              els[node_addr] ||= [0, 0]
              els[node_addr][0] += 1
              els[node_addr][1] += task['welapse']
            end
          end
        }
        putline
        for node_addr, v in els
          putline format '%s %g/%d = %g',
            node_addr, v[1], v[0], v[1] / v[0]
        end
      end
    end

    def show_status addrs, options
      addrs = ['localhost'] if addrs.empty?
      adapter = StorageAdapter.create options[:storage_name], addrs
      msession = MRSession.new addrs, options
      msession.on_error {|addr, err| $stderr.printf "%s: %s\n", addr, err.to_s}
      msession.connect

      mf = msession.multicast_call_async :get_properties
      templ = "%s: %s %s, num_cpu=%s, ruby %s\n"
      mf.on_success {|f|
        props = f.get
        print templ % [props['hostname'],
          props['program_name'], props['VERSION'],
          props['num_cpu'], props['RUBY_VERSION']]
      }
      mf.on_error {|f| printf "%s: ERROR: %s\n", f.addr, f.error}
      mf.join_all

      msession.on_error {}
      mf = msession.multicast_call_async :quit
      mf.join_all
    end

    def lookup addrs, options
      adapter = StorageAdapter.create options[:storage_name], addrs
      name = options[:lookup]
      locator_host = options[:locator_host] || addrs.first || 'localhost'
      locator_port = options[:locator_port]
      adapter.connect_to_storage locator_host, locator_port
      adapter.get_files [name]
      locations = adapter.lookup_file name
      $stderr.puts "name: #{name}"
      for host, path in locations
        $stderr.puts "location: #{host}:#{path}"
      end
    end

    def run_mr addrs, options, argv=ARGV
      invoked_at = Time.now
      if options[:storage_name] == 'local' and addrs.empty?
        addrs = ['localhost']
      end
      adapter = StorageAdapter.create options[:storage_name], addrs, options
      locator_host = options[:locator_host] || addrs.first || 'localhost'
      locator_port = options[:locator_port]

      puts "storage: #{adapter.class}" if options[:verbose]
      begin
        adapter.connect_to_storage locator_host, locator_port
        files = adapter.get_files argv, options[:expand_glob]
      rescue
        STDERR.puts "Storage Error: #{$!}"
        abort
      end
      raise RuntimeError, "no hostname specified" if adapter.addrs.empty?

      msession = MRSession.new adapter.addrs, options
      msession.on_error {|addr, err|
        $stderr.printf "%s: %s\n", addr, err.inspect if err
      }
      msession.connect

      if options[:reducer]
        options[:num_r] ||= 1
      end
      dispatcher = TaskDispatcher.new options, adapter, msession
      job = Job.new options, files
      job[:invoked_at] = invoked_at
      job.mk_reducer_addrs adapter.addrs
      dispatcher.run job
      abort if job.failed
    end

    def optparse opts
      op = OptionParser.new
      op.on('--debug') {$debug = true; STDOUT.sync = true}
      op.on('--server') {opts[:server] = true}
      op.on('--argv=FILES') {}
      op.on('--brick=HOST:/DIR', '-b') {|arg| (opts[:bricks] ||= []).push arg}
      op.on('--config-file=FILE', '-F') {|arg| opts[:config_file] = arg}
      op.on('--disable-plugins') {opts[:disable_plugins] = true}
      op.on('--expand-glob') {opts[:expand_glob] = true}
      op.on('--ff=FF', Integer) {|arg| opts[:ff] = arg}
      op.on('--hosts=HOST,HOST,...') {|arg| opts[:hosts] = arg}
      op.on('--ipaddr=ADDR') {|arg| opts[:ipaddr] = arg}
      op.on('--locator-host=HOST') {|arg| opts[:locator_host] = arg}
      op.on('--locator-port=PORT', Integer) {|arg|
        opts[:locator_port] = arg}
      op.on('--lookup=FILE') {|arg| opts[:lookup] = arg}
      op.on('--mapper=CMD') {|arg| opts[:mapper] = arg}
      op.on('--reducer=CMD') {|arg| opts[:reducer] = arg}
      op.on('--num-r=NUM', Integer) {|arg| opts[:num_r] = arg}
      op.on('--root-dir=DIR') {|arg| opts[:root_dir] = arg}
      op.on('--ship-file=FILE', '--file=FILE') {|arg|
        (opts[:ship_files] ||= []).push arg}
      op.on('--show-joblog [job_id]') {|arg| opts[:show_joblog] = arg || true}
      op.on('--status') {opts[:status] = true}
      op.on('--storage=STORAGE_NAME') {|arg|
        opts[:storage_name] = arg}
      op.on('--verbose') {opts[:verbose] = true}
      op.on('--version') {
        puts "#{op.program_name} #{VERSION}"
        exit
      }
      class <<op
        attr_accessor :options
      end
      op.options = opts
      op
    end
  end
end


text:
#include "ogr_gml.h"
#include "cpl_conv.h"
#include "cpl_multiproc.h"
#include "gmlreaderp.h"

CPL_CVSID("$Id: ogrgmldriver.cpp 29240 2015-05-24 10:58:38Z rouault $");

/************************************************************************/
/*                        OGRGMLDriverUnload()                          */
/************************************************************************/

static void OGRGMLDriverUnload(CPL_UNUSED GDALDriver* poDriver)
{
    if( GMLReader::hMutex != NULL )
        CPLDestroyMutex( GMLReader::hMutex );
    GMLReader::hMutex = NULL;
}

/************************************************************************/
/*                         OGRGMLDriverIdentify()                       */
/************************************************************************/

static int OGRGMLDriverIdentify( GDALOpenInfo* poOpenInfo )

{
    if( poOpenInfo->fpL == NULL )
    {
        if( strstr(poOpenInfo->pszFilename, "xsd=") != NULL )
            return -1; /* must be later checked */
        return FALSE;
    }
    /* Might be a OS-Mastermap gzipped GML, so let be nice and try to open */
    /* it transparently with /vsigzip/ */
    else
    if ( poOpenInfo->pabyHeader[0] == 0x1f && poOpenInfo->pabyHeader[1] == 0x8b &&
         EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "gz") &&
         strncmp(poOpenInfo->pszFilename, "/vsigzip/", strlen("/vsigzip/")) != 0 )
    {
        return -1; /* must be later checked */
    }
    else
    {
        const char* szPtr = (const char*)poOpenInfo->pabyHeader;

        if( ( (unsigned char)szPtr[0] == 0xEF )
            && ( (unsigned char)szPtr[1] == 0xBB )
            && ( (unsigned char)szPtr[2] == 0xBF) )
        {
            szPtr += 3;
        }
/* -------------------------------------------------------------------- */
/*      Here, we expect the opening chevrons of GML tree root element   */
/* -------------------------------------------------------------------- */
        if( szPtr[0] != '<' )
            return FALSE;

        if( !poOpenInfo->TryToIngest(4096) )
            return FALSE;

        return OGRGMLDataSource::CheckHeader((const char*)poOpenInfo->pabyHeader);
    }
}

/************************************************************************/
/*                                Open()                                */
/************************************************************************/

static GDALDataset *OGRGMLDriverOpen( GDALOpenInfo* poOpenInfo )

{
    OGRGMLDataSource    *poDS;

    if( poOpenInfo->eAccess == GA_Update )
        return NULL;

    if( OGRGMLDriverIdentify( poOpenInfo ) == FALSE )
        return NULL;

    poDS = new OGRGMLDataSource();

    if( !poDS->Open(  poOpenInfo ) )
    {
        delete poDS;
        return NULL;
    }
    else
        return poDS;
}

/************************************************************************/
/*                             Create()                                 */
/************************************************************************/

static GDALDataset *OGRGMLDriverCreate( const char * pszName,
                                        CPL_UNUSED int nBands,
                                        CPL_UNUSED int nXSize,
                                        CPL_UNUSED int nYSize,
                                        CPL_UNUSED GDALDataType eDT,
                                        char **papszOptions )
{
    OGRGMLDataSource    *poDS = new OGRGMLDataSource();

    if( !poDS->Create( pszName, papszOptions ) )
    {
        delete poDS;
        return NULL;
    }
    else
        return poDS;
}

/************************************************************************/
/*                           RegisterOGRGML()                           */
/************************************************************************/

void RegisterOGRGML()

{
    GDALDriver  *poDriver;

    if( GDALGetDriverByName( "GML" ) == NULL )
    {
        poDriver = new GDALDriver();

        poDriver->SetDescription( "GML" );
        poDriver->SetMetadataItem( GDAL_DCAP_VECTOR, "YES" );
        poDriver->SetMetadataItem( GDAL_DMD_LONGNAME,
                                   "Geography Markup Language (GML)" );
        poDriver->SetMetadataItem( GDAL_DMD_EXTENSION, "gml" );
        poDriver->SetMetadataItem( GDAL_DMD_EXTENSIONS, "gml xml" );
        poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC,
                                   "drv_gml.html" );

        poDriver->SetMetadataItem( GDAL_DMD_OPENOPTIONLIST,
"<OpenOptionList>"
"  <Option name='XSD' type='string' description='Name of the related application schema file (.xsd).'/>"
"  <Option name='GFS_TEMPLATE' type='string' description='Filename of a .gfs template file to appli.'/>"
"  <Option name='FORCE_SRS_DETECTION' type='boolean' description='Force a full scan to detect the SRS of layers.' default='NO'/>"
"  <Option name='EMPTY_AS_NULL' type='boolean' description='Force empty fields to be reported as NULL. Set to NO so that not-nullable fields can be exposed' default='YES'/>"
"  <Option name='GML_ATTRIBUTES_TO_OGR_FIELDS' type='boolean' description='Whether GML attributes should be reported as OGR fields' default='NO'/>"
"  <Option name='INVERT_AXIS_ORDER_IF_LAT_LONG' type='boolean' description='Whether to present SRS and coordinate ordering in traditional GIS order' default='YES'/>"
"  <Option name='CONSIDER_EPSG_AS_URN' type='string-select' description='Whether to consider srsName like EPSG:XXXX as respecting EPSG axis order' default='AUTO'>"
"    <Value>AUTO</Value>"
"    <Value>YES</Value>"
"    <Value>NO</Value>"
"  </Option>"
"  <Option name='READ_MODE' type='string-select' description='Read mode' default='AUTO'>"
"    <Value>AUTO</Value>"
"    <Value>STANDARD</Value>"
"    <Value>SEQUENTIAL_LAYERS</Value>"
"    <Value>INTERLEAVED_LAYERS</Value>"
"  </Option>"
"  <Option name='EXPOSE_GML_ID' type='string-select' description='Whether to make feature gml:id as a gml_id attribute' default='AUTO'>"
"    <Value>AUTO</Value>"
"    <Value>YES</Value>"
"    <Value>NO</Value>"
"  </Option>"
"  <Option name='EXPOSE_FID' type='string-select' description='Whether to make feature fid as a fid attribute' default='AUTO'>"
"    <Value>AUTO</Value>"
"    <Value>YES</Value>"
"    <Value>NO</Value>"
"  </Option>"
"  <Option name='DOWNLOAD_SCHEMA' type='boolean' description='Whether to download the remote application schema if needed (only for WFS currently)' default='YES'/>"
"  <Option name='REGISTRY' type='string' description='Filename of the registry with application schemas.'/>"
"</OpenOptionList>" );

        poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST,
"<CreationOptionList>"
"  <Option name='XSISCHEMAURI' type='string' description='URI to be inserted as the schema location.'/>"
"  <Option name='XSISCHEMA' type='string-select' description='where to write a .xsd application schema. INTERNAL should not normally be used' default='EXTERNAL'>"
"    <Value>EXTERNAL</Value>"
"    <Value>INTERNAL</Value>"
"    <Value>OFF</Value>"
"  </Option>"
"  <Option name='PREFIX' type='string' description='Prefix for the application target namespace.' default='ogr'/>"
"  <Option name='STRIP_PREFIX' type='boolean' description='Whether to avoid writing the prefix of the application target namespace in the GML file.' default='NO'/>"
"  <Option name='TARGET_NAMESPACE' type='string' description='Application target namespace.' default='http://ogr.maptools.org/'/>"
"  <Option name='FORMAT' type='string-select' description='Version of GML to use' default='GML2'>"
"    <Value>GML2</Value>"
"    <Value>GML3</Value>"
"    <Value>GML3.2</Value>"
"    <Value>GML3Deegree</Value>"
"  </Option>"
"  <Option name='GML3_LONGSRS' type='boolean' description='Whether to write SRS with \"urn:ogc:def:crs:EPSG::\" prefix with GML3* versions' default='YES'/>"
"  <Option name='WRITE_FEATURE_BOUNDED_BY' type='boolean' description='Whether to write <gml:boundedBy> element for each feature with GML3* versions' default='YES'/>"
"  <Option name='SPACE_INDENTATION' type='boolean' description='Whether to indentate the output for readability' default='YES'/>"
"  <Option name='SRSDIMENSION_LOC' type='string-select' description='(only valid for FORMAT=GML3xx) Location where to put srsDimension attribute' default='POSLIST'>"
"    <Value>POSLIST</Value>"
"    <Value>GEOMETRY</Value>"
"    <Value>GEOMETRY,POSLIST</Value>"
"  </Option>"
"  <Option name='GML_ID' type='string' description='Value of feature collection gml:id (GML 3.2 only)' default='aFeatureCollection'/>"
"  <Option name='NAME' type='string' description='Content of GML name element'/>"
"  <Option name='DESCRIPTION' type='string' description='Content of GML description element'/>"
"</CreationOptionList>");

        poDriver->SetMetadataItem( GDAL_DS_LAYER_CREATIONOPTIONLIST, "<LayerCreationOptionList/>");

        poDriver->SetMetadataItem( GDAL_DMD_CREATIONFIELDDATATYPES, "Integer Integer64 Real String Date DateTime IntegerList Integer64List RealList StringList" );
        poDriver->SetMetadataItem( GDAL_DCAP_NOTNULL_FIELDS, "YES" );
        poDriver->SetMetadataItem( GDAL_DCAP_NOTNULL_GEOMFIELDS, "YES" );

        poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" );

        poDriver->pfnOpen = OGRGMLDriverOpen;
        poDriver->pfnIdentify = OGRGMLDriverIdentify;
        poDriver->pfnCreate = OGRGMLDriverCreate;
        poDriver->pfnUnloadDriver = OGRGMLDriverUnload;

        GetGDALDriverManager()->RegisterDriver( poDriver );
    }
}


text:
var React = require('react');

/**
 *
 * BarItem Component
 * @type {BarItem}
 *
 */
var BarItem = React.createClass({
    propTypes: {
        target: React.PropTypes.string.isRequired
    },
    render: function () {
        var className = this.props.currentTarget === this.props.target ? 'active' : '';
        return (

                    {this.props.children}

        );
    },
    onClick: function (event) {
        event.preventDefault();
        this.props.onClickCallback(this.props.target); // inform parent that a navbar item was clicked!
    }
});

module.exports = BarItem;


text:
using System;
using System.Collections.Generic;

using platform;
using account.core;

namespace weibo.core
{
    public class StatusService : PropertyId<StatusOption>
    {
        public StatusCreateC _createStatus(StatusCreateS nStatusCreateS)
        {
            StatusCreateC result_ = new StatusCreateC();
            result_.m_tId = nStatusCreateS.m_tId;
            AccountService accountService_ = __singleton<AccountService>._instance();
            Account account_ = accountService_._getAccount(nStatusCreateS.m_tAccount);
            if (null != account_)
            {
                uint propertyId_ = PropertyId<StatusMgr>._classId();
                StatusMgr statusMgr_ = account_._getProperty<StatusMgr>(propertyId_);
                statusMgr_._createStatus(account_, nStatusCreateS, result_);
            }
            else
            {
                result_.m_tErrorCode = StatusError_.mAccount_;
            }
            return result_;
        }

        public StatusGetC _getStatus(StatusGetS nStatusGetS)
        {
            StatusGetC result_ = new StatusGetC();
            AccountService accountService_ = __singleton<AccountService>._instance();
            Account account_ = accountService_._getAccount(nStatusGetS.m_tAccountGet);
            if (null == account_)
            {
                result_.m_tErrorCode = StatusError_.mAccount_;
                return result_;
            }
            if ((nStatusGetS.m_tPlayer == nStatusGetS.m_tAccountGet.m_tName) || (null == nStatusGetS.m_tPlayer))
            {
                this._getStatus(result_, account_, nStatusGetS.m_tTicks);
            }
            else
            {
                this._getStatus(result_, nStatusGetS.m_tPlayer, nStatusGetS.m_tTicks, (uint)nStatusGetS.m_tServer);
            }
            return result_;
        }

        void _getStatus(StatusGetC nStatusGetC, Account nAccount, long nTicks)
        {
            AccountMgr accountMgr_ = nAccount._getAccountMgr();
            uint accountMgrId_ = accountMgr_._getId();
            uint accountId_ = nAccount._getId();
            uint propertyId_ = PropertyId<StatusMgr>._classId();
            StatusMgr statusMgr_ = nAccount._getProperty<StatusMgr>(propertyId_);
            if (statusMgr_._getTicks() == nTicks)
            {
                nStatusGetC.m_tErrorCode = StatusError_.mSucessTicks_;
                return;
            }
            statusMgr_._getStatus(nStatusGetC, nTicks, accountMgrId_, accountId_);
        }

        void _getStatus(StatusGetC nStatusGetC, string nAccountName, long nTicks, uint nServer)
        {
            SettingService settingService_ = __singleton<SettingService>._instance();
            if (!settingService_._checkServerId(nServer))
            {
                nStatusGetC.m_tErrorCode = StatusError_.mServerId_;
                return;
            }
            AccountService accountService_ = __singleton<AccountService>._instance();
            Account account_ = accountService_._getAccount(nAccountName);
            if (null != account_)
            {
                this._getStatus(nStatusGetC, account_, nTicks);
            }
            else
            {
                this._getStatus(nStatusGetC, nAccountName, nTicks);
            }
        }

        void _getStatus(StatusGetC nStatusGetC, string nAccountName, long nTicks)
        {
            AccountService accountService_ = __singleton<AccountService>._instance();
            uint accountMgrId_ = default(uint);
            uint accountId_ = default(uint);
            accountService_._getAccountInfo(out accountMgrId_, out accountId_, nAccountName);
            StatusMgr statusMgr_ = new StatusMgr();
            statusMgr_._runAccountLogin(accountMgrId_, accountId_);
            statusMgr_._getStatus(nStatusGetC, nTicks, accountMgrId_, accountId_);
        }

        public void _runInit()
        {
            InitService initService_ = __singleton<InitService>._instance();
            initService_.m_tRunSave += this._saveStatusOption;
        }

        public void _runStart()
        {
            this._startStatusOption();
        }

        void _startStatusOption()
        {
            SqlCommand sqlCommand_ = new SqlCommand();
            StatusOptionSelectB statusOptionSelectB_ = new StatusOptionSelectB();
            sqlCommand_._addHeadstream(statusOptionSelectB_);
            SqlService sqlService_ = __singleton<SqlService>._instance();
            if (sqlService_._runSqlCommand(sqlCommand_, statusOptionSelectB_))
            {
                statusOptionSelectB_._runInit();
            }
        }

        void _saveStatusOption()
        {
            SqlCommand sqlCommand_ = new SqlCommand();
            StatusOptionInsertB statusOptionInsertB_ = new StatusOptionInsertB();
            statusOptionInsertB_._runInit();
            sqlCommand_._addHeadstream(statusOptionInsertB_);
            SqlService sqlService_ = __singleton<SqlService>._instance();
            sqlService_._runSqlCommand(sqlCommand_);
        }
    }
}


text:
import axios from 'axios'
import React, { Component } from 'react'
import Board from './board'

// TODO: Will I be needing this? :thinking_face:
class BoardContainer extends Component {
  constructor(props){
    super(props)
  }

  render() {
    return <Board />
  }
}

export default BoardContainer


text:
This release primary brings the replacement of the dashboard with the narratives web app.

Internally, we've completed the migration from travis-ci to github actions, and fixed a few minor bugs.

## CHANGES

### NEW

dashboard: The dashboard plugin now redirects to /narratives

### REMOVED

dashboard: old dashboard plugin removed (rip 2014-2021).

### UNRELEASED

iteration on ontology, taxonomy, sample, sample set landing pages

### IMPROVEMENTS

Finish migration from travis-ci to github actions

### FIXES

- catalog: fix help links to point to new documentation site

### MAJOR DEPENDENCY CHANGES

none


text:
<!DOCTYPE html>
<html>
<head>
    <title>GH-4793</title>
</head>
<body>
<iframe id="cross-domain-iframe" src="http://localhost:3001/fixtures/regression/gh-4793/pages/iframe.html"></iframe>
</body>
</html>


text:
Features

What makes our Refiner Discs special?

Variable rib design

Refiner disc's life is upto
250 to 300 hours

Creates long fibres which
strengthen the paper

High savings on energy

Disc rotors plate are
dynamically balanced

Wide range to choice
of patterns

Keep your cost down

Improved pulp strength and
increased refining capacity

Increases the tensile
strength of paper

Free On-site Support

Free Engineering
Consultancy

Custom Discs for your
requirements