text:
enum
{
    PFTYPE_RESERVED  = 0,
    PFTYPE_AVAILABLE = 1,
    PFTYPE_ALLOCATED = 2,
};

/// The pf structure represents a record in the page frame database.
typedef struct pf
{
    uint32_t prev;          ///< Index of prev pfn on available list
    uint32_t next;          ///< Index of next pfn on available list
    uint16_t refcount;      ///< Number of references to this page
    uint16_t sharecount;    ///< Number of processes sharing page
    uint16_t flags;
    uint8_t  type;          ///< PFTYPE of page frame
    uint8_t  reserved0;
    uint64_t reserved1;
    uint64_t reserved2;
} pf_t;

STATIC_ASSERT(sizeof(pf_t) == 32, "Unexpected page frame size");

/// The pfdb describes the state of the page frame database.
struct pfdb
{
    pf_t    *pf;          ///< Pointer to array of page frames
    uint32_t count;       ///< Total number of frames in the pfdb
    uint32_t avail;       ///< Available number of frames in the pfdb
    uint32_t head;        ///< Index of available frame list head
    uint32_t tail;        ///< Index of available frame list tail
};

static struct pfdb  pfdb;      // Global page frame database
static pagetable_t  kpt;       // Kernel page table (all physical memory)
static pagetable_t *active_pt; // Currently active page table

// TODO: Modify to support multi-core

/// Reserve an aligned region of memory managed by the memory table module.
static void *
reserve_region(const pmap_t *map, uint64_t size, uint32_t alignshift)
{
    const pmapregion_t *r = map->region;
    const pmapregion_t *t = map->region + map->count;
    for (; r < t; r++) {

        // Skip reserved regions and regions that are too small.
        if (r->type != PMEMTYPE_USABLE)
            continue;
        if (r->size < size)
            continue;

        // Find address of first properly aligned byte in the region.
        uint64_t paddr = r->addr + (1 << alignshift) - 1;
        paddr >>= alignshift;
        paddr <<= alignshift;

        // If the region is too small after alignment, skip it.
        if (paddr + size > r->addr + r->size)
            continue;

        // Reserve the aligned memory region and return its address.
        pmap_add(paddr, size, PMEMTYPE_RESERVED);
        return (void *)paddr;
    }
    return NULL;
}

void
page_init()
{
    // Retrieve the physical memory map.
    const pmap_t *map = pmap();
    if (map->last_usable == 0)
        fatal();

    // Calculate the size of the page frame database. It needs to describe
    // each page up to and including the last physical address.
    pfdb.count = map->last_usable / PAGE_SIZE;
    uint64_t pfdbsize = pfdb.count * sizeof(pf_t);

    // Round the database size up to the nearest 2MiB since we'll be using
    // large pages in the kernel page table to describe the database.
    pfdbsize  += PAGE_SIZE_LARGE - 1;
    pfdbsize >>= PAGE_SHIFT_LARGE;
    pfdbsize <<= PAGE_SHIFT_LARGE;

    // Find a contiguous, 2MiB-aligned region of memory large enough to hold
    // the entire pagedb.
    pfdb.pf = (pf_t *)reserve_region(map, pfdbsize, PAGE_SHIFT_LARGE);
    if (pfdb.pf == NULL)
        fatal();

    // Initialize the kernel's page table.
    kmem_init(&kpt);
    set_pagetable(kpt.proot);
    active_pt = &kpt;

    // Create the page frame database in the newly mapped virtual memory.
    memzero(pfdb.pf, pfdbsize);

    // Initialize available page frame list.
    pfdb.avail = 0;
    pfdb.head  = PFN_INVALID;
    pfdb.tail  = PFN_INVALID;

    // Traverse the memory table, adding page frame database entries for each
    // region in the table.
    for (uint64_t r = 0; r < map->count; r++) {
        const pmapregion_t *region = &map->region[r];

        // Ignore non-usable memory regions.
        if (region->type != PMEMTYPE_USABLE)
            continue;

        // Create a chain of available page frames.
        uint64_t pfn0 = region->addr >> PAGE_SHIFT;
        uint64_t pfnN = (region->addr + region->size) >> PAGE_SHIFT;
        for (uint64_t pfn = pfn0; pfn < pfnN; pfn++) {
            pf_t *pf = PFN_TO_PF(pfn);
            pf->prev = pfn - 1;
            pf->next = pfn + 1;
            pf->type = PFTYPE_AVAILABLE;
        }

        // Link the chain to the list of available frames.
        if (pfdb.tail == PFN_INVALID)
            pfdb.head = pfn0;
        else
            pfdb.pf[pfdb.tail].next = pfn0;
        pfdb.pf[pfn0].prev     = pfdb.tail;
        pfdb.pf[pfnN - 1].next = PFN_INVALID;
        pfdb.tail              = pfnN - 1;

        // Update the total number of available frames.
        pfdb.avail += (uint32_t)(pfnN - pfn0);
    }

    // TODO: Install page fault handler
}

static pf_t *
pfalloc()
{
    // For now, fatal out. Later, we'll add swapping.
    if (pfdb.avail == 0)
        fatal();

    // Grab the first available page frame from the database.
    pf_t *pf = PFN_TO_PF(pfdb.head);

    // Update the available frame list.
    pfdb.head = pfdb.pf[pfdb.head].next;
    if (pfdb.head != PFN_INVALID)
        pfdb.pf[pfdb.head].prev = PFN_INVALID;

    // Initialize and return the page frame.
    memzero(pf, sizeof(pf_t));
    pf->refcount = 1;
    pf->type     = PFTYPE_ALLOCATED;
    return pf;
}

static void
pffree(pf_t *pf)
{
    if (pf->type != PFTYPE_ALLOCATED)
        fatal();

    // Re-initialize the page frame record.
    memzero(pf, sizeof(pf_t));
    pf->prev = PFN_INVALID;
    pf->next = pfdb.head;
    pf->type = PFTYPE_AVAILABLE;

    // Update the database's available frame list.
    uint32_t pfn = PF_TO_PFN(pf);
    pfdb.pf[pfdb.head].prev = pfn;
    pfdb.head               = pfn;

    pfdb.avail++;
}

static uint64_t
pgalloc()
{
    // Allocate a page frame from the db and compute its physical address.
    pf_t    *pf    = pfalloc();
    uint64_t paddr = PF_TO_PADDR(pf);

    // Always zero the contents of newly allocated pages.
    memzero((void *)paddr, PAGE_SIZE);

    // Return the page's physical address.
    return paddr;
}

static void
pgfree(uint64_t paddr)
{
    pf_t *pf = PADDR_TO_PF(paddr);
    if (--pf->refcount == 0)
        pffree(pf);
}

static void
pgfree_recurse(page_t *page, int level)
{
    // If we're at the PT level, return the leaf pages to the page frame
    // database.
    if (level == 1) {
        for (uint64_t e = 0; e < 512; e++) {
            uint64_t paddr = PTE_TO_PADDR(page->entry[e]);
            if (paddr == 0)
                continue;
            pf_t *pf = PADDR_TO_PF(paddr);
            if (pf->type == PFTYPE_ALLOCATED)
                pgfree(paddr);
        }
    }

    // If we're at the PD level or above, recursively traverse child tables
    // until we reach the PT level.
    else {
        for (uint64_t e = 0; e < 512; e++) {
            if (page->entry[e] & PF_SYSTEM) // Never free system tables
                continue;
            page_t *child = PGPTR(page->entry[e]);
            if (child == NULL)
                continue;
            pgfree_recurse(child, level - 1);
        }
    }
}

/// Add to the page table an entry mapping a virtual address to a physical
/// address.
static void
add_pte(pagetable_t *pt, uint64_t vaddr, uint64_t paddr, uint32_t pflags,
        uint32_t addflags)
{
    // Fatal out if virtual address space is exhausted.
    if ((addflags & CONTAINS_TABLE) && (vaddr >= pt->vterm))
        fatal();

    // Keep track of the pages we add to the page table as we add this new
    // page table entry.
    uint64_t added[3];
    int      count = 0;

    // Decompose the virtual address into its hierarchical table components.
    uint32_t pml4e = PML4E(vaddr);
    uint32_t pdpte = PDPTE(vaddr);
    uint32_t pde   = PDE(vaddr);
    uint32_t pte   = PTE(vaddr);

    // Follow the page table hierarchy down to the lowest level, creating
    // new pages for tables as needed.

    page_t *pml4t = (page_t *)pt->proot;
    if (pml4t->entry[pml4e] == 0) {
        uint64_t pgaddr = pgalloc();
        added[count++]      = pgaddr;
        pml4t->entry[pml4e] = pgaddr | PF_PRESENT | PF_RW;
    }
    else if (pml4t->entry[pml4e] & PF_SYSTEM) {
        // A system page table should never be modified. This check is
        // performed only within the root PML4 table because checks on
        // lower level tables would be redundant.
        fatal();
    }

    page_t *pdpt = PGPTR(pml4t->entry[pml4e]);
    if (pdpt->entry[pdpte] == 0) {
        uint64_t pgaddr = pgalloc();
        added[count++]     = pgaddr;
        pdpt->entry[pdpte] = pgaddr | PF_PRESENT | PF_RW;
    }

    page_t *pdt = PGPTR(pdpt->entry[pdpte]);
    if (pdt->entry[pde] == 0) {
        uint64_t pgaddr = pgalloc();
        added[count++]  = pgaddr;
        pdt->entry[pde] = pgaddr | PF_PRESENT | PF_RW;
    }

    // Add the page table entry.
    page_t *ptt = PGPTR(pdt->entry[pde]);
    ptt->entry[pte] = paddr | pflags;

    // If adding the new entry required the page table to grow, make sure to
    // add the page table's new pages as well.
    for (int i = 0; i < count; i++) {
        add_pte(pt, pt->vnext, added[i], PF_PRESENT | PF_RW, CONTAINS_TABLE);
        pt->vnext += PAGE_SIZE;
    }
}

static uint64_t
remove_pte(pagetable_t *pt, uint64_t vaddr)
{
    // Decompose the virtual address into its hierarchical table components.
    uint32_t pml4e = PML4E(vaddr);
    uint32_t pdpte = PDPTE(vaddr);
    uint32_t pde   = PDE(vaddr);
    uint32_t pte   = PTE(vaddr);

    // Traverse the hierarchy, looking for the page.
    page_t *pml4t = (page_t *)pt->proot;
    page_t *pdpt  = PGPTR(pml4t->entry[pml4e]);
    page_t *pdt   = PGPTR(pdpt->entry[pdpte]);
    page_t *ptt   = PGPTR(pdt->entry[pde]);
    page_t *pg    = PGPTR(ptt->entry[pte]);

    // Clear the page table entry for the virtual address.
    ptt->entry[pte] = 0;

    // Invalidate the TLB entry for the page that was just removed.
    if (pt == active_pt)
        invalidate_page((void *)vaddr);

    // Return the physical address of the page table entry that was removed.
    return (uint64_t)pg;
}

