text:
package admin

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/exposure-notifications-server/internal/project"
	"github.com/google/exposure-notifications-server/internal/verification/database"
	"github.com/google/exposure-notifications-server/internal/verification/model"
)

// HandleHealthAuthoritySave handles the create/update actions for health
// authorities.
func (s *Server) HandleHealthAuthoritySave() func(c *gin.Context) {
	return func(c *gin.Context) {
		var form healthAuthorityFormData
		err := c.Bind(&form)
		if err != nil {
			ErrorPage(c, err.Error())
			return
		}

		ctx := c.Request.Context()
		m := TemplateMap{}

		haDB := database.New(s.env.Database())
		healthAuthority := &model.HealthAuthority{}
		haID, err := strconv.ParseInt(c.Param("id"), 10, 64)
		if err != nil {
			ErrorPage(c, fmt.Sprintf("failed to parse %q as int: %v", c.Param("id"), err))
			return
		}
		if haID != 0 {
			healthAuthority, err = haDB.GetHealthAuthorityByID(ctx, haID)
			if err != nil {
				ErrorPage(c, fmt.Sprintf("error processing health authority: %v", err))
				return
			}
		}
		form.PopulateHealthAuthority(healthAuthority)

		// Decide if update or insert.
		updateFn := haDB.AddHealthAuthority
		if haID != 0 {
			updateFn = haDB.UpdateHealthAuthority
		}
		if err := updateFn(ctx, healthAuthority); err != nil {
			ErrorPage(c, fmt.Sprintf("Error writing health authority: %v", err))
			return
		}

		m.AddSuccess(fmt.Sprintf("Updated Health Authority '%v'", healthAuthority.Issuer))
		c.Redirect(http.StatusSeeOther, fmt.Sprintf("/healthauthority/%d", healthAuthority.ID))
		c.Abort()
	}
}

// HandleHealthAuthorityShow handles the show action for health authorities.
func (s *Server) HandleHealthAuthorityShow() func(c *gin.Context) {
	return func(c *gin.Context) {
		ctx := c.Request.Context()
		m := TemplateMap{}

		healthAuthority := &model.HealthAuthority{
			EnableStatsAPI: true, // default enabled.
		}
		if IDParam := c.Param("id"); IDParam == "0" {
			m["new"] = true
		} else {
			haID, err := strconv.ParseInt(IDParam, 10, 64)
			if err != nil {
				ErrorPage(c, "Unable to parse `id` param.")
				return
			}

			haDB := database.New(s.env.Database())
			healthAuthority, err = haDB.GetHealthAuthorityByID(ctx, haID)
			if err != nil {
				ErrorPage(c, fmt.Sprintf("Unable to find requested health authority: %v. Error: %v", haID, err))
				return
			}
		}
		m["ha"] = healthAuthority
		m["hak"] = &model.HealthAuthorityKey{From: time.Now()} // For create form.
		c.HTML(http.StatusOK, "healthauthority", m)
	}
}

// HandleHealthAuthorityKeys handles the keys action for health authorities.
func (s *Server) HandleHealthAuthorityKeys() func(c *gin.Context) {
	return func(c *gin.Context) {
		ctx := c.Request.Context()

		haDB := database.New(s.env.Database())
		haID, err := strconv.ParseInt(c.Param("id"), 10, 64)
		if err != nil {
			ErrorPage(c, "Unable to parse `id` param")
			return
		}
		healthAuthority, err := haDB.GetHealthAuthorityByID(ctx, haID)
		if err != nil {
			ErrorPage(c, fmt.Sprintf("error processing health authority: %v", err))
			return
		}

		if action := c.Param("action"); action == "create" {
			var form keyhealthAuthorityFormData
			err := c.Bind(&form)
			if err != nil {
				ErrorPage(c, err.Error())
				return
			}

			var hak model.HealthAuthorityKey
			err = form.PopulateHealthAuthorityKey(&hak)
			if err != nil {
				ErrorPage(c, fmt.Sprintf("Error parsing new health authority key: %v", err))
				return
			}
			err = haDB.AddHealthAuthorityKey(ctx, healthAuthority, &hak)
			if err != nil {
				ErrorPage(c, fmt.Sprintf("Error saving health authority key: %v", err))
				return
			}
		} else if action == "revoke" || action == "reinstate" || action == "activate" {
			version := c.Param("version")

			// find the key.
			var hak *model.HealthAuthorityKey
			for _, key := range healthAuthority.Keys {
				if key.Version == version {
					hak = key
					break
				}
			}
			if hak == nil {
				ErrorPage(c, "Invalid key specified")
				return
			}

			if action == "activate" {
				if hak.IsFuture() {
					hak.From = time.Now()
				}
			} else if action == "revoke" {
				hak.Revoke()
			} else {
				hak.Thru = time.Time{}
			}

			err = haDB.UpdateHealthAuthorityKey(ctx, hak)
			if err != nil {
				ErrorPage(c, fmt.Sprintf("Error saving health authority key: %v", err))
				return
			}
		} else {
			ErrorPage(c, "invalid action")
			return
		}

		c.Redirect(http.StatusSeeOther, fmt.Sprintf("/healthauthority/%d", healthAuthority.ID))
		c.Abort()
	}
}

type healthAuthorityFormData struct {
	Issuer         string `form:"issuer"`
	Audience       string `form:"audience"`
	Name           string `form:"name"`
	EnableStatsAPI bool   `form:"enable-stats-api"`
	JwksURI        string `form:"jwks-uri"`
}

func (f *healthAuthorityFormData) PopulateHealthAuthority(ha *model.HealthAuthority) {
	ha.Issuer = f.Issuer
	ha.Audience = f.Audience
	ha.Name = f.Name
	ha.EnableStatsAPI = f.EnableStatsAPI
	ha.SetJWKS(f.JwksURI)
}

type keyhealthAuthorityFormData struct {
	Version  string `form:"version"`
	PEMBlock string `form:"public-key-pem"`
	FromDate string `form:"from-date"`
	FromTime string `form:"from-time"`
	ThruDate string `form:"thru-date"`
	ThruTime string `form:"thru-time"`
}

func (f *keyhealthAuthorityFormData) FromTimestamp() (time.Time, error) {
	return CombineDateAndTime(f.FromDate, f.FromTime)
}

func (f *keyhealthAuthorityFormData) ThruTimestamp() (time.Time, error) {
	return CombineDateAndTime(f.ThruDate, f.ThruTime)
}

func (f *keyhealthAuthorityFormData) PopulateHealthAuthorityKey(hak *model.HealthAuthorityKey) error {
	fTime, err := f.FromTimestamp()
	if err != nil {
		return fmt.Errorf("invalid from timestamp: %w", err)
	}
	tTime, err := f.ThruTimestamp()
	if err != nil {
		return fmt.Errorf("invalid thru timestamp: %w", err)
	}
	hak.Version = project.TrimSpaceAndNonPrintable(f.Version)
	hak.From = fTime
	hak.Thru = tTime
	hak.PublicKeyPEM = strings.ReplaceAll(project.TrimSpaceAndNonPrintable(f.PEMBlock), "\r", "")

	_, err = hak.PublicKey()
	return err
}


text:
<?php

/**
 * @task lease      Lease Acquisition
 * @task resource   Resource Allocation
 * @task log        Logging
 */
abstract class DrydockBlueprint {

  private $activeResource;
  private $activeLease;

  abstract public function getType();
  abstract public function getInterface(
    DrydockResource $resource,
    DrydockLease $lease,
    $type);

  abstract public function isEnabled();

  public function getBlueprintClass() {
    return get_class($this);
  }

  protected function loadLease($lease_id) {
    $query = id(new DrydockLeaseQuery())
      ->withIDs(array($lease_id))
      ->needResources(true)
      ->execute();

    $lease = idx($query, $lease_id);

    if (!$lease) {
      throw new Exception("No such lease '{$lease_id}'!");
    }

    return $lease;
  }

/* -(  Lease Acquisition  )-------------------------------------------------- */

  /**
   * @task lease
   */
  final public function filterResource(
    DrydockResource $resource,
    DrydockLease $lease) {

    $scope = $this->pushActiveScope($resource, $lease);

    return $this->canAllocateLease($resource, $lease);
  }

  /**
   * Enforce basic checks on lease/resource compatibility. Allows resources to
   * reject leases if they are incompatible, even if the resource types match.
   *
   * For example, if a resource represents a 32-bit host, this method might
   * reject leases that need a 64-bit host. If a resource represents a working
   * copy of repository "X", this method might reject leases which need a
   * working copy of repository "Y". Generally, although the main types of
   * a lease and resource may match (e.g., both "host"), it may not actually be
   * possible to satisfy the lease with a specific resource.
   *
   * This method generally should not enforce limits or perform capacity
   * checks. Perform those in @{method:shouldAllocateLease} instead. It also
   * should not perform actual acquisition of the lease; perform that in
   * @{method:executeAcquireLease} instead.
   *
   * @param   DrydockResource   Candidiate resource to allocate the lease on.
   * @param   DrydockLease      Pending lease that wants to allocate here.
   * @return  bool              True if the resource and lease are compatible.
   * @task lease
   */
  abstract protected function canAllocateLease(
    DrydockResource $resource,
    DrydockLease $lease);

  /**
   * @task lease
   */
  final public function allocateLease(
    DrydockResource $resource,
    DrydockLease $lease) {

    $scope = $this->pushActiveScope($resource, $lease);

    $this->log('Trying to Allocate Lease');

    $lease->setStatus(DrydockLeaseStatus::STATUS_ACQUIRING);
    $lease->setResourceID($resource->getID());
    $lease->attachResource($resource);

    $ephemeral_lease = id(clone $lease)->makeEphemeral();

    $allocated = false;
    $allocation_exception = null;

    $resource->openTransaction();
      $resource->beginReadLocking();
        $resource->reload();

        $other_leases = id(new DrydockLease())->loadAllWhere(
          'status IN (%Ld) AND resourceID = %d',
          array(
            DrydockLeaseStatus::STATUS_ACQUIRING,
            DrydockLeaseStatus::STATUS_ACTIVE,
          ),
          $resource->getID());

        try {
          $allocated = $this->shouldAllocateLease(
            $resource,
            $ephemeral_lease,
            $other_leases);
        } catch (Exception $ex) {
          $allocation_exception = $ex;
        }

        if ($allocated) {
          $lease->save();
        }
      $resource->endReadLocking();
    if ($allocated) {
      $resource->saveTransaction();
      $this->log('Allocated Lease');
    } else {
      $resource->killTransaction();
      $this->log('Failed to Allocate Lease');
    }

    if ($allocation_exception) {
      $this->logException($allocation_exception);
    }

    return $allocated;
  }