void
pagetable_create(pagetable_t *pt, void *vaddr, uint64_t size)
{
    if (size % PAGE_SIZE != 0)
        fatal();

    // Allocate a page from the top level of the page table hierarchy.
    pt->proot = pgalloc();
    pt->vroot = (uint64_t)vaddr;
    pt->vnext = (uint64_t)vaddr + PAGE_SIZE;
    pt->vterm = (uint64_t)vaddr + size;

    // Install the kernel's page table into the created page table.
    page_t *src = (page_t *)kpt.proot;
    page_t *dst = (page_t *)pt->proot;
    for (int i = 0; i < 512; i++)
        dst->entry[i] = src->entry[i];
}

void
pagetable_destroy(pagetable_t *pt)
{
    if (pt->proot == 0)
        fatal();

    // Recursively destroy all pages starting from the PML4 table.
    pgfree_recurse((page_t *)pt->proot, 4);

    // Invalidate TLB entries of all table pages.
    if (pt == active_pt) {
        for (uint64_t vaddr = pt->vroot; vaddr < pt->vterm;
             vaddr += PAGE_SIZE) {
            invalidate_page((void *)vaddr);
        }
    }

    memzero(pt, sizeof(pagetable_t));
}

void
pagetable_activate(pagetable_t *pt)
{
    if (pt == NULL)
        pt = &kpt;
    if (pt->proot == 0)
        fatal();

    set_pagetable(pt->proot);
    active_pt = pt;
}

void *
page_alloc(pagetable_t *pt, void *vaddr_in, int count)
{
    for (uint64_t vaddr = (uint64_t)vaddr_in; count--; vaddr += PAGE_SIZE) {
        uint64_t paddr = pgalloc();
        add_pte(pt, vaddr, paddr, PF_PRESENT | PF_RW, 0);
    }
    return vaddr_in;
}

void
page_free(pagetable_t *pt, void *vaddr_in, int count)
{
    for (uint64_t vaddr = (uint64_t)vaddr_in; count--; vaddr += PAGE_SIZE) {
        uint64_t paddr = remove_pte(pt, vaddr);
        pgfree(paddr);
    }
}


text:
    * web.py
    * phantomJS (not bundled)
#####Note: No need to install dependencies manually, included within the package itself.

+ python server.py

```python
http://kartik.herokuapp.com/urltoimg?url=https://devcenter.heroku.com/articles/buildpacks
```

[A demo here](http://kartik.herokuapp.com/urltoimg?url=https://www.google.co.in/)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace VICTORVIS\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $security = $this->get('security.context');
        $user = $security->getToken()->getUser();

        return $this->render(
            'VICTORVISAdminBundle:Default:index.loggedIn.html.twig',
            compact('user')
        );
    }
}


text:
Sample Angular application for managing tasks stored in a SharePoint list.

![Angular todo application](../assets/angular-todo-preview.png)

## Solution

Solution|Author(s)
--------|---------
angular-todo|Waldek Mastykarz (MVP, Rencore, @waldekm)

## Version history

Version|Date|Comments
-------|----|--------
1.0.0|October 21, 2016|Initial release

## Disclaimer
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

---

## Minimal Path to Awesome

- create **Todo** list
  - in SharePoint site create a new list called `Todo`
  - in the **Todo** list add a new choice column called `Status`
    - as available choices enter (each value in new line): `Not started`, `In progress`, `Completed`
- configure application
  - in the **./app/app.config.js** file in the **sharepointApi** constant, update the URL of the site to match the server-relative URL of your site
- upload application
  - in SharePoint site open the **Shared Documents** library and create new folder called `Todo`
  - upload all application files and folders to the newly created **Todo** folder
- in the web browser navigate to the **index.aspx** page

## Features

This sample application illustrates the following concepts in Angular:

- building Angular applications in plain JavaScript
- styling Angular applications using ngOfficeUIFabric
- communicating with the SharePoint REST API in Angular applications
- using application constants for storing configuration values and using them across the application

![](https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/angular-todo/angular)


text:
#ifndef TextEncodingRegistry_h
#define TextEncodingRegistry_h

#include "wtf/PassOwnPtr.h"
#include "wtf/WTFExport.h"
#include "wtf/text/WTFString.h"
#include "wtf/unicode/Unicode.h"

namespace WTF {

class TextCodec;
class TextEncoding;

// Use TextResourceDecoder::decode to decode resources, since it handles BOMs.
// Use TextEncoding::encode to encode, since it takes care of normalization.
WTF_EXPORT PassOwnPtr<TextCodec> newTextCodec(const TextEncoding&);

// Only TextEncoding should use the following functions directly.
const char* atomicCanonicalTextEncodingName(const char* alias);
template <typename CharacterType>
const char* atomicCanonicalTextEncodingName(const CharacterType*, size_t);
const char* atomicCanonicalTextEncodingName(const String&);
bool noExtendedTextEncodingNameUsed();
bool isReplacementEncoding(const char* alias);
bool isReplacementEncoding(const String& alias);

#ifndef NDEBUG
void dumpTextEncodingNameMap();
#endif

} // namespace WTF

using WTF::newTextCodec;
using WTF::atomicCanonicalTextEncodingName;
using WTF::noExtendedTextEncodingNameUsed;
#ifndef NDEBUG
using WTF::dumpTextEncodingNameMap;
#endif

#endif // TextEncodingRegistry_h


text:
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.jps.builders.java.dependencyView;

import com.intellij.util.io.DataExternalizer;
import org.jetbrains.annotations.NotNull;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * @author Eugene Zhuravlev
 * Date: 04-Oct-17
 */
class ClassFileReprExternalizer implements DataExternalizer<ClassFileRepr> {

  private static final byte CLASS = 0x1;
  private static final byte MODULE = 0x2;
  private final DataExternalizer<ClassRepr> myClassReprExternalizer;
  private final DataExternalizer<ModuleRepr> myModuleReprExternalizer;

  public ClassFileReprExternalizer(DependencyContext context) {
    myClassReprExternalizer = ClassRepr.externalizer(context);
    myModuleReprExternalizer = ModuleRepr.externalizer(context);
  }

  public void save(@NotNull DataOutput out, ClassFileRepr value) throws IOException {
    if (value instanceof ClassRepr) {
      out.writeByte(CLASS);
      myClassReprExternalizer.save(out, (ClassRepr)value);
    }
    else {
      out.writeByte(MODULE);
      myModuleReprExternalizer.save(out, (ModuleRepr)value);
    }
  }

  public ClassFileRepr read(@NotNull DataInput in) throws IOException {
    return in.readByte() == CLASS ? myClassReprExternalizer.read(in) : myModuleReprExternalizer.read(in);
  }
}


text:
title: Infrastructure oVirt Instances
category: infra
authors: knesenko
wiki_title: Infrastructure oVirt Instances
wiki_revision_count: 1
wiki_last_updated: 2013-10-17
---

# Infrastructure oVirt Instances

## oVirt Instances
TBD: update info from PHX dc.


text:
<?php

namespace MediaAlchemyst;

use Neutron\TemporaryFilesystem\Manager;
use Neutron\TemporaryFilesystem\TemporaryFilesystem;
use Silex\Application;
use Silex\ServiceProviderInterface;
use Symfony\Component\Filesystem\Filesystem;

class MediaAlchemystServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['media-alchemyst.configuration'] = array();
        $app['media-alchemyst.logger'] = null;

        $app['media-alchemyst.drivers'] = $app->share(function (Application $app){
            $drivers = DriversContainer::create();
            $drivers['configuration'] = $app['media-alchemyst.configuration'];

            if (null !== $app['media-alchemyst.logger']) {
                $drivers['logger'] = $app['media-alchemyst.logger'];
            }

            return $drivers;
        });

        $app['media-alchemyst.filesystem-manager'] = $app->share(function (Application $app){
            return new Manager($app['media-alchemyst.temporary-filesystem'], $app['media-alchemyst.filesystem']);
        });

        $app['media-alchemyst.filesystem'] = $app->share(function (Application $app){
            return new Filesystem();
        });

        $app['media-alchemyst.temporary-filesystem'] = $app->share(function (Application $app){
            return new TemporaryFilesystem($app['media-alchemyst.filesystem']);
        });

        $app['media-alchemyst'] = $app->share(function(Application $app) {
            return new Alchemyst($app['media-alchemyst.drivers'], $app['media-alchemyst.filesystem-manager']);
        });
    }

    public function boot(Application $app)
    {
    }
}


text:
function ind=insider(x,y,xv,yv,tol);
% INSIDER  determines if points are inside/outside a polygon.
%         IND=INSIDER(X,Y,XV,YV) is a vector of flags corresponding to
%         the vector of points X,Y. If
%
%       -  X(i),Y(i) is outside the polygon XV,YV     : IND(i)=0
%       -  X(i),Y(i) is inside   "   "       "  "     : IND(i)=1
%       -  X(i),Y(i) is on an edge of the polygon     : IND(i)=2
%       -  X(i),Y(i) is a vertex of the polygon       : IND(i)=4
%
%         If a point falls into several categories, it is classified as
%         with the flag of greatest numerical value (i.e. a point on an
%         interior edge is given a flag value of 2).
%
%         XV,YV is an ordered list of polygon vertices. The last point
%         in the list (identical to the first point) may be omitted.
%         There is no restriction on the shape of the polygon.
%
%         IND=INSIDER(...,TOL) sets a tolerance for assigning points
%         to edges or vertices. (the default is 1e-6).

%RP (WHOI) 19/Dec/91
%   - this routine uses the fact that the sum of angles between
%     lines from a point to successive vertices of a polygon is 0
%     for a point outside the polygon, and +/- 2*pi for a point
%     inside. A point on an edge will have one such succesive angle
%     equal to +/- pi.
%RP (WHOI) 5/Dec/92
%   - some bulletproofing for really wierd checkerboard polygons and
%     single point "polygons".

if (nargin<5),
   tol=1e-6;
end;

% Put things into rows or columns...
x=x(:)';
y=y(:)';
xv=xv(:);
yv=yv(:);

NP=length(x);
NV=length(xv);

if (NP~=length(y)), error('Point x,y vectors of unequal length!'); end;
if (NV~=length(yv)), error('Polygon vertex x,y vectors of unequal length!');end;

   % If last point is missing append it

if ( (xv(NV) ~= xv(1)) | (yv(NV) ~= yv(1))),
   xv=[xv;xv(1)];
   yv=[yv;yv(1)];
   NV=NV+1;
end;

    % distances from points to vertices

dx=ones(NV,1)*x-xv*ones(1,NP);
dy=ones(NV,1)*y-yv*ones(1,NP);

    % If we have only 1 point in the polygon, we can only search
    % for matches to the "vertex". Otherwise we do all the tests.

if (NV==1),
   vertexpt=( abs(dx)<tol & abs(dy)<tol );
   ind=4*vertexpt;