  /**
   * Enforce lease limits on resources. Allows resources to reject leases if
   * they would become over-allocated by accepting them.
   *
   * For example, if a resource represents disk space, this method might check
   * how much space the lease is asking for (say, 200MB) and how much space is
   * left unallocated on the resource. It could grant the lease (return true)
   * if it has enough remaining space (more than 200MB), and reject the lease
   * (return false) if it does not (less than 200MB).
   *
   * A resource might also allow only exclusive leases. In this case it could
   * accept a new lease (return true) if there are no active leases, or reject
   * the new lease (return false) if there any other leases.
   *
   * A lock is held on the resource while this method executes to prevent
   * multiple processes from allocating leases on the resource simultaneously.
   * However, this means you should implement the method as cheaply as possible.
   * In particular, do not perform any actual acquisition or setup in this
   * method.
   *
   * If allocation is permitted, the lease will be moved to `ACQUIRING` status
   * and @{method:executeAcquireLease} will be called to actually perform
   * acquisition.
   *
   * General compatibility checks unrelated to resource limits and capacity are
   * better implemented in @{method:canAllocateLease}, which serves as a
   * cheap filter before lock acquisition.
   *
   * @param   DrydockResource     Candidate resource to allocate the lease on.
   * @param   DrydockLease        Pending lease that wants to allocate here.
   * @param   list<DrydockLease>  Other allocated and acquired leases on the
   *                              resource. The implementation can inspect them
   *                              to verify it can safely add the new lease.
   * @return  bool                True to allocate the lease on the resource;
   *                              false to reject it.
   * @task lease
   */
  abstract protected function shouldAllocateLease(
    DrydockResource $resource,
    DrydockLease $lease,
    array $other_leases);

  /**
   * @task lease
   */
  final public function acquireLease(
    DrydockResource $resource,
    DrydockLease $lease) {

    $scope = $this->pushActiveScope($resource, $lease);

    $this->log('Acquiring Lease');
    $lease->setStatus(DrydockLeaseStatus::STATUS_ACTIVE);
    $lease->setResourceID($resource->getID());
    $lease->attachResource($resource);

    $ephemeral_lease = id(clone $lease)->makeEphemeral();

    try {
      $this->executeAcquireLease($resource, $ephemeral_lease);
    } catch (Exception $ex) {
      $this->logException($ex);
      throw $ex;
    }

    $lease->setAttributes($ephemeral_lease->getAttributes());
    $lease->save();
    $this->log('Acquired Lease');
  }

  /**
   * Acquire and activate an allocated lease. Allows resources to peform setup
   * as leases are brought online.
   *
   * Following a successful call to @{method:canAllocateLease}, a lease is moved
   * to `ACQUIRING` status and this method is called after resource locks are
   * released. Nothing is locked while this method executes; the implementation
   * is free to perform expensive operations like writing files and directories,
   * executing commands, etc.
   *
   * After this method executes, the lease status is moved to `ACTIVE` and the
   * original leasee may access it.
   *
   * If acquisition fails, throw an exception.
   *
   * @param   DrydockResource   Resource to acquire a lease on.
   * @param   DrydockLease      Lease to acquire.
   * @return  void
   */
  abstract protected function executeAcquireLease(
    DrydockResource $resource,
    DrydockLease $lease);

  final public function releaseLease(
    DrydockResource $resource,
    DrydockLease $lease) {
    $scope = $this->pushActiveScope(null, $lease);

    $released = false;

    $lease->openTransaction();
      $lease->beginReadLocking();
        $lease->reload();

        if ($lease->getStatus() == DrydockLeaseStatus::STATUS_ACTIVE) {
          $lease->setStatus(DrydockLeaseStatus::STATUS_RELEASED);
          $lease->save();
          $released = true;
        }

      $lease->endReadLocking();
    $lease->saveTransaction();

    if (!$released) {
      throw new Exception("Unable to release lease: lease not active!");
    }

  }

/* -(  Resource Allocation  )------------------------------------------------ */

  public function canAllocateMoreResources(array $pool) {
    return true;
  }

  abstract protected function executeAllocateResource(DrydockLease $lease);

  final public function allocateResource(DrydockLease $lease) {
    $scope = $this->pushActiveScope(null, $lease);

    $this->log(
      pht(
        "Blueprint '%s': Allocating Resource for '%s'",
        $this->getBlueprintClass(),
        $lease->getLeaseName()));

    try {
      $resource = $this->executeAllocateResource($lease);
      $this->validateAllocatedResource($resource);
    } catch (Exception $ex) {
      $this->logException($ex);
      throw $ex;
    }

    return $resource;
  }

/* -(  Logging  )------------------------------------------------------------ */

  /**
   * @task log
   */
  protected function logException(Exception $ex) {
    $this->log($ex->getMessage());
  }

  /**
   * @task log
   */
  protected function log($message) {
    self::writeLog(
      $this->activeResource,
      $this->activeLease,
      $message);
  }

  /**
   * @task log
   */
  public static function writeLog(
    DrydockResource $resource = null,
    DrydockLease $lease = null,
    $message) {

    $log = id(new DrydockLog())
      ->setEpoch(time())
      ->setMessage($message);

    if ($resource) {
      $log->setResourceID($resource->getID());
    }

    if ($lease) {
      $log->setLeaseID($lease->getID());
    }

    $log->save();
  }

  public static function getAllBlueprints() {
    static $list = null;

    if ($list === null) {
      $blueprints = id(new PhutilSymbolLoader())
        ->setType('class')
        ->setAncestorClass('DrydockBlueprint')
        ->setConcreteOnly(true)
        ->selectAndLoadSymbols();
      $list = ipull($blueprints, 'name', 'name');
      foreach ($list as $class_name => $ignored) {
        $list[$class_name] = newv($class_name, array());
      }
    }

    return $list;
  }

  public static function getAllBlueprintsForResource($type) {
    static $groups = null;
    if ($groups === null) {
      $groups = mgroup(self::getAllBlueprints(), 'getType');
    }
    return idx($groups, $type, array());
  }

  protected function newResourceTemplate($name) {
    $resource = new DrydockResource();
    $resource->setBlueprintClass($this->getBlueprintClass());
    $resource->setType($this->getType());
    $resource->setStatus(DrydockResourceStatus::STATUS_PENDING);
    $resource->setName($name);
    $resource->save();

    $this->activeResource = $resource;

    $this->log(
      pht(
        "Blueprint '%s': Created New Template",
        $this->getBlueprintClass()));

    return $resource;
  }

  /**
   * Sanity checks that the blueprint is implemented properly.
   */
  private function validateAllocatedResource($resource) {
    $blueprint = $this->getBlueprintClass();

    if (!($resource instanceof DrydockResource)) {
      throw new Exception(
        "Blueprint '{$blueprint}' is not properly implemented: ".
        "executeAllocateResource() must return an object of type ".
        "DrydockResource or throw, but returned something else.");
    }

    $current_status = $resource->getStatus();
    $req_status = DrydockResourceStatus::STATUS_OPEN;
    if ($current_status != $req_status) {
      $current_name = DrydockResourceStatus::getNameForStatus($current_status);
      $req_name = DrydockResourceStatus::getNameForStatus($req_status);
      throw new Exception(
        "Blueprint '{$blueprint}' is not properly implemented: ".
        "executeAllocateResource() must return a DrydockResource with ".
        "status '{$req_name}', but returned one with status ".
        "'{$current_name}'.");
    }
  }

  private function pushActiveScope(
    DrydockResource $resource = null,
    DrydockLease $lease = null) {

    if (($this->activeResource !== null) ||
        ($this->activeLease !== null)) {
      throw new Exception("There is already an active resource or lease!");
    }

    $this->activeResource = $resource;
    $this->activeLease = $lease;

    return new DrydockBlueprintScopeGuard($this);
  }

  public function popActiveScope() {
    $this->activeResource = null;
    $this->activeLease = null;
  }

}

redpajama_set_name: RedPajamaGithub


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

namespace stubbles\peer\http;
use PHPUnit\Framework\TestCase;

use function bovigo\assert\assertTrue;
use function stubbles\values\value;
/**
 * Checks integration with stubbles/values.
 *
 * @group  peer
 * @group  peer_http
 */
class ValueTest extends TestCase
{
    /**
     * @test
     */
    public function valueCanBeValidatedAsHttpUri(): void
    {
        assertTrue(value('http://example.net/')->isHttpUri());
    }

    /**
     * @test
     */
    public function valueCanBeValidatedAsExistingHttpUri(): void
    {
        assertTrue(value('http://localhost/')->isExistingHttpUri());
    }
}


text:
describe "NumberHelper" do
  class TestClassWithInstanceNumberHelpers
    include MotionSupport::NumberHelper
  end

  class TestClassWithClassNumberHelpers
    extend MotionSupport::NumberHelper
  end

  before do
    @instance_with_helpers = TestClassWithInstanceNumberHelpers.new
  end

  describe "number_to_phone" do
    it "should convert number to phone" do
      [@instance_with_helpers, TestClassWithClassNumberHelpers, MotionSupport::NumberHelper].each do |number_helper|
        number_helper.number_to_phone(5551234).should == "555-1234"
        number_helper.number_to_phone(8005551212).should == "800-555-1212"
        number_helper.number_to_phone(8005551212, {:area_code => true}).should == "(800) 555-1212"
        number_helper.number_to_phone("", {:area_code => true}).should == ""
        number_helper.number_to_phone(8005551212, {:delimiter => " "}).should == "800 555 1212"
        number_helper.number_to_phone(8005551212, {:area_code => true, :extension => 123}).should == "(800) 555-1212 x 123"
        number_helper.number_to_phone(8005551212, :extension => "  ").should == "800-555-1212"
        number_helper.number_to_phone(5551212, :delimiter => '.').should == "555.1212"
        number_helper.number_to_phone("8005551212").should == "800-555-1212"
        number_helper.number_to_phone(8005551212, :country_code => 1).should == "+1-800-555-1212"
        number_helper.number_to_phone(8005551212, :country_code => 1, :delimiter => '').should == "+18005551212"
        number_helper.number_to_phone(225551212).should == "22-555-1212"
        number_helper.number_to_phone(225551212, :country_code => 45).should == "+45-22-555-1212"
      end
    end

    it "should return nil when given nil" do
      [@instance_with_helpers, TestClassWithClassNumberHelpers, MotionSupport::NumberHelper].each do |number_helper|
        number_helper.number_to_phone(nil).should.be.nil
      end
    end

    it "should not mutate options hash" do
      [@instance_with_helpers, TestClassWithClassNumberHelpers, MotionSupport::NumberHelper].each do |number_helper|
        options = { 'raise' => true }

        number_helper.number_to_phone(1, options)
        options.should == { 'raise' => true }
      end
    end

    it "should return non-numeric parameter unchanged" do
      [@instance_with_helpers, TestClassWithClassNumberHelpers, MotionSupport::NumberHelper].each do |number_helper|
        number_helper.number_to_phone("x", :country_code => 1, :extension => 123).should == "+1-x x 123"
        number_helper.number_to_phone("x").should == "x"
      end
    end
  end