else

        % Test for points at vertices

   vertexpt=any( abs(dx)<tol & abs(dy)<tol );

        % Compute angular intervals between vertex points. We shift
        % to put things in the range -pi<= ang <pi, with some slop for
        % possible edge points

   angs=rem( diff(atan2(dy,dx)) + 3*pi+tol , 2*pi ) - pi-tol;

        % If ang= -pi then we are on an edge

   edgept=any( abs(angs+pi)<tol );

        % If the angles sum to 0, 4*pi, etc., we are outside - if they
        % sum to  2*pi, 6*pi, etc. we are inside. This will result in a
        % "checkerboard" inside/outside classification when polygon
        % segments intersect.

   interiorpt=rem( abs(round( sum(angs)/(2*pi) )) , 2);

        % Classify points by priority

   ind=interiorpt;
   ind(edgept)=2*ones(sum(edgept),1);
   ind(vertexpt)=4*ones(sum(vertexpt),1);
end;


text:
package depauw.edu.myro.original;

import java.util.Random;

//import com.sun.speech.freetts.*; // for text-to-speech

/**
 * Miscellaneous methods for Myro/Java programs
 *
 * @author Douglas Harms
 * @version 1.0
 */
public class MyroUtils
{

    private static Random _randomSeq;
    private static boolean _newCountDown;
    private static long _startTime;
 //   private static Void _voice;

//    // static constructor
//    static
//    {
//        String VOICE_NAME = "kevin16";
//
//        // initialize random number sequence
//        _randomSeq = new Random();
//
//        // initialize timeRemaining
//        _newCountDown = true;
//
//        // initialize text-to-speach
//        VoiceManager voiceManager = VoiceManager.getInstance();
//        _voice = voiceManager.getVoice( VOICE_NAME );
//        _voice.allocate();
//    }

    /**
     * Cause the current thread to sleep for numSeconds.
     *
     * @pre numSeconds >= 0.0
     *
     * @param numSeconds The length of time to sleep.
     */
    public static void sleep( double numSeconds )
    {
        assert numSeconds >= 0.0 : "numSeconds must be >= 0.0";
        try
        {
            Thread.sleep( (int)(numSeconds * 1000.0) );
        } catch (InterruptedException e) {}

    }

    /**
     * Returns a random integer within a specified range.
     *
     * @pre low &lt= high
     *
     * @param low Low end of range
     * @param high High end of range
     * @return A uniformly distributed random int between low (inclusive) and high (inclusive)
     */
    public static int randomInt( int low, int high )
    {
        assert low <= high : "low cannot be greater than high";

        return _randomSeq.nextInt( high-low+1 ) + low ;
    }

    /**
     * Returns a random double in the range 0.0 (inclusive) and 1.0 (exclusive).
     *
     * @return A uniformly distributed random double between 0.0 (inclusive) and 1.0 (exclusive)
     */
    public static double randomDouble( )
    {
        return _randomSeq.nextDouble();
    }

    /**
     * Controls a while-loop for a specific number of seconds.
     *
     * @param seconds number of seconds to loop
     * @return true iff the specified number of seconds has not elapsed
     */
    public static boolean timeRemaining( double seconds )
    {
        if( _newCountDown )
        {
            _startTime = System.currentTimeMillis();
            _newCountDown = false;
        }

        if( System.currentTimeMillis() <= _startTime+seconds*1000 )
            return true;
        else
        {
            _newCountDown = true;
            return false;
        }
    }

//    /**
//     * Speak the passed string using the speach synthesizer.
//     *
//     * @param message The string to speak.
//     */
//    public static void speak( String message )
//    {
//        _voice.speak( message );
//    }

}


text:
package com.koch.ambeth.job;

public interface IJobExtendable {
	void registerJob(IJob job, String jobName, String cronPattern);

	void unregisterJob(IJob job, String jobName, String cronPattern);
}


text:
using System;
using NUnit.Framework;

namespace Mono.Debugging.Tests.Win32
{
	[TestFixture]
	[Platform (Include = "Win")]
	public class CorBreakpointsAndSteppingTests: BreakpointsAndSteppingTests
	{
		public CorBreakpointsAndSteppingTests () : base ("MonoDevelop.Debugger.Win32")
		{
		}
	}
}


text:
export default function() {
  return {
    setupMap: function(map) {
      map.setClickHandler(function(e, click, target) {
        if (map.unitManager.selected && map.unitManager.selected.length > 0) {
          target()
        } else {
          click()
        }
      })
    },
    setupUnitManager: function(unitManager) {
      unitManager.setClickHandler(function(e, click, target) {
        if (unitManager.selected && unitManager.selected.length > 0) {
          target()
        } else {
          click()
        }
      })
    }
  }
}


text:
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import OSM from '../src/ol/source/OSM.js';
import TileLayer from '../src/ol/layer/Tile.js';
import Vector from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
import WebGLPointsLayer from '../src/ol/layer/WebGLPoints.js';

const vectorSource = new Vector({
  url: 'data/geojson/world-cities.geojson',
  format: new GeoJSON(),
  wrapX: true,
});

const predefinedStyles = {
  'icons': {
    symbol: {
      symbolType: 'image',
      src: 'data/icon.png',
      size: [18, 28],
      color: 'lightyellow',
      rotateWithView: false,
      offset: [0, 9],
    },
  },
  'triangles': {
    symbol: {
      symbolType: 'triangle',
      size: 18,
      color: [
        'interpolate',
        ['linear'],
        ['get', 'population'],
        20000,
        '#5aca5b',
        300000,
        '#ff6a19',
      ],
      rotateWithView: true,
    },
  },
  'triangles-latitude': {
    symbol: {
      symbolType: 'triangle',
      size: [
        'interpolate',
        ['linear'],
        ['get', 'population'],
        40000,
        12,
        2000000,
        24,
      ],
      color: [
        'interpolate',
        ['linear'],
        ['get', 'latitude'],
        -60,
        '#ff14c3',
        -20,
        '#ff621d',
        20,
        '#ffed02',
        60,
        '#00ff67',
      ],
      offset: [0, 0],
      opacity: 0.95,
    },
  },
  'circles': {
    symbol: {
      symbolType: 'circle',
      size: [
        'interpolate',
        ['linear'],
        ['get', 'population'],
        40000,
        8,
        2000000,
        28,
      ],
      color: ['match', ['get', 'hover'], 1, '#ff3f3f', '#006688'],
      rotateWithView: false,
      offset: [0, 0],
      opacity: [
        'interpolate',
        ['linear'],
        ['get', 'population'],
        40000,
        0.6,
        2000000,
        0.92,
      ],
    },
  },
  'circles-zoom': {
    symbol: {
      symbolType: 'circle',
      size: ['interpolate', ['exponential', 2.5], ['zoom'], 2, 1, 14, 32],
      color: ['match', ['get', 'hover'], 1, '#ff3f3f', '#006688'],
      offset: [0, 0],
      opacity: 0.95,
    },
  },
  'rotating-bars': {
    symbol: {
      symbolType: 'square',
      rotation: ['*', ['time'], 0.1],
      size: [
        'array',
        4,
        [
          'interpolate',
          ['linear'],
          ['get', 'population'],
          20000,
          4,
          300000,
          28,
        ],
      ],
      color: [
        'interpolate',
        ['linear'],
        ['get', 'population'],
        20000,
        '#ffdc00',
        300000,
        '#ff5b19',
      ],
      offset: [
        'array',
        0,
        [
          'interpolate',
          ['linear'],
          ['get', 'population'],
          20000,
          2,
          300000,
          14,
        ],
      ],
    },
  },
};

const map = new Map({
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
  ],
  target: document.getElementById('map'),
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

let literalStyle;
let pointsLayer;

let selected = null;

map.on('pointermove', function (ev) {
  if (selected !== null) {
    selected.set('hover', 0);
    selected = null;
  }

  map.forEachFeatureAtPixel(ev.pixel, function (feature) {
    feature.set('hover', 1);
    selected = feature;
    return true;
  });
});

function refreshLayer(newStyle) {
  const previousLayer = pointsLayer;
  pointsLayer = new WebGLPointsLayer({
    source: vectorSource,
    style: newStyle,
  });
  map.addLayer(pointsLayer);

  if (previousLayer) {
    map.removeLayer(previousLayer);
    previousLayer.dispose();
  }
  literalStyle = newStyle;
}

const spanValid = document.getElementById('style-valid');
const spanInvalid = document.getElementById('style-invalid');
function setStyleStatus(errorMsg) {
  const isError = typeof errorMsg === 'string';
  spanValid.style.display = errorMsg === null ? 'initial' : 'none';
  spanInvalid.firstElementChild.innerText = isError ? errorMsg : '';
  spanInvalid.style.display = isError ? 'initial' : 'none';
}

const editor = document.getElementById('style-editor');
editor.addEventListener('input', function () {
  const textStyle = editor.value;
  try {
    const newLiteralStyle = JSON.parse(textStyle);
    if (JSON.stringify(newLiteralStyle) !== JSON.stringify(literalStyle)) {
      refreshLayer(newLiteralStyle);
    }
    setStyleStatus(null);
  } catch (e) {
    setStyleStatus(e.message);
  }
});

const select = document.getElementById('style-select');
select.value = 'circles';
function onSelectChange() {
  const style = select.value;
  const newLiteralStyle = predefinedStyles[style];
  editor.value = JSON.stringify(newLiteralStyle, null, 2);
  try {
    refreshLayer(newLiteralStyle);
    setStyleStatus();
  } catch (e) {
    setStyleStatus(e.message);
  }
}
onSelectChange();
select.addEventListener('change', onSelectChange);

// animate the map
function animate() {
  map.render();
  window.requestAnimationFrame(animate);
}
animate();


text:
package org.neo4j.ogm.annotation.typeconversion;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Vince Bickers
 * @author Gerrit Meier
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
public @interface EnumString {

    String TYPE = "value";

    Class<? extends Enum> value();

    /**
     * Toggle lenient conversion mode by setting this flag to true (defaults to false).
     * Has to be supported by the corresponding converter.
     * @return flag that represents the desired conversion mode.
     */
    boolean lenient() default false;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.fcrepo.camel</groupId>
    <artifactId>fcrepo-camel-toolbox</artifactId>
    <version>4.1.2-SNAPSHOT</version>
  </parent>

  <artifactId>fcrepo-indexing-solr-web</artifactId>
  <packaging>war</packaging>

  <name>Web-deployed Solr-based indexing system</name>
  <description>Camel-based solr indexer, deployable to web containers</description>

  <properties>
  </properties>

  <dependencies>

    <!-- Camel Dependencies -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-spring</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-http4</artifactId>
    </dependency>
    <dependency>
      <groupId>org.fcrepo.camel</groupId>
      <artifactId>fcrepo-camel</artifactId>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>fcrepo-indexing-solr</artifactId>
      <version>${project.version}</version>
    </dependency>

    <!-- Spring Web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
    </dependency>

    <!-- logging -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
    </dependency>

    <!-- testing -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-test-spring</artifactId>
    </dependency>
  </dependencies>

  <build>
    <defaultGoal>install</defaultGoal>

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
      </plugin>

    </plugins>
  </build>

</project>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../">
  <title data-ice="title">src/connector.js | API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

  Home

  Reference
  Source
  Test
  Repository

    <input class="search-input">

CTrelloConnector

Fpoll

src/connector.js

import logger from '@hoist/logger';
import config from 'config';
import Trello from 'node-trello';
import Bluebird from 'bluebird';
import url from 'url';
import {
  OAuthConnectorBase
}
from '@hoist/oauth-connector';
import {
  merge
}
from 'lodash';

let overrides = {
  requestTokenUri: 'https://trello.com/1/OAuthGetRequestToken',
  accessTokenUri: 'https://trello.com/1/OAuthGetAccessToken',
  authorizationUri: 'https://trello.com/1/OAuthAuthorizeToken',
  oauthVersion: '1.0'
}
let baseUri = {
  protocol: 'https',
  hostname: 'api.trello.com'
}

/*
 * The main class for connecting to Trello
 * @extends {OAuthConnectorBase}
 */
export default class TrelloConnector extends OAuthConnectorBase {

  /**
   * create a new TrelloConnector
   * @param {object} configuration - the configuration details for this connector
   * @param {string} configuration.apiKey - the trello API Key
   * @param {string} configuration.apiSecret - the trello API secret
   * @param {string} configuration.appName - the application name as it should show up to the user in Trello
   */
  constructor(configuration) {
    configuration.consumerKey = configuration.apiKey;
    configuration.consumerSecret = configuration.apiSecret;
    super(merge({}, configuration, overrides));
    this._logger = logger.child({
      cls: TrelloConnector
    });
  }
  _setupAuthorizationQuery(query) {
    query.name = this._configuration.appName;
    query.expiration = "never";
    query.scope = "read,write";
    return query;
  }

  get(path, urlArguments) {
    var uri = merge({}, {
      pathname: path,
      query: urlArguments
    }, baseUri);
    return this._performRequest('GET', url.format(uri), {}).then((result) => {
      return JSON.parse(result);
    });
  }
  post(path, body) {
    var uri = merge({}, {
      pathname: path
    }, baseUri);
    return this._performRequest('POST', url.format(uri), body || {}).then((result) => {
      return JSON.parse(result);
    });
  }
  put(path, body) {
    var uri = merge({}, {
      pathname: path
    }, baseUri);
    return this._performRequest('PUT', url.format(uri), body || {}).then((result) => {
      return JSON.parse(result);
    });
  }
  delete(path) {
    var uri = merge({}, {
      pathname: path
    }, baseUri);
    return this._performRequest('DELETE', url.format(uri)).then((result) => {
      return JSON.parse(result);
    });
  }
}

  Generated by ESDoc(0.4.6)


text:
package com.mvc.util.fusion;

/**
 * chart标签
 *
 * @author jobin
 */
public class Chart extends Attribute{
	/**
     * 主标题
     */
    private String caption;
    private String xAxisName;
    private String yAxisName;
    private String numberPrefix;
    private String showValues="0";
    private String showNames="1";
    private String palette="4";
    private String decimals="0";
    private String enableSmartLabels="1";
    private String enableRotation="0";
    private String bgAlpha="40,100";
    private String showBorder="0";
    private String showFCMenuItem="0";
    private String bgColor="99CCFF,FFFFFF";
    private String baseFont="Arial";
    private String baseFontSize="12";
    private String bgRatio="0,100";
    /**
     * 标题
     * @return
     */
    public String getCaption() {
		return caption;
	}
    /**
     * 标题
     * @param caption
     */
	public void setCaption(String caption) {
		this.caption = caption;
	}
	/**
	 * x轴名称
	 * @return
	 */
	public String getxAxisName() {
		return xAxisName;
	}
	/**
	 * x轴名称
	 * @param xAxisName
	 */
	public void setxAxisName(String xAxisName) {
		this.xAxisName = xAxisName;
	}
	/**
	 * y轴名称
	 * @return
	 */
	public String getyAxisName() {
		return yAxisName;
	}
	/**
	 * y轴名称
	 * @param yAxisName
	 */
	public void setyAxisName(String yAxisName) {
		this.yAxisName = yAxisName;
	}
	/**
	 * 增加数字前缀
	 * @return
	 */
	public String getNumberPrefix() {
		return numberPrefix;
	}
	/**
	 * 增加数字前缀
	 * @param numberPrefix
	 */
	public void setNumberPrefix(String numberPrefix) {
		this.numberPrefix = numberPrefix;
	}
	/**
	 * 是否显示对应的数据值,默认为1(True)
	 * @return
	 */
	public String getShowValues() {
		return showValues;
	}
	/**
	 * 是否显示对应的数据值,默认为1(True)
	 * @param showValues
	 */
	public void setShowValues(String showValues) {
		this.showValues = showValues;
	}
	/**
	 * 是否显示横向坐标轴(x轴)标签名称
	 * @return
	 */
	public String getShowNames() {
		return showNames;
	}
	/**
	 * 是否显示横向坐标轴(x轴)标签名称
	 * @param shownames
	 */
	public void setShowNames(String showNames) {
		this.showNames = showNames;
	}
	public String getPalette() {
		return palette;
	}
	public void setPalette(String palette) {
		this.palette = palette;
	}
	public String getDecimals() {
		return decimals;
	}
	public void setDecimals(String decimals) {
		this.decimals = decimals;
	}
	public String getEnableSmartLabels() {
		return enableSmartLabels;
	}
	public void setEnableSmartLabels(String enableSmartLabels) {
		this.enableSmartLabels = enableSmartLabels;
	}
	public String getEnableRotation() {
		return enableRotation;
	}
	public void setEnableRotation(String enableRotation) {
		this.enableRotation = enableRotation;
	}
	public String getBgAlpha() {
		return bgAlpha;
	}
	public void setBgAlpha(String bgAlpha) {
		this.bgAlpha = bgAlpha;
	}
	public String getShowBorder() {
		return showBorder;
	}
	public void setShowBorder(String showBorder) {
		this.showBorder = showBorder;
	}
	public String getShowFCMenuItem() {
		return showFCMenuItem;
	}
	public void setShowFCMenuItem(String showFCMenuItem) {
		this.showFCMenuItem = showFCMenuItem;
	}
	public Categories getCategories() {
		return categories;
	}
	public void setCategories(Categories categories) {
		this.categories = categories;
	}
	public String getBgColor() {
		return bgColor;
	}
	public void setBgColor(String bgColor) {
		this.bgColor = bgColor;
	}
	public String getBaseFont() {
		return baseFont;
	}
	public void setBaseFont(String baseFont) {
		this.baseFont = baseFont;
	}
	public String getBaseFontSize() {
		return baseFontSize;
	}
	public void setBaseFontSize(String baseFontSize) {
		this.baseFontSize = baseFontSize;
	}
	public String getBgRatio() {
		return bgRatio;
	}
	public void setBgRatio(String bgRatio) {
		this.bgRatio = bgRatio;
	}
	/**
     * Categories
     */
    private Categories categories=new Categories();
    public void addCategory(String... labels){
    	for(String label : labels){
    		Category category=new Category(label);
        	categories.add(category);
    	}
    }
    /**
     * Datasets
     */
    private Datasets datasets=new Datasets();
    public void addDataset(Dataset dataset){
    	datasets.add(dataset);
    }
    /**
     * Sets
     */
    private Sets sets=new Sets();
    public void addSet(String label,String value){
    	Set set=new Set(label,value);
    	addSet(set);
    }
    public void addSet(Set set){
    	sets.add(set);
    }
	@Override
	public String toString() {
		StringBuffer strings=new StringBuffer();
		strings.append("<?xml version=\"1.0\" encoding=\"GBK\"?>");
		strings.append("\n");
		strings.append("<chart");
		strings.append(this.getAttribute(this));
		strings.append(">");
		strings.append(categories.toString());
		strings.append(datasets.toString());
		strings.append(sets.toString());
		strings.append("</chart>");
		return strings.toString();
	}
}


text:
teamSite.controller('NavContoller', function($scope,$window,$location,$log) {

    $scope.navCloseSymbol = {};
    $scope.clearHeaderBackgroundTimeout = 0;
    $scope.hamburgerClosed = true;
    //this shouldn't be in here,
    //either this should be moved to a directive that incldues the hamburger menu and the overlay or needs to be split up into two dif controllers,
    // not sure the best approach but dom manipulation directly here is bad.

    $("#navigationOverlay li").on( {mouseenter: function() {
        $(this).addClass( "over" );
    }, mouseleave: function() {
        $(this).removeClass( "over" );
    }, click: function() {
        $scope.toggleMenu(true);
    }
    });

    $scope.toggleMenu = function(force) {

        var trigger = $('#hamburger');

        if ( force ) {
            this.hamburgerClosed = false;
        }

        if ( this.hamburgerClosed ) {

            trigger.removeClass('is-closed');
            trigger.addClass('is-open');

            this.hamburgerClosed  = false;

            $("#navigationOverlay").addClass("open");

        } else {

            trigger.removeClass('is-open');
            trigger.addClass('is-closed');

            this.hamburgerClosed = true;
            $("#navigationOverlay").removeClass("open");
        }

    };

    $scope.closeOverlay = function(){

        console.log("closeOverlay closed");
        $scope.toggleMenu(true);

    };

    $(window).on('mousewheel DOMMouseScroll scroll', function() {

        var header = $("header");

        clearTimeout($scope.clearHeaderBackgroundTimeout);
        $scope.clearHeaderBackgroundTimeout = setTimeout(function() {
            header.removeClass("isShowing");
        }, 2500 );

        if ( !header.hasClass("isShowing") ) {
            header.addClass("isShowing");
        }

    });

    $scope.$on("$destroy", function() {
    });
});


text:
package com.impossibl.postgres.protocol.ssl;

import com.impossibl.postgres.jdbc.PGSQLSimpleException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.sql.SQLException;
import java.util.Collection;

import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.x500.X500Principal;

/**
 * A Key manager that only loads the keys, if necessary.
 *
 */
public class OnDemandKeyManager extends X509ExtendedKeyManager {

  private X509Certificate[] certificates = null;
  private PrivateKey key = null;
  private String certfile;
  private String keyfileName;
  private CallbackHandler cbh;
  private boolean defaultfile;
  private PGSQLSimpleException error = null;

  /**
   * Constructor. certfile and keyfile can be null, in that case no certificate
   * is presented to the server.
   *
   * @param certfile
   * @param keyfile
   * @param cbh
   * @param defaultfile
   */
  public OnDemandKeyManager(String certfile, String keyfile, CallbackHandler cbh, boolean defaultfile) {
    this.certfile = certfile;
    this.keyfileName = keyfile;
    this.cbh = cbh;
    this.defaultfile = defaultfile;
  }

  /**
   * getCertificateChain and getPrivateKey cannot throw exeptions, therefore any
   * exception is stored in this.error and can be raised by this method
   *
   * @throws SQLException
   */
  public void throwKeyManagerException() throws SQLException {
    if (error != null)
      throw error;
  }

  @Override
  public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {

    if (certfile == null) {
      return null;
    }
    else {
      if (issuers == null || issuers.length == 0) {
        // Postgres 8.4 and earlier do not send the list of
        // accepted certificate authorities to the client. See BUG
        // #5468. We only hope, that our certificate will be accepted.
        return "user";
      }
      else {
        // Sending a wrong certificate makes the connection rejected, even,
        // if clientcert=0 in pg_hba.conf. therefore we only send our
        // certificate, if the issuer is listed in
        // issuers
        X509Certificate[] certchain = getCertificateChain("user");
        if (certchain == null) {
          return null;
        }
        else {
          X500Principal ourissuer = certchain[certchain.length - 1].getIssuerX500Principal();
          boolean found = false;
          for (int i = 0; i < issuers.length; i++) {
            if (ourissuer.equals(issuers[i])) {
              found = true;
            }
          }
          return (found ? "user" : null);
        }
      }
    }
  }

  @Override
  public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
    return null;
  }

  @Override
  public X509Certificate[] getCertificateChain(String alias) {

    // If certfile is null, we do not load the certificates
    if (certificates == null && certfile != null) {

      // The certificate must be loaded
      CertificateFactory cf;
      try {
        cf = CertificateFactory.getInstance("X.509");
      }
      catch (CertificateException ex) {
        error = new PGSQLSimpleException("Could not find a java cryptographic algorithm: X.509 CertificateFactory not available");
        return null;
      }

      Collection<? extends Certificate> certs;
      try {
        certs = cf.generateCertificates(new FileInputStream(certfile));
      }
      catch (FileNotFoundException ioex) {
        if (!defaultfile) {
          // It is not an error if there is no file at the default location
          error = new PGSQLSimpleException("Could not open SSL certificate file " + certfile, ioex);
        }
        return null;
      }
      catch (CertificateException gsex) {
        error = new PGSQLSimpleException("Loading the SSL certificate " + certfile + " into a KeyManager failed", gsex);
        return null;
      }

      certificates = certs.toArray(new X509Certificate[certs.size()]);
    }

    return certificates;
  }

  @Override
  public String[] getClientAliases(String keyType, Principal[] issuers) {
    String alias = chooseClientAlias(new String[] {keyType}, issuers, (Socket) null);
    return (alias == null ? new String[] {} : new String[] {alias});
  }

  @Override
  public PrivateKey getPrivateKey(String alias) {

    try {

      // If keyFileName is null, we do not load the key
      if (key == null && keyfileName != null) {

        // The private key must be loaded

        if (certificates == null) {
          // We need the certificate for the algorithm
          if (getCertificateChain("user") == null) {
            return null;
          }

        }

        byte[] keydata;

        File keyf = new File(keyfileName);
        try (FileInputStream fl = new FileInputStream(keyfileName)) {

          keydata = new byte[(int) keyf.length()];
          fl.read(keydata, 0, (int) keyf.length());

        }
        catch (FileNotFoundException ex) {
          if (!defaultfile) {
            // It is not an error if there is no file at the default location
            throw ex;
          }
          return null;
        }

        KeyFactory keyFactory = KeyFactory.getInstance(certificates[0].getPublicKey().getAlgorithm());
        try {
          KeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keydata);
          key = keyFactory.generatePrivate(pkcs8KeySpec);
        }
        catch (InvalidKeySpecException ex) {

          // The key might be password protected
          EncryptedPrivateKeyInfo ePKInfo = new EncryptedPrivateKeyInfo(keydata);
          Cipher cipher;
          try {
            cipher = Cipher.getInstance(ePKInfo.getAlgName());
          }
          catch (NoSuchPaddingException npex) {
            throw new NoSuchAlgorithmException(npex.getMessage(), npex);
          }

          // We call back for the password
          PasswordCallback pwdcb = new PasswordCallback("Enter SSL password:", false);
          try {
            cbh.handle(new Callback[] {pwdcb});
          }
          catch (UnsupportedCallbackException ucex) {
            error = new PGSQLSimpleException("Could not read password for SSL key file, console is not available", ucex);
            return null;
          }

          try {

            PBEKeySpec pbeKeySpec = new PBEKeySpec(pwdcb.getPassword());

            // Now create the Key from the PBEKeySpec
            SecretKeyFactory skFac = SecretKeyFactory.getInstance(ePKInfo.getAlgName());
            Key pbeKey = skFac.generateSecret(pbeKeySpec);

            // Extract the iteration count and the salt
            AlgorithmParameters algParams = ePKInfo.getAlgParameters();
            cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);

            // Decrypt the encryped private key into a PKCS8EncodedKeySpec
            KeySpec pkcs8KeySpec = ePKInfo.getKeySpec(cipher);
            key = keyFactory.generatePrivate(pkcs8KeySpec);
          }
          catch (GeneralSecurityException ikex) {
            error = new PGSQLSimpleException("Could not decrypt SSL key file " + keyfileName, ikex);
            return null;
          }
        }
      }
    }
    catch (IOException ioex) {
      error = new PGSQLSimpleException("Could not read SSL key file " + keyfileName, ioex);
    }
    catch (NoSuchAlgorithmException ex) {
      error = new PGSQLSimpleException("Could not find a java cryptographic algorithm: " + ex.getMessage(), ex);
      return null;
    }

    return key;
  }

  @Override
  public String[] getServerAliases(String keyType, Principal[] issuers) {
    return new String[] {};
  }

  @Override
  public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) {
    return chooseClientAlias(keyType, issuers, null);
  }

}