end


text:
..
    pysqlw documentation master file, created by
    sphinx-quickstart on Wed Jan 16 23:21:28 2013.
    You can adapt this file completely to your liking, but it should at least
    contain the root `toctree` directive.

Welcome to pysqlw's documentation!
==================================

pysqlw is a wrapping library for Python to make creating and executing SQL queries a breeze.

Documentation
-------------

.. toctree::
    :maxdepth: 2

    usage
    wrappers


text:
using LibrarySystem.Commands.Functional;
using LibrarySystem.Repositories.Contracts.Data;

using Moq;
using NUnit.Framework;

namespace LibrarySystem.Commands.UnitTests.FunctionalTests.ClientGetBookCommandTests
{
    [TestFixture]
    public class Constructor_Should
    {
        [Test]
        [Category("Commands.Functional.ClientExitLibrary.Constructor")]
        public void CreateInstanceOfClientExitLibraryCommandClass_WhenValidArgumentsArePassed()
        {
            //Arrange
            var clientRepositoryStub = new Mock<IClientRepository>();
            var clientExitLibraryCommand = new ClientExitLibraryCommand(clientRepositoryStub.Object);
            //Act
            //Assert
            Assert.That(clientExitLibraryCommand, Is.InstanceOf<ClientExitLibraryCommand>());
        }
    }
}


text:
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import AssetPickerHeader from '../AssetPickerHeader';

describe('<AssetPickerHeader />', () => {
    it('should be able to be instantiated', () => {
        expect(() => <AssetPickerHeader />).to.not.throw();
    });

    it('should show submarket always', () => {
        const wrapper = shallow(<AssetPickerHeader submarket="some-submarket" />);
        expect(wrapper.text()).to.contain('some-submarket');
    });

    it('should show market if showMarket is true', () => {
        const wrapper = shallow(<AssetPickerHeader market="some-market" showMarket />);
        expect(wrapper.text()).to.contain('some-market');
    });
});


text:
// Write a recursive program for generating and printing all ordered k-element subsets from n-element set(variations Vkn).
// Example: n=3, k=2, set = {hi, a, b} → (hi hi), (hi a), (hi b), (a hi), (a a), (a b), (b hi), (b a), (b b)

namespace AllOrderedKsubsetsFromNElements
{
    using System;
    using System.Linq;

    public class AllOrderedKsubsetsFromNElements
    {
        public static void Main()
        {
            Console.WriteLine("Please enter number n:");
            int n = int.Parse(Console.ReadLine());

            Console.WriteLine("Please enter number k:");
            int k = int.Parse(Console.ReadLine());

            Console.WriteLine("Please enter string subsets from n-element, separated by comma:");
            string input = Console.ReadLine();
            string[] set = new string[n];
            set = input.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);

            if (!(0 < k && k <= n) || set.Length != n)
            {
                throw new Exception("Invalid input!");
            }

            int index = 0;
            int[] variation = new int[k];
            FindVariations(index, n, k, variation, set);
        }

        private static void FindVariations(int index, int n, int k, int[] variation, string[] set)
        {
            if (index == k)
            {
                Console.WriteLine("({0})", string.Join(", ", variation.Select(x => set[x])));
                return;
            }

            for (int i = 0; i < n; i++)
            {
                variation[index] = i;
                FindVariations(index + 1, n, k, variation, set);
            }
        }
    }
}


text:
const ratatoskr = require("./ratatoskr")();

function startServer() {
    ratatoskr.start();
}

function handleShutdown() {
    ratatoskr.stop().then(() => process.exit(0));
}

process.on("SIGTERM", handleShutdown);
process.on("SIGINT", handleShutdown);

startServer();


text:
/* include other h files */
#include "arch.h"
#include "parse.h"
#include "os_calls.h"
#include "defines.h"
#include "xrdp_rail.h"
#include "xrdp_client_info.h"
#include "xrdp_constants.h"

/* this is the freerdp main header */
#include <freerdp/freerdp.h>
#include <freerdp/rail.h>
#include <freerdp/rail/rail.h>
#include <freerdp/codec/bitmap.h>
//#include <freerdp/utils/memory.h>
//#include "/home/jay/git/jsorg71/staging/include/freerdp/freerdp.h"

struct bitmap_item
{
    int width;
    int height;
    char *data;
};

struct brush_item
{
    int bpp;
    int width;
    int height;
    char *data;
    char b8x8[8];
};

struct pointer_item
{
    int hotx;
    int hoty;
    char data[32 * 32 * 4];
    char mask[32 * 32 / 8];
    int bpp;
};

#define CURRENT_MOD_VER 4

struct source_info;

struct kbd_overrides
{
    int type;
    int subtype;
    int fn_keys;
    int layout;
    int layout_mask;
};

struct mod
{
    int size; /* size of this struct */
    int version; /* internal version */
    /* client functions */
    int (*mod_start)(struct mod *v, int w, int h, int bpp);
    int (*mod_connect)(struct mod *v);
    int (*mod_event)(struct mod *v, int msg, long param1, long param2,
                     long param3, long param4);
    int (*mod_signal)(struct mod *v);
    int (*mod_end)(struct mod *v);
    int (*mod_set_param)(struct mod *v, const char *name, const char *value);
    int (*mod_session_change)(struct mod *v, int, int);
    int (*mod_get_wait_objs)(struct mod *v, tbus *read_objs, int *rcount,
                             tbus *write_objs, int *wcount, int *timeout);
    int (*mod_check_wait_objs)(struct mod *v);
    int (*mod_frame_ack)(struct mod *mod, int flags, int frame_id);
    int (*mod_suppress_output)(struct mod *mod, int suppress,
                               int left, int top, int right, int bottom);
    int (*mod_server_monitor_resize)(struct mod *mod,
                                     int width, int height);
    int (*mod_server_monitor_full_invalidate)(struct mod *mod,
            int width, int height);
    int (*mod_server_version_message)(struct mod *mod);
    tintptr mod_dumby[100 - 14]; /* align, 100 minus the number of mod
                                 functions above */
    /* server functions */
    int (*server_begin_update)(struct mod *v);
    int (*server_end_update)(struct mod *v);
    int (*server_fill_rect)(struct mod *v, int x, int y, int cx, int cy);
    int (*server_screen_blt)(struct mod *v, int x, int y, int cx, int cy,
                             int srcx, int srcy);
    int (*server_paint_rect)(struct mod *v, int x, int y, int cx, int cy,
                             char *data, int width, int height, int srcx, int srcy);
    int (*server_set_pointer)(struct mod *v, int x, int y, char *data, char *mask);
    int (*server_palette)(struct mod *v, int *palette);
    int (*server_msg)(struct mod *v, const char *msg, int code);
    int (*server_is_term)(void);
    int (*server_set_clip)(struct mod *v, int x, int y, int cx, int cy);
    int (*server_reset_clip)(struct mod *v);
    int (*server_set_fgcolor)(struct mod *v, int fgcolor);
    int (*server_set_bgcolor)(struct mod *v, int bgcolor);
    int (*server_set_opcode)(struct mod *v, int opcode);
    int (*server_set_mixmode)(struct mod *v, int mixmode);
    int (*server_set_brush)(struct mod *v, int x_origin, int y_origin,
                            int style, char *pattern);
    int (*server_set_pen)(struct mod *v, int style,
                          int width);
    int (*server_draw_line)(struct mod *v, int x1, int y1, int x2, int y2);
    int (*server_add_char)(struct mod *v, int font, int character,
                           int offset, int baseline,
                           int width, int height, char *data);
    int (*server_draw_text)(struct mod *v, int font,
                            int flags, int mixmode, int clip_left, int clip_top,
                            int clip_right, int clip_bottom,
                            int box_left, int box_top,
                            int box_right, int box_bottom,
                            int x, int y, char *data, int data_len);
    int (*server_reset)(struct mod *v, int width, int height, int bpp);
    int (*server_get_channel_count)(struct mod *v);
    int (*server_query_channel)(struct mod *v, int index,
                                char *channel_name,
                                int *channel_flags);
    int (*server_get_channel_id)(struct mod *v, const char *name);
    int (*server_send_to_channel)(struct mod *v, int channel_id,
                                  char *data, int data_len,
                                  int total_data_len, int flags);
    int (*server_bell_trigger)(struct mod *v);
    int (*server_chansrv_in_use)(struct mod *v);
    /* off screen bitmaps */
    int (*server_create_os_surface)(struct mod *v, int rdpindex,
                                    int width, int height);
    int (*server_switch_os_surface)(struct mod *v, int rdpindex);
    int (*server_delete_os_surface)(struct mod *v, int rdpindex);
    int (*server_paint_rect_os)(struct mod *mod, int x, int y,
                                int cx, int cy,
                                int rdpindex, int srcx, int srcy);
    int (*server_set_hints)(struct mod *mod, int hints, int mask);
    /* rail */
    int (*server_window_new_update)(struct mod *mod, int window_id,
                                    struct rail_window_state_order *window_state,
                                    int flags);
    int (*server_window_delete)(struct mod *mod, int window_id);
    int (*server_window_icon)(struct mod *mod,
                              int window_id, int cache_entry, int cache_id,
                              struct rail_icon_info *icon_info,
                              int flags);
    int (*server_window_cached_icon)(struct mod *mod,
                                     int window_id, int cache_entry,
                                     int cache_id, int flags);
    int (*server_notify_new_update)(struct mod *mod,
                                    int window_id, int notify_id,
                                    struct rail_notify_state_order *notify_state,
                                    int flags);
    int (*server_notify_delete)(struct mod *mod, int window_id,
                                int notify_id);
    int (*server_monitored_desktop)(struct mod *mod,
                                    struct rail_monitored_desktop_order *mdo,
                                    int flags);
    int (*server_set_pointer_ex)(struct mod *mod, int x, int y, char *data,
                                 char *mask, int bpp);
    int (*server_add_char_alpha)(struct mod *mod, int font, int character,
                                 int offset, int baseline,
                                 int width, int height, char *data);
    int (*server_create_os_surface_bpp)(struct mod *v, int rdpindex,
                                        int width, int height, int bpp);
    int (*server_paint_rect_bpp)(struct mod *v, int x, int y, int cx, int cy,
                                 char *data, int width, int height,
                                 int srcx, int srcy, int bpp);
    int (*server_composite)(struct mod *v, int srcidx, int srcformat,
                            int srcwidth, int srcrepeat, int *srctransform,
                            int mskflags, int mskidx, int mskformat,
                            int mskwidth, int mskrepeat, int op,
                            int srcx, int srcy, int mskx, int msky,
                            int dstx, int dsty, int width, int height,
                            int dstformat);
    int (*server_paint_rects)(struct mod *v,
                              int num_drects, short *drects,
                              int num_crects, short *crects,
                              char *data, int width, int height,
                              int flags, int frame_id);
    int (*server_session_info)(struct mod *v, const char *data,
                               int data_bytes);
    tintptr server_dumby[100 - 46]; /* align, 100 minus the number of server
                                       functions above */
    /* common */
    tintptr handle; /* pointer to self as long */
    tintptr wm;
    tintptr painter;
    struct source_info *si;