text: from .tsdataset import TSDataset


text:
"""
Normalizes Smart Fantasy Baseball's registry
"""

import datetime
import logging

from .models import Row

def normalize_sfbb(row):
    """Normalizes a single row of SFBB data

    Args:
        row: `dict`-ified row from SFBB spreadsheet

    Returns:
        Formatted model (`Model`)
    """

    log = logging.getLogger(__name__)

    model = Row()
    model.src = 'sfbb'
    model.name_last = row['LASTNAME']
    model.name_first = row['FIRSTNAME']
    model.name_full = row['PLAYERNAME']
    model.name_lfc = row['LASTCOMMAFIRST']

    if row['BIRTHDATE']:
        try:
            birth_date = datetime.datetime.strptime(row['BIRTHDATE'],
                                                    '%m/%d/%Y')
            model.birth_date = datetime.date(
                birth_date.year,
                birth_date.month,
                birth_date.day)
        except ValueError:
            log.exception('Invalid birth date for SFBB: %s %s',
                          row['IDPLAYER'],
                          row['BIRTHDATE'])

    model.bats = row['BATS']
    model.throws = row['THROWS']
    model.team = row['TEAM']
    model.lg = row['LG']
    model.pos = row['POS']

    fg_id = row['IDFANGRAPHS']

    if fg_id.startswith('sa'):
        model.key_fangraphs_minors = fg_id
    else:
        model.key_fangraphs = fg_id

    model.key_mlbam = row['MLBID']
    model.key_cbs = row['CBSID']
    model.key_retro = row['RETROID']
    model.key_bbref = row['BREFID']
    model.key_nfbc = row['NFBCID']
    model.key_espn = row['ESPNID']
    model.key_kffl = row['KFFLNAME']
    model.key_davenport = row['DAVENPORTID']
    model.key_bpro = row['BPID']
    model.key_yahoo = row['YAHOOID']
    model.key_rotowire = row['ROTOWIREID']
    model.key_fanduel = row['FANDUELID']
    model.key_ottoneu = row['OTTONEUID']

    return model


text:
import Browser from 'components/browser'

var assign = function(obj, source) {
  if (source) {
    for (var prop in source) {
      var propDescriptor = Object.getOwnPropertyDescriptor(source, prop)
      if (propDescriptor) {
        Object.defineProperty(obj, prop, propDescriptor)
      } else {
        obj[prop] = source[prop]
      }
    }
  }
  return obj
}

export function extend(parent, properties) {
  var constructor = function() {
    parent.prototype.constructor.apply(this, arguments)
    if (properties.constructor) {
      properties.constructor.apply(this, arguments)
    }
  }
  constructor.prototype = Object.create(parent.prototype)
  assign(constructor.prototype, properties)
  return constructor
}

export function formatTime(time) {
    if (!isFinite(time)) {
      return "--:--"
    }
    time = time * 1000
    time = parseInt(time/1000)
    var seconds = time % 60
    time = parseInt(time/60)
    var minutes = time % 60
    time = parseInt(time/60)
    var hours = time % 24
    var days = parseInt(time/24)
    var out = ""
    if (days && days > 0) {
      out += days + ":"
      if (hours < 1) out += "00:"
    }
    if (hours && hours > 0) out += ("0" + hours).slice(-2) + ":"
    out += ("0" + minutes).slice(-2) + ":"
    out += ("0" + seconds).slice(-2)
    return out.trim()
}

export var Fullscreen = {
  isFullscreen: function() {
    return (
      document.webkitFullscreenElement ||
      document.webkitIsFullScreen ||
      document.mozFullScreen ||
      !!document.msFullscreenElement
    )
  },
  requestFullscreen: function(el) {
    if(el.requestFullscreen) {
      el.requestFullscreen()
    } else if(el.webkitRequestFullscreen) {
      el.webkitRequestFullscreen()
    } else if(el.mozRequestFullScreen) {
      el.mozRequestFullScreen()
    } else if(el.msRequestFullscreen) {
      el.msRequestFullscreen()
    } else if (el.querySelector && el.querySelector("video") && el.querySelector("video").webkitEnterFullScreen) {
      el.querySelector("video").webkitEnterFullScreen()
    }
  },
  cancelFullscreen: function() {
    if(document.exitFullscreen) {
      document.exitFullscreen()
    } else if(document.webkitCancelFullScreen) {
      document.webkitCancelFullScreen()
    } else if(document.webkitExitFullscreen) {
      document.webkitExitFullscreen()
    } else if(document.mozCancelFullScreen) {
      document.mozCancelFullScreen()
    } else if(document.msExitFullscreen) {
      document.msExitFullscreen()
    }
  }
}

export class Config {

  static _defaultConfig() {
    return {
      volume: {
        value: 100,
        parse: parseInt
      }
    }
  }

  static _defaultValueFor(key) {
    try {
      return this._defaultConfig()[key]['parse'](this._defaultConfig()[key]['value'])
    } catch(e) {
      return undefined
    }
  }

  static _create_keyspace(key){
    return 'clappr.' + document.domain + '.' + key
  }

  static restore(key) {
    if (Browser.hasLocalstorage && localStorage[this._create_keyspace(key)]){
      return this._defaultConfig()[key]['parse'](localStorage[this._create_keyspace(key)])
    }
    return this._defaultValueFor(key)
  }

  static persist(key, value) {
    if (Browser.hasLocalstorage) {
      try {
        localStorage[this._create_keyspace(key)] = value
        return true
      } catch(e) {
        return false
      }
    }
  }
}

export function seekStringToSeconds(url) {
  var parts = url.match(/t=([0-9]*)(&|\/|$)/);
  if (parts && parts.length > 0) {
    return parseInt(parts[1], 10);
  } else {
    var seconds = 0;
    var factor = {'h': 3600, 'm': 60, 's': 1};
    parts = url.match(/[0-9]+[hms]+/g) || [];
    parts.forEach(function(el) {
      if (el) {
        var suffix = el[el.length - 1];
        var time = parseInt(el.slice(0, el.length - 1), 10);
        seconds += time * (factor[suffix]);
      }
    });
    return seconds;
   }
}

var idsCounter = {}