    /* mod data */
    int sck;
    int width;
    int height;
    int bpp;
    int colormap[256];
    char *chan_buf;
    int chan_buf_valid;
    int chan_buf_bytes;
    int vmaj;
    int vmin;
    int vrev;
    char username[INFO_CLIENT_MAX_CB_LEN];
    char password[INFO_CLIENT_MAX_CB_LEN];
    char domain[INFO_CLIENT_MAX_CB_LEN];
    int bool_keyBoardSynced ; /* Numlock can be out of sync, we hold state here to resolve */
    int keyBoardLockInfo ; /* Holds initial numlock capslock state */

    struct xrdp_client_info client_info;

    struct rdp_freerdp *inst;
    struct bitmap_item bitmap_cache[4][4096];
    struct brush_item brush_cache[64];
    struct pointer_item pointer_cache[32];
    char pamusername[255];

    int allow_client_experiencesettings;
    int perf_settings_override_mask; /* Performance bits overridden in ini file */
    int perf_settings_values_mask; /* Values of overridden performance bits */
    int allow_client_kbd_settings;
    struct kbd_overrides kbd_overrides; /* neutrinordp.overide_kbd_* values */
};


text:
package org.eclipse.jgit.revwalk.filter;

import java.io.IOException;

import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevFlagSet;
import org.eclipse.jgit.revwalk.RevWalk;

/** Matches only commits with some/all RevFlags already set. */
public abstract class RevFlagFilter extends RevFilter {
	/**
	 * Create a new filter that tests for a single flag.
	 *
	 * @param a
	 *            the flag to test.
	 * @return filter that selects only commits with flag a.
	 */
	public static RevFilter has(final RevFlag a) {
		final RevFlagSet s = new RevFlagSet();
		s.add(a);
		return new HasAll(s);
	}

	/**
	 * Create a new filter that tests all flags in a set.
	 *
	 * @param a
	 *            set of flags to test.
	 * @return filter that selects only commits with all flags in a.
	 */
	public static RevFilter hasAll(final RevFlag... a) {
		final RevFlagSet set = new RevFlagSet();
		for (final RevFlag flag : a)
			set.add(flag);
		return new HasAll(set);
	}

	/**
	 * Create a new filter that tests all flags in a set.
	 *
	 * @param a
	 *            set of flags to test.
	 * @return filter that selects only commits with all flags in a.
	 */
	public static RevFilter hasAll(final RevFlagSet a) {
		return new HasAll(new RevFlagSet(a));
	}

	/**
	 * Create a new filter that tests for any flag in a set.
	 *
	 * @param a
	 *            set of flags to test.
	 * @return filter that selects only commits with any flag in a.
	 */
	public static RevFilter hasAny(final RevFlag... a) {
		final RevFlagSet set = new RevFlagSet();
		for (final RevFlag flag : a)
			set.add(flag);
		return new HasAny(set);
	}

	/**
	 * Create a new filter that tests for any flag in a set.
	 *
	 * @param a
	 *            set of flags to test.
	 * @return filter that selects only commits with any flag in a.
	 */
	public static RevFilter hasAny(final RevFlagSet a) {
		return new HasAny(new RevFlagSet(a));
	}

	final RevFlagSet flags;

	RevFlagFilter(final RevFlagSet m) {
		flags = m;
	}

	@Override
	public RevFilter clone() {
		return this;
	}

	@Override
	public String toString() {
		return super.toString() + flags;
	}

	private static class HasAll extends RevFlagFilter {
		HasAll(final RevFlagSet m) {
			super(m);
		}

		@Override
		public boolean include(final RevWalk walker, final RevCommit c)
				throws MissingObjectException, IncorrectObjectTypeException,
				IOException {
			return c.hasAll(flags);
		}
	}

	private static class HasAny extends RevFlagFilter {
		HasAny(final RevFlagSet m) {
			super(m);
		}

		@Override
		public boolean include(final RevWalk walker, final RevCommit c)
				throws MissingObjectException, IncorrectObjectTypeException,
				IOException {
			return c.hasAny(flags);
		}
	}
}


text:
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures
from django.db.backends.mysql.features import (
    DatabaseFeatures as MySQLDatabaseFeatures,
)
from django.utils.functional import cached_property

class DatabaseFeatures(BaseSpatialFeatures, MySQLDatabaseFeatures):
    has_spatialrefsys_table = False
    supports_add_srs_entry = False
    supports_distance_geodetic = False
    supports_length_geodetic = False
    supports_area_geodetic = False
    supports_transform = False
    supports_real_shape_operations = False
    supports_null_geometries = False
    supports_num_points_poly = False

    @cached_property
    def supports_empty_geometry_collection(self):
        return self.connection.mysql_version >= (5, 7, 5)

    @cached_property
    def supports_geometry_field_unique_index(self):
        # Not supported in MySQL since https://dev.mysql.com/worklog/task/?id=11808
        return self.connection.mysql_is_mariadb


text:
namespace System.Net
{
    /// <devdoc>
    ///    <para>
    ///       An exception class used when an attempt is made to use an invalid
    ///       protocol.
    ///    </para>
    /// </devdoc>
    public class ProtocolViolationException : InvalidOperationException
    {
        /// <devdoc>
        ///    <para>
        ///       Creates a new instance of the <see cref='System.Net.ProtocolViolationException'/>class.
        ///    </para>
        /// </devdoc>
        public ProtocolViolationException() : base()
        {
        }

        /// <devdoc>
        ///    <para>
        ///       Creates a new instance of the <see cref='System.Net.ProtocolViolationException'/>
        ///       class with the specified message.
        ///    </para>
        /// </devdoc>
        public ProtocolViolationException(string message) : base(message)
        {
        }
    }
}


text:
package org.ihtsdo.otf.rest.client.terminologyserver.pojo;

import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonPropertyOrder({"conceptId", "effectiveTime", "active", "released", "inactivationIndicator", "moduleId", "definitionStatus",
		"descriptions", "classAxioms", "gciAxioms", "relationships"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class ConceptPojo {

	private String conceptId;

	private String effectiveTime;

	private boolean released;

	private boolean active;

	private String moduleId;

	private DefinitionStatus definitionStatus;

	private String inactivationIndicator;

	private Map<String, String[]> associationTargets;

	private Set<DescriptionPojo> descriptions;

	private Set<AxiomPojo> classAxioms;

	private Set<AxiomPojo> gciAxioms;

	private Set<RelationshipPojo> relationships;

	public ConceptPojo() {
		active = true;
	}

	public String getFsn() {
		if (descriptions != null) {
			for (DescriptionPojo description : descriptions) {
				if ("FSN".equals(description.getType()) && description.isActive()) {
					return description.getTerm();
				}
			}
		}
		return null;
	}

	public void add(RelationshipPojo relationship) {
		if (relationships == null) {
			relationships = new HashSet<>();
		}
		relationships.add(relationship);
	}

	public void add(DescriptionPojo description) {
		if (descriptions == null) {
			descriptions = new HashSet<>();
		}
		descriptions.add(description);
	}

	public void addClassAxiom(AxiomPojo axiomPojo) {
		if (classAxioms == null) {
			classAxioms = new HashSet<>();
		}
		classAxioms.add(axiomPojo);
	}

	public String getConceptId() {
		return conceptId;
	}

	public void setConceptId(String conceptId) {
		this.conceptId = conceptId;
	}

	public String getEffectiveTime() {
		return effectiveTime;
	}

	public void setEffectiveTime(String effectiveTime) {
		this.effectiveTime = effectiveTime;
	}

	public boolean isReleased() {
		return released;
	}

	public void setReleased(boolean released) {
		this.released = released;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	public String getModuleId() {
		return moduleId;
	}

	public void setModuleId(String moduleId) {
		this.moduleId = moduleId;
	}

	public DefinitionStatus getDefinitionStatus() {
		return definitionStatus;
	}

	public void setDefinitionStatus(DefinitionStatus definitionStatus) {
		this.definitionStatus = definitionStatus;
	}

	public String getInactivationIndicator() {
		return inactivationIndicator;
	}

	public void setInactivationIndicator(String inactivationIndicator) {
		this.inactivationIndicator = inactivationIndicator;
	}

	public Map<String, String[]> getAssociationTargets() {
		return associationTargets;
	}

	public void setAssociationTargets(Map<String, String[]> associationTargets) {
		this.associationTargets = associationTargets;
	}

	public Set<DescriptionPojo> getDescriptions() {
		return descriptions;
	}

	public void setDescriptions(Set<DescriptionPojo> descriptions) {
		this.descriptions = descriptions;
	}

	public Set<RelationshipPojo> getRelationships() {
		return relationships;
	}

	public void setRelationships(Set<RelationshipPojo> relationships) {
		this.relationships = relationships;
	}

	public Set<AxiomPojo> getClassAxioms() {
		return classAxioms;
	}

	public void setClassAxioms(Set<AxiomPojo> classAxioms) {
		this.classAxioms = classAxioms;
	}

	public Set<AxiomPojo> getGciAxioms() {
		return gciAxioms;
	}

	public void setGciAxioms(Set<AxiomPojo> gciAxioms) {
		this.gciAxioms = gciAxioms;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;
		ConceptPojo that = (ConceptPojo) o;
		return released == that.released &&
				active == that.active &&
				Objects.equals(conceptId, that.conceptId) &&
				Objects.equals(effectiveTime, that.effectiveTime) &&
				Objects.equals(moduleId, that.moduleId) &&
				definitionStatus == that.definitionStatus &&
				Objects.equals(inactivationIndicator, that.inactivationIndicator) &&
				Objects.equals(associationTargets, that.associationTargets) &&
				Objects.equals(descriptions, that.descriptions) &&
				Objects.equals(classAxioms, that.classAxioms) &&
				Objects.equals(gciAxioms, that.gciAxioms) &&
				Objects.equals(relationships, that.relationships);
	}

	@Override
	public int hashCode() {

		return Objects.hash(conceptId, effectiveTime, released, active, moduleId, definitionStatus, inactivationIndicator, associationTargets, descriptions, classAxioms, gciAxioms, relationships);
	}

	@Override
	public String toString() {
		return "ConceptPojo{" +
				"conceptId='" + conceptId + '\'' +
				", effectiveTime='" + effectiveTime + '\'' +
				", released=" + released +
				", active=" + active +
				", moduleId='" + moduleId + '\'' +
				", definitionStatus=" + definitionStatus +
				", inactivationIndicator='" + inactivationIndicator + '\'' +
				", associationTargets=" + associationTargets +
				", descriptions=" + descriptions +
				", classAxioms=" + classAxioms +
				", gciAxioms=" + gciAxioms +
				", relationships=" + relationships +
				'}';
	}
}


text:
var KeyboardInputManager = function() {
  this.events = {};
  this.listen();
};

KeyboardInputManager.prototype.on = function(event, cb) {
  if (!this.events[event]) this.events[event] = [];
  this.events[event].push(cb);
};

KeyboardInputManager.prototype.emit = function(event, data) {
  var callbacks = this.events[event];
  if (callbacks) {
    callbacks.forEach(function(cb) {
      cb(data);
    });
  }
};

KeyboardInputManager.prototype.listen = function() {
  var gameContainer = document.getElementById('game-container');
  var xAngle = 0, yAngle = 0, zAngle = 0;

  document.addEventListener('keydown', function(event) {
    event.preventDefault();
    var keyCode = event.which;
    var keyPressed = this.keyMap(keyCode);
    var arrowKeyAction = null, rotateKeyAction = null;

    var modifiers = event.altKey || event.ctrlKey
                    event.metaKey || event.shiftKey;

    if (modifiers) return;

    var arrowKeyPressed  = keyPressed.arrowKey;
    var rotateKeyPressed = keyPressed.rotateKey;

    if (arrowKeyPressed) {
      keyCode = this.arrowKeyModifier(keyCode, xAngle, yAngle, zAngle);
      arrowKeyAction = this.arrowKeyAction(keyCode);
      this.emit('move', arrowKeyAction);
    }

    else if (rotateKeyPressed) {
      keyCode = this.rotateKeyModifier(keyCode, xAngle, yAngle, zAngle);
      rotateKeyAction = this.rotateKeyAction(keyCode, xAngle, yAngle, zAngle);

      xAngle = rotateKeyAction.newXAngle;
      yAngle = rotateKeyAction.newYAngle;

      var newStyle = ["rotate3d(1,0,0,"+ xAngle +"deg)",
                      "rotate3d(0,1,0,"+ yAngle +"deg)",
                      "rotate3d(0,0,1,"+ zAngle +"deg)"];

      gameContainer.style.webkitTransform = newStyle.join(' ');
    }

  }.bind(this), false);
};

KeyboardInputManager.prototype.keyMap = function(keyCode) {
  var arrowKey = {
    38: true,
    39: true,
    40: true,
    37: true,
    191: true,
    190: true
  };

  var rotateKey = {
    65: true,
    87: true,
    68: true,
    83: true
  };

  return {
    arrowKey: arrowKey[keyCode],
    rotateKey: rotateKey[keyCode]
  };
};

KeyboardInputManager.prototype.arrowKeyModifier = function(keyCode, x, y, z) {
  var arrowKey = {
    38: 0,  // up
    39: 1,  // right
    40: 2,  // down
    37: 3,  // left
    191: 4, // front /
    190: 5  // back  .
  };

  var upsideDown     = (x % 180 === 0 && (x / 180) % 2 !== 0);
  var acuteSideways  = (x % 90  === 0 && (x / 90)  % 2 !== 0);
  var obtuseSideways = (x % 270 === 0 && (x / 270) % 2 !== 0);

  return keyCode;
};

KeyboardInputManager.prototype.arrowKeyAction = function(keyCode) {
  var arrowKey = {
    38: 0,  // up
    39: 1,  // right
    40: 2,  // down
    37: 3,  // left
    191: 4, // front /
    190: 5  // back  .
  };

  return arrowKey[keyCode];
};

KeyboardInputManager.prototype.rotateKeyModifier = function(keyCode, x, y, z) {
  var acuteSidewaysModifier = { // to do
    65: 65, // a
    87: 87, // w
    68: 68, // d
    83: 83  // s
  };

  var upsideDownModifier = {
    65: 68, // a
    87: 87, // w
    68: 65, // d
    83: 83  // s
  };

  var obtuseSidewaysModifier = { // to do
    65: 65, // a
    87: 87, // w
    68: 68, // d
    83: 83  // s
  };

  var acuteSideways  = (x % 90  === 0 && (x / 90)  % 2 !== 0);
  var upsideDown     = (x % 180 === 0 && (x / 180) % 2 !== 0);
  var obtuseSideways = (x % 270 === 0 && (x / 270) % 2 !== 0);

  if (acuteSideways) {
    keyCode = acuteSidewaysModifier[keyCode];
  } else if (upsideDown) {
    keyCode = upsideDownModifier[keyCode];
  } else if (obtuseSideways) {
    keyCode = obtuseSidewaysModifier[keyCode];
  }

  return keyCode;
};

KeyboardInputManager.prototype.rotateKeyAction = function(keyCode, x, y, z) {
  var rotateKey = {
    65: function() { y -= 90; }, // a
    87: function() { x += 90; }, // w
    68: function() { y += 90; }, // d
    83: function() { x -= 90; }  // s
  };

  var rotateAction = rotateKey[keyCode];
  rotateAction && rotateAction();

  return {
    newXAngle: x,
    newYAngle: y
  };
};


text:
// # API Utils
// Shared helpers for working with the API
var Promise = require('bluebird'),
    _       = require('lodash'),
    path    = require('path'),
    errors  = require('../errors'),
    permissions = require('../permissions'),
    validation  = require('../data/validation'),

    utils;

utils = {
    // ## Default Options
    // Various default options for different types of endpoints

    // ### Auto Default Options
    // Handled / Added automatically by the validate function
    // globalDefaultOptions - valid for every api endpoint
    globalDefaultOptions: ['context', 'include'],
    // dataDefaultOptions - valid for all endpoints which take object as well as options
    dataDefaultOptions: ['data'],

    // ### Manual Default Options
    // These must be provided by the endpoint
    // browseDefaultOptions - valid for all browse api endpoints
    browseDefaultOptions: ['page', 'limit', 'fields'],
    // idDefaultOptions - valid whenever an id is valid
    idDefaultOptions: ['id'],

    /**
     * ## Validate
     * Prepare to validate the object and options passed to an endpoint
     * @param {String} docName
     * @param {Object} extras
     * @returns {Function} doValidate
     */
    validate: function validate(docName, extras) {
        /**
         * ### Do Validate
         * Validate the object and options passed to an endpoint
         * @argument {...*} [arguments] object or object and options hash
         */
        return function doValidate() {
            var object, options, permittedOptions;
            if (arguments.length === 2) {
                object = arguments[0];
                options = _.clone(arguments[1]) || {};
            } else if (arguments.length === 1) {
                options = _.clone(arguments[0]) || {};
            } else {
                options = {};
            }

            // Setup permitted options, starting with the global defaults
            permittedOptions = utils.globalDefaultOptions;

            // Add extra permitted options if any are passed in
            if (extras && extras.opts) {
                permittedOptions = permittedOptions.concat(extras.opts);
            }

            // This request will have a data key added during validation
            if ((extras && extras.attrs) || object) {
                permittedOptions = permittedOptions.concat(utils.dataDefaultOptions);
            }

            // If an 'attrs' object is passed, we use this to pick from options and convert them to data
            if (extras && extras.attrs) {
                options.data = _.pick(options, extras.attrs);
                options = _.omit(options, extras.attrs);
            }

            /**
             * ### Check Options
             * Ensure that the options provided match exactly with what is permitted
             * - incorrect option keys are sanitized
             * - incorrect option values are validated
             * @param {object} options
             * @returns {Promise<options>}
             */
            function checkOptions(options) {
                // @TODO: should we throw an error if there are incorrect options provided?
                options = _.pick(options, permittedOptions);

                var validationErrors = utils.validateOptions(options);

                if (_.isEmpty(validationErrors)) {
                    return Promise.resolve(options);
                }

                // For now, we can only handle showing the first validation error
                return errors.logAndRejectError(validationErrors[0]);
            }

            // If we got an object, check that too
            if (object) {
                return utils.checkObject(object, docName, options.id).then(function (data) {
                    options.data = data;

                    return checkOptions(options);
                });
            }

            // Otherwise just check options and return
            return checkOptions(options);
        };
    },

    validateOptions: function validateOptions(options) {
        var globalValidations = {
                id: {matches: /^\d+|me$/},
                uuid: {isUUID: true},
                slug: {isSlug: true},
                page: {matches: /^\d+$/},
                limit: {matches: /^\d+|all$/},
                fields: {matches: /^[a-z0-9_,]+$/},
                name: {}
            },
            // these values are sanitised/validated separately
            noValidation = ['data', 'context', 'include'],
            errors = [];

        _.each(options, function (value, key) {
            // data is validated elsewhere
            if (noValidation.indexOf(key) === -1) {
                if (globalValidations[key]) {
                    errors = errors.concat(validation.validate(value, key, globalValidations[key]));
                } else {
                    // all other keys should be alpha-numeric with dashes/underscores, like tag, author, status, etc
                    errors = errors.concat(validation.validate(value, key, globalValidations.slug));
                }
            }
        });

        return errors;
    },

    /**
     * ## Is Public Context?
     * If this is a public context, return true
     * @param {Object} options
     * @returns {Boolean}
     */
    isPublicContext: function isPublicContext(options) {
        return permissions.parseContext(options.context).public;
    },
    /**
     * ## Apply Public Permissions
     * Update the options object so that the rules reflect what is permitted to be retrieved from a public request
     * @param {String} docName
     * @param {String} method (read || browse)
     * @param {Object} options
     * @returns {Object} options
     */
    applyPublicPermissions: function applyPublicPermissions(docName, method, options) {
        return permissions.applyPublicRules(docName, method, options);
    },

    /**
     * ## Handle Public Permissions
     * @param {String} docName
     * @param {String} method (read || browse)
     * @returns {Function}
     */
    handlePublicPermissions: function handlePublicPermissions(docName, method) {
        var singular = docName.replace(/s$/, '');

        /**
         * Check if this is a public request, if so use the public permissions, otherwise use standard canThis
         * @param {Object} options
         * @returns {Object} options
         */
        return function doHandlePublicPermissions(options) {
            var permsPromise;

            if (utils.isPublicContext(options)) {
                permsPromise = utils.applyPublicPermissions(docName, method, options);
            } else {
                permsPromise = permissions.canThis(options.context)[method][singular](options.data);
            }

            return permsPromise.then(function permissionGranted() {
                return options;
            }).catch(function handleError(error) {
                return errors.handleAPIError(error);
            });
        };
    },

    /**
     * ## Handle Permissions
     * @param {String} docName
     * @param {String} method (browse || read || edit || add || destroy)
     * @returns {Function}
     */
    handlePermissions: function handlePermissions(docName, method) {
        var singular = docName.replace(/s$/, '');

        /**
         * ### Handle Permissions
         * We need to be an authorised user to perform this action
         * @param {Object} options
         * @returns {Object} options
         */
        return function doHandlePermissions(options) {
            var permsPromise = permissions.canThis(options.context)[method][singular](options.id);

            return permsPromise.then(function permissionGranted() {
                return options;
            }).catch(errors.NoPermissionError, function handleNoPermissionError(error) {
                // pimp error message
                error.message = 'You do not have permission to ' + method + ' ' + docName;
                // forward error to next catch()
                return Promise.reject(error);
            }).catch(function handleError(error) {
                return errors.handleAPIError(error);
            });
        };
    },

    prepareInclude: function prepareInclude(include, allowedIncludes) {
        include = include || '';
        include = _.intersection(include.split(','), allowedIncludes);

        return include;
    },

    prepareFields: function prepareFields(fields) {
        fields = fields || '';
        if (_.isString(fields)) {
            fields = fields.split(',');
        }

        return fields;
    },

    /**
     * ## Convert Options
     * @param {Array} allowedIncludes
     * @returns {Function} doConversion
     */
    convertOptions: function convertOptions(allowedIncludes) {
        /**
         * Convert our options from API-style to Model-style
         * @param {Object} options
         * @returns {Object} options
         */
        return function doConversion(options) {
            if (options.include) {
                options.include = utils.prepareInclude(options.include, allowedIncludes);
            }
            if (options.fields) {
                options.columns = utils.prepareFields(options.fields);
                delete options.fields;
            }
            return options;
        };
    },
    /**
     * ### Check Object
     * Check an object passed to the API is in the correct format
     *
     * @param {Object} object
     * @param {String} docName
     * @returns {Promise(Object)} resolves to the original object if it checks out
     */
    checkObject: function (object, docName, editId) {
        if (_.isEmpty(object) || _.isEmpty(object[docName]) || _.isEmpty(object[docName][0])) {
            return errors.logAndRejectError(new errors.BadRequestError('No root key (\'' + docName + '\') provided.'));
        }

        // convert author property to author_id to match the name in the database
        if (docName === 'posts') {
            if (object.posts[0].hasOwnProperty('author')) {
                object.posts[0].author_id = object.posts[0].author;
                delete object.posts[0].author;
            }
        }

        if (editId && object[docName][0].id && parseInt(editId, 10) !== parseInt(object[docName][0].id, 10)) {
            return errors.logAndRejectError(new errors.BadRequestError('Invalid id provided.'));
        }

        return Promise.resolve(object);
    },
    checkFileExists: function (options, filename) {
        return !!(options[filename] && options[filename].type && options[filename].path);
    },
    checkFileIsValid: function (file, types, extensions) {
        var type = file.type,
            ext = path.extname(file.name).toLowerCase();

        if (_.contains(types, type) && _.contains(extensions, ext)) {
            return true;
        }
        return false;
    }
};

module.exports = utils;


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../utils/CSSClassnames';
import { graphValue, trackSize, padding } from './utils';

const CLASS_ROOT = CSSClassnames.CHART_MARKER;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;

const DOUBLE_PADDING = 2 * padding;

export default class Marker extends Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      size: { width: 0, height: 0 },
      graphHeight: 0,
      graphWidth: 0
    };
    this._size = new trackSize(props, this._onSize.bind(this));
  }

  componentDidMount () {
    this._size.start(this.svgRef);
  }

  componentWillReceiveProps (nextProps) {
    this._size.reset(nextProps);
  }

  componentWillUnmount () {
    this._size.stop();
  }

  _onSize (size) {
    this.setState({
      size: size,
      graphWidth: size.width - DOUBLE_PADDING,
      graphHeight: size.height - DOUBLE_PADDING
    });
  }

  render () {
    const {
      className, colorIndex, count, index, max, min, reverse, value, vertical,
      ...props
    } = this.props;
    delete props.height;
    delete props.width;
    const { size: { height, width }, graphWidth, graphHeight } = this.state;
    const classes = classnames(
      CLASS_ROOT, {
        [`${COLOR_INDEX}-${colorIndex}`]: colorIndex
      },
      className
    );

    let path;
    if ((count > 1 && index >= 1 && index < count) ||
      (value >= min && value <= max)) {
      let commands = '';

      if (vertical) {
        let x;
        if (count) {
          x = graphValue(index, 0, count - 1, graphWidth);
        } else if (max) {
          x = graphValue(value, min, max, graphWidth);
        }
        if (reverse) {
          x = graphWidth - x;
        }
        commands = `M${x + padding},0 L${x + padding},${height}`;
      } else {
        let y;
        if (count) {
          y = graphValue(index, 0, count - 1, graphHeight);
        } else if (max) {
          y = graphValue(value, min, max, graphHeight);
        }
        if (! reverse) {
          y = graphHeight - y;
        }
        commands = `M0,${y + padding} L${width},${y + padding}`;
      }

      path = <path fill="none" d={commands} />;
    }

    return (
      <svg ref={ref => this.svgRef = ref} {...props} className={classes}
        viewBox={`0 0 ${width} ${height}`} aria-hidden='true'
        preserveAspectRatio="none">
        {path}
      </svg>
    );
  }

}