export function uniqueId(prefix) {
  idsCounter[prefix] || (idsCounter[prefix] = 0)
  var id = ++idsCounter[prefix]
  return prefix + id
}

export function isNumber(value) {
  return value - parseFloat(value) + 1 >= 0
}

export function currentScriptUrl() {
  var scripts = document.getElementsByTagName('script')
  return scripts[scripts.length - 1].src
}

export var requestAnimationFrame = (window.requestAnimationFrame ||
                            window.mozRequestAnimationFrame ||
                            window.webkitRequestAnimationFrame ||
                            function(fn) { window.setTimeout(fn, 1000/60) }).bind(window)

export var cancelAnimationFrame = (window.cancelAnimationFrame ||
                           window.mozCancelAnimationFrame ||
                           window.webkitCancelAnimationFrame ||
                           window.clearTimeout).bind(window)

export default {
  Config,
  Fullscreen,
  extend,
  formatTime,
  seekStringToSeconds,
  uniqueId,
  currentScriptUrl,
  isNumber,
  requestAnimationFrame,
  cancelAnimationFrame
}


text:
<?php
namespace Neos\Flow\I18n\EelHelper;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\I18n\Exception\IndexOutOfBoundsException;
use Neos\Flow\I18n\Exception\InvalidFormatPlaceholderException;
use Neos\Flow\I18n\Exception\InvalidLocaleIdentifierException;
use Neos\Flow\I18n\Locale;
use Neos\Flow\I18n\Translator;
use Neos\Flow\Exception as FlowException;
use Neos\Eel\ProtectedContextAwareInterface;

/**
 * Provides a chainable interface to collect all arguments needed to
 * translate messages using source message or key ID
 *
 * It also translates labels according to the configuration it stores
 */
class TranslationParameterToken implements ProtectedContextAwareInterface
{
    /**
     * @var Translator
     */
    protected $translator;

    /**
     * Key/Value store to keep the collected parameters
     *
     * @var array
     */
    protected $parameters = [];

    /**
     * @param string $id
     * @param string $value
     */
    public function __construct($id = null, $value = null)
    {
        if ($id !== null) {
            $this->parameters['id'] = $id;
        }

        if ($value !== null) {
            $this->parameters['value'] = $value;
        }
    }

    /**
     * Inject the translator into the token.
     * Used for testing.
     *
     * @param Translator $translator
     */
    public function injectTranslator(Translator $translator)
    {
        $this->translator = $translator;
    }

    /**
     * Set the id.
     *
     * @param string $id Id to use for finding translation (trans-unit id in XLIFF)
     * @return TranslationParameterToken
     */
    public function id($id)
    {
        $this->parameters['id'] = $id;
        return $this;
    }

    /**
     * Set the original translation value (the untranslated source string).
     *
     * @param string $value
     * @return TranslationParameterToken
     */
    public function value($value)
    {
        $this->parameters['value'] = $value;
        return $this;
    }

    /**
     * Set the arguments.
     *
     * @param array $arguments Numerically indexed array of values to be inserted into placeholders
     * @return TranslationParameterToken
     */
    public function arguments(array $arguments)
    {
        $this->parameters['arguments'] = $arguments;
        return $this;
    }

    /**
     * Set the source.
     *
     * @param string $source Name of file with translations
     * @return TranslationParameterToken
     */
    public function source($source)
    {
        $this->parameters['source'] = $source;
        return $this;
    }

    /**
     * Set the package.
     *
     * @param string $package Target package key. If not set, the current package key will be used
     * @return TranslationParameterToken
     */
    public function package($package)
    {
        $this->parameters['package'] = $package;
        return $this;
    }

    /**
     * Set the quantity.
     *
     * @param mixed $quantity A number to find plural form for (float or int), NULL to not use plural forms
     * @return TranslationParameterToken
     */
    public function quantity($quantity)
    {
        $this->parameters['quantity'] = $quantity;
        return $this;
    }

    /**
     * Set the locale.
     * The locale Identifier will be converted into a Locale
     *
     * @param string $locale An identifier of locale to use (NULL for use the default locale)
     * @return TranslationParameterToken
     * @throws FlowException
     */
    public function locale($locale)
    {
        try {
            $this->parameters['locale'] = new Locale($locale);
        } catch (InvalidLocaleIdentifierException $e) {
            throw new FlowException(sprintf('"%s" is not a valid locale identifier.', $locale), 1436784806);
        }

        return $this;
    }

    /**
     * Translate according to currently collected parameters
     *
     * @param array $overrides An associative array to override the collected parameters
     * @return string|null
     * @throws IndexOutOfBoundsException
     * @throws InvalidFormatPlaceholderException
     */
    public function translate(array $overrides = [])
    {
        array_replace_recursive($this->parameters, $overrides);

        $id = $this->parameters['id'] ?? null;
        $value = $this->parameters['value'] ?? '';
        $arguments = $this->parameters['arguments'] ?? [];
        $source = $this->parameters['source'] ?? 'Main';
        $package = $this->parameters['package'] ?? '';
        $quantity = $this->parameters['quantity'] ?? null;
        $locale = $this->parameters['locale'] ?? null;

        if ($id === null) {
            return $this->translator->translateByOriginalLabel($value, $arguments, $quantity, $locale, $source, $package);
        }

        $translation = $this->translator->translateById($id, $arguments, $quantity, $locale, $source, $package);
        if ($translation === null && $value !== null) {
            return $this->translator->translateByOriginalLabel($value, $arguments, $quantity, $locale, $source, $package);
        }

        return $translation;
    }

    /**
     * Runs translate to avoid the need of calling translate as a finishing method
     *
     * @return string
     */
    public function __toString()
    {
        return (string)$this->translate();
    }

    /**
     * All methods are considered safe
     *
     * @param string $methodName
     * @return boolean
     */
    public function allowsCallOfMethod($methodName)
    {
        return true;
    }
}


text:
package middleware

import (
	"net/http"

	"github.com/zenazn/goji/web"
)

type subrouter struct {
	c *web.C
	h http.Handler
}

func (s subrouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if s.c.URLParams != nil {
		if path, ok := s.c.URLParams["*"]; ok {
			oldpath := r.URL.Path
			r.URL.Path = path
			defer func() {
				r.URL.Path = oldpath
			}()
		}
	}
	s.h.ServeHTTP(w, r)
}

// SubRouter is a helper middleware that makes writing sub-routers easier.
//
// If you register a sub-router under a key like "/admin/*", Goji's router will
// automatically set c.URLParams["*"] to the unmatched path suffix. This
// middleware will help you set the request URL's Path to this unmatched suffix,
// allowing you to write sub-routers with no knowledge of what routes the parent
// router matches.
func SubRouter(c *web.C, h http.Handler) http.Handler {
	return subrouter{c, h}
}


text:
PHANTOMJS=/opt/decktape/phantomjs
DECKTAPE=/opt/decktape/decktape.js

%.pdf: presentation.md presentation.html style.css
	@$(PHANTOMJS) --ignore-ssl-errors=true $(DECKTAPE) remark presentation.html $@

slides: presentation.md presentation.html style.css
	@$(PHANTOMJS) --ignore-ssl-errors=true $(DECKTAPE) remark presentation.html slides.pdf


text:
<?php
/*
 * This class was auto-generated from the API references found at
 * https://epayments-api.developer-ingenico.com/s2sapi/v1/
 */
namespace Ingenico\Connect\Sdk\Domain\Payment\Definitions;

use UnexpectedValueException;

/**
 * @package Ingenico\Connect\Sdk\Domain\Payment\Definitions
 */
class ThreeDSecure extends AbstractThreeDSecure
{
    /**
     * @var ExternalCardholderAuthenticationData
     */
    public $externalCardholderAuthenticationData = null;

    /**
     * @var RedirectionData
     */
    public $redirectionData = null;

    /**
     * @return object
     */
    public function toObject()
    {
        $object = parent::toObject();
        if (!is_null($this->externalCardholderAuthenticationData)) {
            $object->externalCardholderAuthenticationData = $this->externalCardholderAuthenticationData->toObject();
        }
        if (!is_null($this->redirectionData)) {
            $object->redirectionData = $this->redirectionData->toObject();
        }
        return $object;
    }

    /**
     * @param object $object
     * @return $this
     * @throws UnexpectedValueException
     */
    public function fromObject($object)
    {
        parent::fromObject($object);
        if (property_exists($object, 'externalCardholderAuthenticationData')) {
            if (!is_object($object->externalCardholderAuthenticationData)) {
                throw new UnexpectedValueException('value \'' . print_r($object->externalCardholderAuthenticationData, true) . '\' is not an object');
            }
            $value = new ExternalCardholderAuthenticationData();
            $this->externalCardholderAuthenticationData = $value->fromObject($object->externalCardholderAuthenticationData);
        }
        if (property_exists($object, 'redirectionData')) {
            if (!is_object($object->redirectionData)) {
                throw new UnexpectedValueException('value \'' . print_r($object->redirectionData, true) . '\' is not an object');
            }
            $value = new RedirectionData();
            $this->redirectionData = $value->fromObject($object->redirectionData);
        }
        return $this;
    }
}


text:
namespace UnityApiPoc.Extension
{
    using System;
    using System.Collections.Generic;

    using Microsoft.Practices.Unity;
    using Microsoft.Practices.Unity.InterceptionExtension;

    public class UnityInterfaceInterceptionRegister : UnityContainerExtension
    {
        private List<Type> _interfaces = new List<Type>();

        private List<IInterceptionBehavior> _interceptionBehaviors = new List<IInterceptionBehavior>();

        public UnityInterfaceInterceptionRegister(Type interfaceType, IInterceptionBehavior behavior)
        {
            _interfaces.Add(interfaceType);
            _interceptionBehaviors.Add(behavior);
        }

        public UnityInterfaceInterceptionRegister(Type[] interfaces, IInterceptionBehavior[] behaviors)
        {
            _interfaces.AddRange(interfaces);
            _interceptionBehaviors.AddRange(behaviors);

            ValidateInterfaces(_interfaces);
        }

        protected override void Initialize()
        {
            Container.AddNewExtension<Interception>();

            Context.Registering += OnRegister;
        }

        private void ValidateInterfaces(List<Type> interfaces)
        {
            interfaces.ForEach(
                (i) =>
                    {
                        if (!i.IsInterface)
                        {
                            throw new ArgumentException("Only interfaces may be intercepted for interface interceptors.");
                        }
                    });
        }

        private bool ShouldIntercept(RegisterEventArgs e)
        {
            return e != null && e.TypeFrom != null && e.TypeFrom.IsInterface && _interfaces.Contains(e.TypeFrom);
        }

        private void OnRegister(object sender, RegisterEventArgs e)
        {
            if (ShouldIntercept(e))
            {
                var container = sender as IUnityContainer;

                var i = new Interceptor<InterfaceInterceptor>();
                i.AddPolicies(e.TypeFrom, e.TypeTo, e.Name, Context.Policies);

                _interceptionBehaviors.ForEach(
                    (b) =>
                        {
                            var interfaceBehavior = new InterceptionBehavior(b);
                            interfaceBehavior.AddPolicies(e.TypeFrom, e.TypeTo, e.Name, Context.Policies);
                        });
            }
        }
    }
}