// Need either count and index or value, min, and max
Marker.propTypes = {
  colorIndex: PropTypes.string,
  count: PropTypes.number,
  index: PropTypes.number,
  max: PropTypes.number,
  min: PropTypes.number,
  reverse: PropTypes.bool,
  value: PropTypes.number,
  vertical: PropTypes.bool
};

Marker.defaultProps = {
  max: 100,
  min: 0
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
C. r. Congr. natn. Socs. sav. Paris, sect. sci. , fasc. 1. (Paleobotanique) 105: 188 + pl. II, fig. 11 (1980)

#### Original name
Didymoporisporonites didymus Sal.-Cheb. & Locq.

### Remarks
null


text:
package org.treeleaf.db;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.treeleaf.common.bean.FastBeanUtils;
import org.treeleaf.common.safe.ID;
import org.treeleaf.db.handler.AnnotationBeanListHandler;
import org.treeleaf.db.meta.DBColumnMeta;
import org.treeleaf.db.meta.DBTableMeta;
import org.treeleaf.db.meta.DBTableMetaFactory;
import org.treeleaf.db.model.Model;
import org.treeleaf.db.model.example.Example;
import org.treeleaf.db.sql.AnalyzeResult;
import org.treeleaf.db.sql.SqlAnalyzer;
import org.treeleaf.db.sql.SqlAnalyzerFactory;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * MySql数据库操作器
 *
 * @Author leaf
 * 2015/1/11 0011 1:02.
 */
public class MySqlDBModelOperator extends DefaultDBOperator {

    private Logger log = LoggerFactory.getLogger(MySqlDBModelOperator.class);

    protected SqlAnalyzer sqlAnalyzer = null;

    public MySqlDBModelOperator(DBConnectionFactory dbConnectionFactory) {
        super(dbConnectionFactory);
        this.sqlAnalyzer = SqlAnalyzerFactory.getSqlAnalyzer(DBType.MYSQL);
    }

    /**
     * 保存数据
     *
     * @param model
     */
    public Serializable save(Object model) {
        if (model == null) {
            log.warn("更新数据失败,传入的model对象为null");
            return null;
        }

        DBTableMeta dbTableMeta = DBTableMetaFactory.getDBTableMeta(model.getClass());
        DBColumnMeta pk = dbTableMeta.getPrimaryKeys().get(0);
        if (dbTableMeta.getPrimaryKeys().size() == 1) {
            if (FastBeanUtils.getFieldValue(pk.getField(), model) == null && !pk.isAutoIncremen()) {//非数据库自增的主键,如果没传,则自动生成一个
                FastBeanUtils.setFieldValue(pk.getField(), model, ID.get());
            }
        }

        AnalyzeResult analyzeResult = getSqlAnalyzer().analyzeInsert(dbTableMeta, model);

        printSQL(analyzeResult.getSql(), analyzeResult.getParams());

        Connection conn = getDbConnectionFactory().getConnection();

        QueryRunner queryRunner = new QueryRunner();
        try {
            queryRunner.update(conn, analyzeResult.getSql(), analyzeResult.getParams());

            if (dbTableMeta.getPrimaryKeys().size() == 1 && pk.isAutoIncremen()) {//对于基于mysql数据库自增的主键,这里查出来,并设值回去
                Object id = queryRunner.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler(1));
                FastBeanUtils.setFieldValue(pk.getField(), model, id);
                return (Serializable) id;
            } else {
                return (Serializable) FastBeanUtils.getFieldValue(pk.getField(), model);
            }

        } catch (SQLException e) {
            throw new RuntimeException("保存数据失败", e);
        } finally {
            getDbConnectionFactory().releaseConnection(conn);
        }

    }

    /**
     * 通过表达式查询数据
     *
     * @param example
     * @param classz
     * @param <T>
     * @return
     */
    public <T extends Model> List<T> findByExample(Example example, Class<T> classz) {
        DBTableMeta dbTableMeta = DBTableMetaFactory.getDBTableMeta(classz);
        AnalyzeResult analyzeResult = getSqlAnalyzer().analyzeSelectByExample(dbTableMeta, example);
        printSQL(analyzeResult.getSql(), analyzeResult.getParams());

        Connection conn = getDbConnectionFactory().getConnection();

        QueryRunner queryRunner = new QueryRunner();
        try {
            return queryRunner.query(conn, analyzeResult.getSql(), new AnnotationBeanListHandler<>(classz), analyzeResult.getParams());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            getDbConnectionFactory().releaseConnection(conn);
        }
    }

    @Override
    public SqlAnalyzer getSqlAnalyzer() {
        return this.sqlAnalyzer;
    }

}


text:
"""empty message

Revision ID: 4a60dc223c11
Revises: 2732661b799a
Create Date: 2015-03-29 22:02:51.411483

"""