text:
package gameover.fwk.ai

trait HComputeStrategy {
  def h(x: Int, y: Int, px: Int, py: Int, collisionDetector: CollisionDetector): Int
}


text:
Previous: Start/Stop Characters, Up: Special Characters   [Contents][Index]

17.4.9.4 Other Special Characters

Macro: int VLNEXT

This is the subscript for the LNEXT character in the special control
character array.  <var>termios</var>.c_cc[VLNEXT] holds the character
itself.

The LNEXT character is recognized only when IEXTEN is set, but in
both canonical and noncanonical mode.  It disables any special
significance of the next character the user types.  Even if the
character would normally perform some editing function or generate a
signal, it is read as a plain character.  This is the analogue of the
C-q command in Emacs.  “LNEXT” stands for “literal next.”

The LNEXT character is usually C-v.

This character is available on BSD systems and GNU/Linux and GNU/Hurd systems.

Macro: int VDISCARD

This is the subscript for the DISCARD character in the special control
character array.  <var>termios</var>.c_cc[VDISCARD] holds the character
itself.

The DISCARD character is recognized only when IEXTEN is set, but
in both canonical and noncanonical mode.  Its effect is to toggle the
discard-output flag.  When this flag is set, all program output is
discarded.  Setting the flag also discards all output currently in the
output buffer.  Typing any other character resets the flag.

This character is available on BSD systems and GNU/Linux and GNU/Hurd systems.

Macro: int VSTATUS

This is the subscript for the STATUS character in the special control
character array.  <var>termios</var>.c_cc[VSTATUS] holds the character
itself.

The STATUS character’s effect is to print out a status message about how
the current process is running.

The STATUS character is recognized only in canonical mode, and only if
NOKERNINFO is not set.

This character is available only on BSD systems and GNU/Hurd systems.

Previous: Start/Stop Characters, Up: Special Characters   [Contents][Index]


text:
/
   long getAvailCodeDE2() const;

   long getRSMEDE2x () const;

   long getRSMEDE2y () const;

   long getRSMEDE2z () const;

   /*!
    *  This code defines the sample size use
    *  to compute the accuracy, if 0 then the
    *  accuracy is estimated.
    */
   long getSampleSizeDE2() const;

   /*!
    *  1 = available
    *  2 = unavailable
    *  The code defines the availability of statics
    */
   long getAvailCodeDE5() const;

   long getRSMEDE5x () const;

   long getRSMEDE5y () const;

   long getRSMEDE5z () const;

   /*!
    *  This code defines the sample size use
    *  to compute the accuracy, if 0 then the
    *  accuracy is estimated.
    */
   long getSampleSizeDE5() const;

private:

   long _availCodeDE2;
   long _rsmeDE2x;
   long _rsmeDE2y;
   long _rsmeDE2z;
   long _sampleSizeDE2;
   long _availCodeDE5;
   long _rsmeDE5x;
   long _rsmeDE5y;
   long _rsmeDE5z;
   long _sampleSizeDE5;
};

#endif // #ifndef ossimDemStats_HEADER


text:
var logger = require('pomelo-logger').getLogger(__filename);
var area = require('../../../domain/area/area');

module.exports = function() {
	return new Filter();
};

var Filter = function() {
};

/**
 * Area filter
 */
Filter.prototype.before = function(msg, session, next){
	var player = area.getPlayer(session.get('playerId'));

	if(!player){
		var route = msg.__route__;

		if(route.search(/^area\.resourceHandler/i) == 0 || route.search(/enterScene$/i) >= 0){
			next();
			return;
		}else{
			next(new Error('No player exist!'));
			return;
		}
	}

	if(player.died){
		next(new Error("You can't move a dead man!!!"));
		return;
	}

	next();
};


text:
var helper = require("../helpers")
var request = require("request")
var Mailgun = function(keys) {
  this.name = "mailgun";
  this.keys = keys;
  this.validate = function(callback) {
    this.keyErrors = this.validateMailgunCall(this.keys);
    if (this.keyErrors.length != 0) {
      return callback(this.keyErrors, null);
    }
    request(this.getOptions(), function(err, result) {
      if (result.statusCode === 200) {
        return callback(null, result);
      } else {
        return callback(result, null);
      }
    });
  };
  this.validateMailgunCall = function(keys) {
    var schema = require('validate');
    var user = schema({
      api_key: {
        type: 'string',
        required: true,
        message: 'API USER IS REQUIRED'
      },
      domain: {
        type: 'string',
        required: true,
        match: /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/,
        message: 'DOMAIN IS IMPROPER FORMAT'
      },
    });
    return user.validate(keys)
  }
  this.getOptions = function() {
    url = 'https://api:'+ this.keys.api_key +'@api.mailgun.net/v3/'+ this.keys.domain +'/stats';
    var options = {
      url: url,
      method: 'GET'
    };
    return options;
  }
  return this;
};
module.exports = Mailgun;


text:
<?php

namespace PSR2R\Sniffs\WhiteSpace;

use PHP_CodeSniffer_File;

/**
 * Always have an extra new line at the beginning and end of a classy body.
 *
 * @author Mark Scherer
 * @license MIT
 */
class EmptyEnclosingLineSniff implements \PHP_CodeSniffer_Sniff {

	/**
	 * @inheritDoc
	 */
	public function register() {
		return [
			T_CLASS,
			T_INTERFACE,
			T_TRAIT,
		];
	}

	/**
	 * @inheritDoc
	 */
	public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) {
		$tokens = $phpcsFile->getTokens();
		$errorData = [strtolower($tokens[$stackPtr]['content'])];

		if (isset($tokens[$stackPtr]['scope_opener']) === false) {
			$error = 'Possible parse error: %s missing opening or closing brace';
			$phpcsFile->addWarning($error, $stackPtr, 'MissingBrace', $errorData);
			return;
		}

		$curlyBraceStartIndex = $tokens[$stackPtr]['scope_opener'];
		$curlyBraceEndIndex = $tokens[$stackPtr]['scope_closer'];

		$lastContentIndex = $phpcsFile->findPrevious(T_WHITESPACE, ($curlyBraceEndIndex - 1), $stackPtr, true);

		if ($lastContentIndex === $curlyBraceStartIndex) {
			// Single new line for empty classes
			if ($tokens[$curlyBraceEndIndex]['line'] === $tokens[$curlyBraceStartIndex]['line'] + 1) {
				return;
			}

			$error = 'Closing brace of an empty %s must have a single new line between curly brackets';

			$fix = $phpcsFile->addFixableError($error, $curlyBraceEndIndex, 'CloseBraceNewLine', $errorData);
			if ($fix === true) {
				if ($curlyBraceEndIndex - $curlyBraceStartIndex === 1) {
					$phpcsFile->fixer->addNewline($curlyBraceStartIndex);
				} else {
					$phpcsFile->fixer->replaceToken($curlyBraceStartIndex + 1, '');
					$phpcsFile->fixer->addNewline($curlyBraceStartIndex + 1);
				}
			}
			return;
		}

		$contentLine = $tokens[$lastContentIndex]['line'];
		$braceLine = $tokens[$curlyBraceEndIndex]['line'];

		if ($braceLine !== $contentLine + 2) {
			$phpcsFile->recordMetric($stackPtr, 'Class closing brace placement', 'lines');
			$error = 'Closing brace of a %s must have a new line between itself and the last content.';

			$fix = $phpcsFile->addFixableError($error, $curlyBraceEndIndex, 'CloseBraceNewLine', $errorData);
			if ($fix === true) {
				if ($braceLine < $contentLine + 2) {
					$phpcsFile->fixer->addNewlineBefore($curlyBraceEndIndex);
				} else {
					$phpcsFile->fixer->replaceToken($curlyBraceEndIndex - 1, '');
				}
			}
		}
	}

}


text:
package com.strobel.decompiler.languages.java.ast;

import com.strobel.core.VerifyArgument;
import com.strobel.decompiler.languages.TextLocation;
import com.strobel.decompiler.languages.java.JavaFormattingOptions;
import com.strobel.decompiler.patterns.INode;
import com.strobel.decompiler.patterns.Match;
import com.strobel.decompiler.patterns.Role;

public class JavaTokenNode extends AstNode {
    private TextLocation _startLocation;

    public JavaTokenNode(final TextLocation startLocation) {
        _startLocation = VerifyArgument.notNull(startLocation, "startLocation");
    }

    public TextLocation getStartLocation() {
        return _startLocation;
    }

    public void setStartLocation(final TextLocation startLocation) {
        _startLocation = startLocation;
    }

    public TextLocation getEndLocation() {
        return new TextLocation(_startLocation.line(), _startLocation.column() + getTokenLength());
    }

    @Override
    public String getText(final JavaFormattingOptions options) {
        final Role role = getRole();

        if (role instanceof TokenRole) {
            return ((TokenRole) role).getToken();
        }

        return null;
    }

    protected int getTokenLength() {
        final Role<?> role = getRole();

        if (role instanceof TokenRole) {
            return ((TokenRole) role).getLength();
        }

        return 0;
    }

    // <editor-fold defaultstate="collapsed" desc="Null JavaTokenNode">

    public final static JavaTokenNode NULL = new NullJavaTokenNode();

    private static final class NullJavaTokenNode extends JavaTokenNode {
        public NullJavaTokenNode() {
            super(TextLocation.EMPTY);
        }

        @Override
        public final boolean isNull() {
            return true;
        }

        @Override
        public <T, R> R acceptVisitor(final IAstVisitor<? super T, ? extends R> visitor, final T data) {
            return null;
        }

        @Override
        public boolean matches(final INode other, final Match match) {
            return other == null || other.isNull();
        }
    }

    // </editor-fold>

    @Override
    @SuppressWarnings("unchecked")
    public Role<? extends JavaTokenNode> getRole() {
        return (Role<? extends JavaTokenNode>) super.getRole();
    }

    @Override
    public <T, R> R acceptVisitor(final IAstVisitor<? super T, ? extends R> visitor, final T data) {
        return visitor.visitJavaTokenNode(this, data);
    }

    @Override
    public NodeType getNodeType() {
        return NodeType.TOKEN;
    }

    @Override
    public boolean matches(final INode other, final Match match) {
        return other instanceof JavaTokenNode &&
               !other.isNull() &&
               !(other instanceof JavaModifierToken);
    }

    @Override
    public String toString() {
        return String.format(
            "[JavaTokenNode: StartLocation=%s, EndLocation=%s, Role=%s]",
            getStartLocation(),
            getEndLocation(),
            getRole()
        );
    }
}