# revision identifiers, used by Alembic.
revision = '4a60dc223c11'
down_revision = '2732661b799a'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('daily_stats',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('datetime', sa.DateTime(), nullable=True),
    sa.Column('path', sa.String(), nullable=True),
    sa.Column('args', postgresql.JSON(), nullable=True),
    sa.Column('referrer', sa.String(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('daily_stats')
    ### end Alembic commands ###


text:
<?php while (have_posts()) : the_post(); ?>
  <article <?php post_class(); ?>>

          <a href="<?= the_permalink(45); ?>" class="backtowork">

<?php the_title(); ?>

          <?php the_content(); ?>

           <?php
            /**
             *  Infinite next and previous post looping in WordPress
             */
            if( get_adjacent_post(false, '', true) ) {
              previous_post_link('%link', ' %title', FALSE);
            } else {
                $first = new WP_Query('post_type=project&posts_per_page=1&order=DESC'); $first->the_post();
                  echo ' '.get_the_title().'';
                wp_reset_query();
            };
              echo " | ";
            if( get_adjacent_post(false, '', false) ) {
              next_post_link('%link', '%title ', FALSE);
            } else {
              $last = new WP_Query('post_type=project&posts_per_page=1&order=ASC'); $last->the_post();
                  echo ''.get_the_title().' ';
                wp_reset_query();
            };
          ?>

    <?php
      $the_gallery = get_field('gallery');
      if( $the_gallery ): ?>

              <?php foreach( $the_gallery as $image ): ?>

                  <a class="popimg" href="<?= $image['url']; ?>" title="<?php the_title(); ?>">
                    <?= wp_get_attachment_image($image['id'], 'large' ); ?>

              <?php endforeach; ?>

    <?php endif; ?>

<?php endwhile; ?>
<?php get_template_part('templates/project','keyboard'); ?>


text:
#include "CCGLViewImpl-wp8.h"
#include "deprecated/CCSet.h"
#include "base/ccMacros.h"
#include "base/CCDirector.h"
#include "base/CCTouch.h"
#include "base/CCIMEDispatcher.h"
#include "CCApplication.h"
#include "CCWinRTUtils.h"
#include "deprecated/CCNotificationCenter.h"

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Display;
using namespace Windows::UI::Input;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::System;
using namespace Windows::UI::ViewManagement;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::Phone::UI::Core;
using namespace Platform;
using namespace Microsoft::WRL;

NS_CC_BEGIN

static GLViewImpl* s_pEglView = NULL;

GLViewImpl* GLViewImpl::create(const std::string& viewName)
{
    auto ret = new GLViewImpl;
    if(ret && ret->initWithFullScreen(viewName))
    {
        ret->autorelease();
        return ret;
    }

    return nullptr;
}

GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, cocos2d::Rect /*rect*/, float /*frameZoomFactor*/)
{
    CCLOG("Not support rect on windows phone");
    return GLViewImpl::create(viewName);
}

GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName)
{
    return GLViewImpl::create(viewName);
}

GLViewImpl::GLViewImpl()
	: _frameZoomFactor(1.0f)
	, _supportTouch(true)
    , _isRetina(false)
	, m_lastPointValid(false)
	, m_running(false)
	, m_initialized(false)
	, m_windowClosed(false)
	, m_windowVisible(true)
    , m_width(0)
    , m_height(0)
    , m_eglDisplay(nullptr)
    , m_eglContext(nullptr)
    , m_eglSurface(nullptr)
    , m_delegate(nullptr)
    , m_messageBoxDelegate(nullptr)
    , m_orientation(DisplayOrientations::Landscape)
{
	s_pEglView = this;
    _viewName =  "cocos2dx";
}

GLViewImpl::~GLViewImpl()
{
	CC_ASSERT(this == s_pEglView);
    s_pEglView = NULL;

	// TODO: cleanup
}

bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
    setViewName(viewName);
    setFrameSize(rect.size.width, rect.size.height);
    setFrameZoomFactor(frameZoomFactor);
    return true;
}

bool GLViewImpl::initWithFullScreen(const std::string& viewName)
{
    return initWithRect(viewName, Rect(0, 0, m_width, m_height), 1.0f);
}

bool GLViewImpl::Create(EGLDisplay eglDisplay, EGLContext eglContext, EGLSurface eglSurface, float width, float height, DisplayOrientations orientation)
{
    m_orientation = orientation;
    m_eglDisplay = eglDisplay;
    m_eglContext = eglContext;
    m_eglSurface = eglSurface;
    UpdateForWindowSizeChange(width, height);
    return true;
}

void GLViewImpl::UpdateDevice(EGLDisplay eglDisplay, EGLContext eglContext, EGLSurface eglSurface)
{
    m_eglDisplay = eglDisplay;
    m_eglContext = eglContext;
    m_eglSurface = eglSurface;

    //UpdateForWindowSizeChange(width, height);
}

void GLViewImpl::setIMEKeyboardState(bool bOpen)
{
    std::string str;
    setIMEKeyboardState(bOpen, str);
}

void GLViewImpl::setIMEKeyboardState(bool bOpen, std::string str)
{
    if(m_delegate)
    {
        if(bOpen)
        {
            m_delegate->Invoke(Cocos2dEvent::ShowKeyboard, stringToPlatformString(str));
        }
        else
        {
            m_delegate->Invoke(Cocos2dEvent::HideKeyboard, stringToPlatformString(str));
        }
    }
}

Platform::String^ GLViewImpl::stringToPlatformString(std::string strSrc)
{
    // to wide char
    int strLen = MultiByteToWideChar(CP_UTF8, 0, strSrc.c_str(), -1, NULL, 0);
    wchar_t* wstr = new wchar_t[strLen + 1];
    memset(wstr, 0, strLen + 1);
    MultiByteToWideChar(CP_UTF8, 0, strSrc.c_str(), -1, wstr, strLen);
    Platform::String^ strDst = ref new Platform::String(wstr);
    delete[] wstr;
    return strDst;
}

void GLViewImpl::swapBuffers()
{
    eglSwapBuffers(m_eglDisplay, m_eglSurface);
}

bool GLViewImpl::isOpenGLReady()
{
	// TODO: need to revisit this
    return (m_eglDisplay && m_orientation != DisplayOrientations::None);
}

void GLViewImpl::end()
{
	m_windowClosed = true;
    std::string str;
	if (m_delegate) {
		// Terminate app on Director::getInstance()->end();
        m_delegate->Invoke(Cocos2dEvent::TerminateApp, stringToPlatformString(str));
	}
}

void GLViewImpl::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
{
}

void GLViewImpl::OnResuming(Platform::Object^ sender, Platform::Object^ args)
{
}

// user pressed the Back Key on the phone
void GLViewImpl::OnBackKeyPress()
{
	EventKeyboard event(EventKeyboard::KeyCode::KEY_ESCAPE, false);
	Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}

void GLViewImpl::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
{
    OnPointerPressed(args);
}

void GLViewImpl::OnPointerPressed(PointerEventArgs^ args)
{
    int id = args->CurrentPoint->PointerId;
    Vec2 pt = GetPoint(args);
    handleTouchesBegin(1, &id, &pt.x, &pt.y);
}

void GLViewImpl::OnPointerWheelChanged(CoreWindow^ sender, PointerEventArgs^ args)
{
    float direction = (float)args->CurrentPoint->Properties->MouseWheelDelta;
    int id = 0;
    Vec2 p(0.0f,0.0f);
    handleTouchesBegin(1, &id, &p.x, &p.y);
    p.y += direction;
    handleTouchesMove(1, &id, &p.x, &p.y);
    handleTouchesEnd(1, &id, &p.x, &p.y);
}

void GLViewImpl::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
{
	m_windowVisible = args->Visible;
}

void GLViewImpl::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
{
	m_windowClosed = true;
}

void GLViewImpl::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
{
    OnPointerMoved(args);
}

void GLViewImpl::OnPointerMoved( PointerEventArgs^ args)
{
	auto currentPoint = args->CurrentPoint;
	if (currentPoint->IsInContact)
	{
		if (m_lastPointValid)
		{
			int id = args->CurrentPoint->PointerId;
			Vec2 p = GetPoint(args);
			handleTouchesMove(1, &id, &p.x, &p.y);
		}
		m_lastPoint = currentPoint->Position;
		m_lastPointValid = true;
	}
	else
	{
		m_lastPointValid = false;
	}
}

void GLViewImpl::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
{
    OnPointerReleased(args);
}

void GLViewImpl::OnPointerReleased(PointerEventArgs^ args)
{
    int id = args->CurrentPoint->PointerId;
    Vec2 pt = GetPoint(args);
    handleTouchesEnd(1, &id, &pt.x, &pt.y);
}

void GLViewImpl::resize(int width, int height)
{

}

void GLViewImpl::setFrameZoomFactor(float fZoomFactor)
{
    _frameZoomFactor = fZoomFactor;
    Director::getInstance()->setProjection(Director::getInstance()->getProjection());
    //resize(m_obScreenSize.width * fZoomFactor, m_obScreenSize.height * fZoomFactor);
}

float GLViewImpl::getFrameZoomFactor()
{
    return _frameZoomFactor;
}

void GLViewImpl::centerWindow()
{
	// not implemented in WinRT. Window is always full screen
}

GLViewImpl* GLViewImpl::sharedOpenGLView()
{
    return s_pEglView;
}

int GLViewImpl::Run()
{
    // XAML version does not have a run loop
	m_running = true;
    return 0;
};

void GLViewImpl::Render()
{
    OnRendering();
}

void GLViewImpl::OnRendering()
{
	if(m_running && m_initialized)
	{
        Director::getInstance()->mainLoop();
	}
}

bool GLViewImpl::ShowMessageBox(Platform::String^ title, Platform::String^ message)
{
    if(m_messageBoxDelegate)
    {
        m_messageBoxDelegate->Invoke(title, message);
        return true;
    }
    return false;
}

bool GLViewImpl::OpenXamlEditBox(Platform::String^ strPlaceHolder, Platform::String^ strText, int maxLength, int inputMode, int inputFlag, Windows::Foundation::EventHandler<Platform::String^>^ receiveHandler)
{
    if(m_editBoxDelegate)
    {
        m_editBoxDelegate->Invoke(strPlaceHolder, strText, maxLength, inputMode, inputFlag, receiveHandler);
        return true;
    }
    return false;
}

// called by orientation change from WP8 XAML
void GLViewImpl::UpdateOrientation(DisplayOrientations orientation)
{
    if(m_orientation != orientation)
    {
        m_orientation = orientation;
        UpdateWindowSize();
    }
}

// called by size change from WP8 XAML
void GLViewImpl::UpdateForWindowSizeChange(float width, float height)
{
    m_width = width;
    m_height = height;
    UpdateWindowSize();
}

#if 0
win32 version

void GLViewEventHandler::OnGLFWWindowSizeFunCallback(GLFWwindow *windows, int width, int height)
{
	auto view = Director::getInstance()->getOpenGLView();
	if(view && view->getResolutionPolicy() != ResolutionPolicy::UNKNOWN)
	{
		Size resSize=view->getDesignResolutionSize();
		ResolutionPolicy resPolicy=view->getResolutionPolicy();
		view->setFrameSize(width, height);
 		view->setDesignResolutionSize(resSize.width, resSize.height, resPolicy);
		Director::getInstance()->setViewport();
	}
}
#endif

void GLViewImpl::UpdateWindowSize()
{
    float width, height;

    if(m_orientation == DisplayOrientations::Landscape || m_orientation == DisplayOrientations::LandscapeFlipped)
    {
        width = m_height;
        height = m_width;
    }
    else
    {
        width = m_width;
        height = m_height;
    }

    UpdateOrientationMatrix();

    //CCSize designSize = getDesignResolutionSize();
    if(!m_initialized)
    {
        m_initialized = true;
        GLView::setFrameSize(width, height);
    }

    auto view = Director::getInstance()->getOpenGLView();
	if(view && view->getResolutionPolicy() != ResolutionPolicy::UNKNOWN)
	{
		Size resSize=view->getDesignResolutionSize();
		ResolutionPolicy resPolicy=view->getResolutionPolicy();
		view->setFrameSize(width, height);
 		view->setDesignResolutionSize(resSize.width, resSize.height, resPolicy);
		Director::getInstance()->setViewport();
        Director::sharedDirector()->setProjection(Director::sharedDirector()->getProjection());
	}
}

const Mat4& GLViewImpl::getOrientationMatrix() const
{
    return m_orientationMatrix;
};

void GLViewImpl::UpdateOrientationMatrix()
{
    kmMat4Identity(&m_orientationMatrix);
    kmMat4Identity(&m_reverseOrientationMatrix);
    switch(m_orientation)
	{
		case Windows::Graphics::Display::DisplayOrientations::PortraitFlipped:
			kmMat4RotationZ(&m_orientationMatrix, M_PI);
			kmMat4RotationZ(&m_reverseOrientationMatrix, -M_PI);
			break;

		case Windows::Graphics::Display::DisplayOrientations::Landscape:
            kmMat4RotationZ(&m_orientationMatrix, -M_PI_2);
			kmMat4RotationZ(&m_reverseOrientationMatrix, M_PI_2);
			break;

		case Windows::Graphics::Display::DisplayOrientations::LandscapeFlipped:
            kmMat4RotationZ(&m_orientationMatrix, M_PI_2);
            kmMat4RotationZ(&m_reverseOrientationMatrix, -M_PI_2);
			break;

        default:
            break;
	}
}

cocos2d::Vec2 GLViewImpl::TransformToOrientation(Windows::Foundation::Point p)
{
    cocos2d::Vec2 returnValue;

    float x = p.X;
    float y = p.Y;

    switch (m_orientation)
    {
        case DisplayOrientations::Portrait:
        default:
            returnValue = Vec2(x, y);
            break;
        case DisplayOrientations::Landscape:
            returnValue = Vec2(y, m_width - x);
            break;
        case DisplayOrientations::PortraitFlipped:
            returnValue = Vec2(m_width - x, m_height - y);
            break;
        case DisplayOrientations::LandscapeFlipped:
            returnValue = Vec2(m_height - y, x);
            break;
    }

	float zoomFactor = GLViewImpl::sharedOpenGLView()->getFrameZoomFactor();
	if(zoomFactor > 0.0f) {
		returnValue.x /= zoomFactor;
		returnValue.y /= zoomFactor;
	}

    // CCLOG("%.2f %.2f : %.2f %.2f", p.X, p.Y,returnValue.x, returnValue.y);

    return returnValue;
}

Vec2 GLViewImpl::GetPoint(PointerEventArgs^ args) {

	return TransformToOrientation(args->CurrentPoint->Position);

}

void GLViewImpl::setViewPortInPoints(float x , float y , float w , float h)
{
    switch(m_orientation)
	{
		case DisplayOrientations::Landscape:
		case DisplayOrientations::LandscapeFlipped:
            glViewport((GLint)(y * _scaleY + _viewPortRect.origin.y),
                       (GLint)(x * _scaleX + _viewPortRect.origin.x),
                       (GLsizei)(h * _scaleY),
                       (GLsizei)(w * _scaleX));
			break;

        default:
            glViewport((GLint)(x * _scaleX + _viewPortRect.origin.x),
                       (GLint)(y * _scaleY + _viewPortRect.origin.y),
                       (GLsizei)(w * _scaleX),
                       (GLsizei)(h * _scaleY));
	}
}

void GLViewImpl::setScissorInPoints(float x , float y , float w , float h)
{
    switch(m_orientation)
	{
		case DisplayOrientations::Landscape:
		case DisplayOrientations::LandscapeFlipped:
            glScissor((GLint)(y * _scaleX + _viewPortRect.origin.y),
                       (GLint)((_viewPortRect.size.width - ((x + w) * _scaleX)) + _viewPortRect.origin.x),
                       (GLsizei)(h * _scaleY),
                       (GLsizei)(w * _scaleX));
			break;

        default:
            glScissor((GLint)(x * _scaleX + _viewPortRect.origin.x),
                       (GLint)(y * _scaleY + _viewPortRect.origin.y),
                       (GLsizei)(w * _scaleX),
                       (GLsizei)(h * _scaleY));
	}
}

void GLViewImpl::QueueBackKeyPress()
{
    std::shared_ptr<BackButtonEvent> e(new BackButtonEvent());
    mInputEvents.push(e);
}

void GLViewImpl::QueuePointerEvent(PointerEventType type, PointerEventArgs^ args)
{
    std::shared_ptr<PointerEvent> e(new PointerEvent(type, args));
    mInputEvents.push(e);
}

void GLViewImpl::QueueEvent(std::shared_ptr<InputEvent>& event)
{
    mInputEvents.push(event);
}

void GLViewImpl::ProcessEvents()
{
    std::shared_ptr<InputEvent> e;
    while (mInputEvents.try_pop(e))
    {
        e->execute();
    }
}

NS_CC_END


text:
import React, { ComponentType, ReactElement, ReactNode } from 'react';
import { ContentState } from 'draft-js';
import clsx from 'clsx';
import { MentionData } from '.';
import { MentionPluginTheme } from './theme';

export interface SubMentionComponentProps {
  mention: MentionData;
  children: ReactNode;
  className: string;
  entityKey: string;
  theme: MentionPluginTheme;
  decoratedText: string;
}

export interface MentionProps {
  mention: MentionData;
  children: ReactNode;
  className: string;
  entityKey: string;
  theme?: MentionPluginTheme;
  mentionComponent?: ComponentType<SubMentionComponentProps>;
  decoratedText: string;
  contentState: ContentState;
}

function MentionLink({
  mention,
  children,
  className,
}: SubMentionComponentProps): ReactElement {
  return (
    <a
      href={mention.link}
      className={className}
      spellCheck={false}
      data-testid="mentionLink"
    >
      {children}
    </a>
  );
}

function MentionText({
  children,
  className,
}: SubMentionComponentProps): ReactElement {
  return (
    <span className={className} spellCheck={false} data-testid="mentionText">
      {children}
    </span>
  );
}

export default function Mention(props: MentionProps): ReactElement {
  const {
    entityKey,
    theme = {},
    mentionComponent,
    children,
    decoratedText,
    className,
    contentState,
  } = props;

  const combinedClassName = clsx(theme.mention, className);
  const mention = contentState.getEntity(entityKey).getData().mention;

  const Component =
    mentionComponent || (mention.link ? MentionLink : MentionText);

  return (
    <Component
      entityKey={entityKey}
      mention={mention}
      theme={theme}
      className={combinedClassName}
      decoratedText={decoratedText}
    >
      {children}
    </Component>
  );
}


text:
namespace ExampleApp
{
    namespace OpenableControl
    {
        namespace View
        {
            class IOpenableControlViewModel : public virtual Eegeo::Helpers::IIdentity
            {
            public:
                virtual ~IOpenableControlViewModel() { }

                virtual void Open() = 0;

                virtual void Close() = 0;

                virtual void InsertOpenStateChangedCallback(Eegeo::Helpers::ICallback1<IOpenableControlViewModel&>& callback) = 0;

                virtual void RemoveOpenStateChangedCallback(Eegeo::Helpers::ICallback1<IOpenableControlViewModel&>& callback) = 0;

                virtual bool IsOpen() const = 0;

                virtual bool IsClosed() const = 0;
            };
        }
    }
}


text:
import { takeLatest, takeEvery } from 'redux-saga'

import api from 'store/api'

import {
  noop
} from 'store/actions/common'

import {
  createRequestSaga
} from 'store/sagas/common'

import {
  replaceNotes,
  openNote,
  insertNote,
  updateNote,
  removeNote,
  setToast
} from 'store/actions/note'

const requestReadNotesAsync = createRequestSaga({
  request: api.notes.readList,
  key: 'readNotes',
  success: [
    replaceNotes,
    (notes) => (notes.ids.length > 0)
      ? openNote(notes.ids[0])
      : noop('No note to open')
  ],
})

const requestCreateNoteAsync = createRequestSaga({
  request: api.notes.create,
  key: 'createNote',
  success: [
    insertNote,
    (note) => openNote(note.id),
    () => setToast('Note created')
  ],
  failure: [
    () => setToast('Couldn\'t add note', 'warn')
  ],
})

const requestUpdateNoteAsync = createRequestSaga({
  request: api.notes.update,
  key: (id) => `updateNote/${id}`,
  success: [
    updateNote,
    () => setToast('Note saved')
  ],
  failure: [
    () => setToast('Couldn\'t save note', 'warn')
  ],
})

const requestDeleteNoteAsync = createRequestSaga({
  request: api.notes.delete,
  key: (id) => `deleteNote/${id}`,
  success: [
    (note) => removeNote(note.id),
    () => setToast('Note deleted')
  ],
  failure: [
    () => setToast('Couldn\'t remove note', 'warn')
  ],
})

// root saga reducer
const asyncNoteFetchWatchers = [
  // like case return, this is take => call
  // inner function we use yield*
  // from direct watcher we just yield value
  function* asyncNoteFetchWatcher() {
    // use takeLatest instead of take every, so double click in short time will not trigger more fork
    yield [
      takeEvery('app/requestReadNotes', requestReadNotesAsync),
      takeEvery('app/requestCreateNote', requestCreateNoteAsync),
      takeEvery('app/requestUpdateNote', requestUpdateNoteAsync),
      takeEvery('app/requestDeleteNote', requestDeleteNoteAsync)
    ]
  }
]

export default asyncNoteFetchWatchers