text:
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor.FileDescriptor(
  name='POGOProtos/Data/Player/PlayerCurrency.proto',
  package='POGOProtos.Data.Player',
  syntax='proto3',
  serialized_pb=_b('\n+POGOProtos/Data/Player/PlayerCurrency.proto\x12\x16POGOProtos.Data.Player\"\x1e\n\x0ePlayerCurrency\x12\x0c\n\x04gems\x18\x01 \x01(\x05\x62\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

_PLAYERCURRENCY = _descriptor.Descriptor(
  name='PlayerCurrency',
  full_name='POGOProtos.Data.Player.PlayerCurrency',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='gems', full_name='POGOProtos.Data.Player.PlayerCurrency.gems', index=0,
      number=1, type=5, cpp_type=1, label=1,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  syntax='proto3',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=71,
  serialized_end=101,
)

DESCRIPTOR.message_types_by_name['PlayerCurrency'] = _PLAYERCURRENCY

PlayerCurrency = _reflection.GeneratedProtocolMessageType('PlayerCurrency', (_message.Message,), dict(
  DESCRIPTOR = _PLAYERCURRENCY,
  __module__ = 'POGOProtos.Data.Player.PlayerCurrency_pb2'
  # @@protoc_insertion_point(class_scope:POGOProtos.Data.Player.PlayerCurrency)
  ))
_sym_db.RegisterMessage(PlayerCurrency)

# @@protoc_insertion_point(module_scope)


text:
extern void _init_charlock_encoding_detector();
extern void _init_charlock_converter();
extern void _init_charlock_transliterator();

VALUE rb_mCharlockHolmes;

void Init_charlock_holmes() {
	rb_mCharlockHolmes = rb_define_module("CharlockHolmes");

	_init_charlock_encoding_detector();
	_init_charlock_converter();
	_init_charlock_transliterator();
}


text:
package spock.util.mop;

import java.lang.annotation.*;

import org.spockframework.runtime.extension.ExtensionAnnotation;
import org.spockframework.runtime.extension.builtin.ConfineMetaClassChangesExtension;

/**
 * Confines any changes made to the meta classes of the specified classes to the
 * annotated scope. This is done by installing new meta classes when the scope is
 * entered, and restoring the previously installed meta classes when the scope is
 * left. Note that this only works reliably as long as spec execution is
 * single-threaded.
 *
 *
If a spec class is annotated, the meta classes are restored to as they
 * were before <tt>setupSpec()</tt> was executed, after <tt>cleanupSpec</tt>
 * was executed.
 *
 *
If a feature method is annotated, the meta classes are restored to as they
 * were after <tt>setup()</tt> was executed, before <tt>cleanup() is executed.
 * For a data-driven feature method, meta classes are restored after each iteration.
 *
 * @author Luke Daley
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@ExtensionAnnotation(ConfineMetaClassChangesExtension.class)
public @interface ConfineMetaClassChanges {
  /**
   * The classes whose meta class changes are to be confined.
   */
  Class<?>[] value();
}


text:
  <button type="button" class="close" ng-click="$dismiss()" aria-label="Close">
    ×
  </button>

Stop Messages To {{participant.nickname}}

Start Messages To {{participant.nickname}}

<form name="stopMessageForm" class="form-horizontal" >

      Reason

      <textarea name="reason" ng-model="form.reason" placeholder="Reason..."
        class="form-control" ng-required="!(participant.status == 'sae' || participant.status == 'loss')" rows="5" cols="25"></textarea>

      SAE

        <input type="checkbox" ng-model="form.sae" name="sae" ng-disabled="participant.status == 'sae' || participant.status == 'loss'"/>

      SAE Date

          <input name="loss_date" ng-model="form.loss_date" type="text" class="form-control" ng-disabled="participant.status == 'sae' || participant.status == 'loss'"
               datepicker-popup is-open="loss_date_open" ng-required="form.sae" max-date="today">

           <button type="button" class="btn btn-default" ng-click="loss_date_open = !loss_date_open" ng-disabled="participant.status == 'sae' || participant.status == 'loss'">

          </button>

      Continue Messaging

        Yes
        No

</form>

  <button class="btn btn-primary" ng-disabled="stopMessageForm.$invalid || stopMessageForm.$pristine" ng-click="$close(form)">
    Stop Messaging
    Start Messaging
    Change Messaging
  </button>
  <button class="btn btn-default" ng-click="$dismiss()">Cancel</button>


text:
'use strict';

angular.module('videostoreApp')
    .factory('Movie', function ($resource, DateUtils) {
        return $resource('api/movies/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': {
                method: 'GET',
                transformResponse: function (data) {
                    data = angular.fromJson(data);
                    data.releasedDate = DateUtils.convertDateTimeFromServer(data.releasedDate);
                    return data;
                }
            },
            'update': { method:'PUT' }
        });
    });


text:
<?xml version="1.0"?>
<project name="org.bridgedb.tools.benchmarking" default="jar" basedir=".">

	<import file="../build-common.xml" />

	<path id="absolute.deps">
		<fileset dir="${bundle.dest}">
			<include name="org.bridgedb.jar"/>
			<include name="org.bridgedb.bio.jar"/>
			<include name="org.bridgedb.server.jar"/>
			<include name="derby.jar"/>
		</fileset>
		<fileset dir="../common-bundles">
			<include name="com.google.collect*.jar"/>
		</fileset>
	</path>

	<path id="test.deps">
		<pathelement location="../corelib/build-lib/junit.jar"/>
		<pathelement location="../corelib/build-lib/measure.jar"/>
		<pathelement location="../corelib/build-lib/derbyclient.jar"/>
	</path>

</project>


text:
package org.hl7.rim;

import org.hl7.rim.Role;
import org.hl7.types.CD;
import org.hl7.types.PQ;

import /*org.hl7.rim.AssociationSet*/java.util.List;

/**
A role played by a device when the device is used to administer therapeutic agents (medication and vital elements) into the
   body, or to drain material (e.g., exudates, pus, urine, air, blood) out of the body.

Discussion: In general, Access is a Role of a ManufacturedMaterial or Device, something specifically manufactured or created to serve
   that purpose, such as a catheter or cannula inserted into a compartment of the body.

Devices in the role of an Access are typically used in intake/outflow observations, and in medication routing instructions.
   Microbiologic observations on the material itself or on fluids coming out of a drain, are also common.

Rationale: The Access role primarily exists in order to describe material actually deployed as an access, and not so much the fresh
   material as it comes from the manufacturer. For example, in supply ordering a box of catheters from a distributor, it is not
   necessary to use the Access role class, since the material attributes will usually suffice to describe and identify the product
   for the order. But the Access role is used to communicate about the maintenance, intake/outflow, and due replacement of tubes
   and drains.

*/
public interface Access extends org.hl7.rim.Role {

  /**
A coded specification of the anatomic site where the Access (cannula, line or drain) first enters the body and, if applicable,
   a routing from the first entrance to the target site.

Examples: For example an arteria pulmonalis catheter targets a pulmonary artery but the access approach site is typically the vena
   carotis interna at the neck, or the vena subclavia at the fossa subclavia.

Constraints: The coding system is the same as for Procedure.approachSiteCode; indeed the Access.approachSiteCode has been copied from
   the Procedure class into the Access role class. The value of the Access.approachSiteCode should be identical to the value
   of the Procedure.approachSiteCode of an associated access placement procedure.

Rationale: Since accesses are typically placed for a considerable period of time and since the access is used as a resource of many
   acts, the access approach site becomes an important identifying attribute of the access itself (as opposed to merely being
   an attribute of the placement procedure).

  */
  CD getApproachSiteCode();
  /** Sets the property approachSiteCode.
      @see #getApproachSiteCode
  */
  void setApproachSiteCode(CD approachSiteCode);

  /**
A coded specification of the site or body compartment into which access is being provided, i.e., the compartment into which
   material is administered or from which it is collected.

Examples: For example, a pulmonary artery catheter will have the target site "arteria pulmonalis".

Constraints: The coding system is the same as for Procedure.targetSiteCode; indeed the Access.targetSiteCode has been copied from the
   Procedure class into the Access role class. The value of the Access.targetSiteCode should be identical to the value of the
   Procedure.targetSiteCode of an associated access placement procedure.

Rationale: Since accesses are typically placed for a considerable period of time and since the access is used as a resource of many
   acts, the target site becomes an important identifying attribute of the access itself (as opposed to merely being an attribute
   of the placement procedure). The target site is important information that determines what kinds of substances may or may
   not be administered (e.g., special care to avoid medication injections into an arterial access).

  */
  CD getTargetSiteCode();
  /** Sets the property targetSiteCode.
      @see #getTargetSiteCode
  */
  void setTargetSiteCode(CD targetSiteCode);

  /**
A measure for the inner diameter of the Access (e.g. the lumen of the tube).

  */
  PQ getGaugeQuantity();
  /** Sets the property gaugeQuantity.
      @see #getGaugeQuantity
  */
  void setGaugeQuantity(PQ gaugeQuantity);
}


text:
@extends('layout')

@section('content')

        @if (isset($from) && ($from != null))

 Bienvenue dans la procedure de changement d'équipe

        @else

 Bienvenue {{ Auth::user()->first_name }} dans les Joutes du CPNV

        @endif

        @if ($toFinish == null)

Vous êtes obligés de vous inscrire à un tournoi. Il est également nécessaire d'avoir ou de rejoindre une équipe

Veuillez terminer votre inscription en utilisant le formulaire ci-dessous.

        @else
            @if ($toFinish == "requiredMorning")

ATTENTION! Il ne vous reste plus qu'à choisir une équipe pour le matin

            @endif
            @if ($toFinish == "requiredAfternoon")

ATTENTION! Il ne vous reste plus qu'à choisir une equipe pour l'après-midi

            @endif
        @endif

        @if (isset($error))

{{$error}}

        @endif

        {{ Form::open(array('url' => route('profile.store'), 'method' => 'post', 'id' => 'formProfile')) }}

            {{ Form::label('event', 'Evénements disponbles') }}
            {{ Form::select('event', $dropdownListEvent, null, ['placeholder' => 'Sélectionner', 'class' => 'form-control allSameStyle', 'id' => 'event']) }}

            {{ Form::label('tournament', 'Tournois disponibles') }}
            {{ Form::select('tournament', [], null, ['placeholder' => 'Sélectionner', 'class' => 'form-control allSameStyle', 'id' => 'tournament', 'disabled' => 'disabled']) }}

            {{ Form::label('teamSelected', 'Equipes disponibles') }}

            {{ Form::select('teamSelected', [], null, ['placeholder' => 'Sélectionner', 'class' => 'form-control allSameStyle', 'id' => 'teamSelected', 'disabled' => 'disabled']) }}

            {{ Form::checkbox('switch', 1, false, ['class' => 'switch', "id"=>'switch', 'disabled' => 'disabled']) }} Je veux créer une equipe

            {{ Form::label('teamNew', 'Nom de l\'équipe') }}

            {{ Form::text('teamNew', null,['class' => 'form-control', 'disabled' => 'disabled', 'id' => 'teamNew']) }}

            {{ Form::text('toFinish', $toFinish, ['id' => 'toFinish']) }}

{{ Form::button('Terminer', array('class' => 'btn btn-success', 'disabled' => 'disabled', 'id' => 'formValidate')) }}

        {{ Form::close() }}

        {{ Form::open(array('url' => route('profile.destroy', Auth::user()->id), 'method' => 'delete')) }}
            <button class="btn btn-success  button-delete"  data-type="participantSigin">Reset</button>
        {{ Form::close() }}

@stop