text:
//---------------------------------------------------------------------
// <copyright file="AssociationEnd.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.Contracts.EntityModel
{
    using System.Collections;

    /// <summary>
    /// Association (type) End
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "IEnumerable is just for easy construction. Type is not really a collection")]
    public class AssociationEnd : AnnotatedItem, IEnumerable
    {
        /// <summary>
        /// Initializes a new instance of the AssociationEnd class without a RoleName.
        /// </summary>
        public AssociationEnd()
            : this(null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the AssociationEnd class with a given RoleName.
        /// </summary>
        /// <param name="roleName">The RoleName for the association end</param>
        public AssociationEnd(string roleName)
        {
            this.RoleName = roleName;
            this.DeleteBehavior = OperationAction.None;
        }

        /// <summary>
        /// Initializes a new instance of the AssociationEnd class with a given RoleName, EntityType, and multiplicity
        /// </summary>
        /// <param name="roleName">The RoleName for the association end</param>
        /// <param name="type">The EntityType this association end refers to</param>
        /// <param name="multiplicity">Mulitipliciy of this association end</param>
        public AssociationEnd(string roleName, EntityType type, EndMultiplicity multiplicity)
            : this(roleName)
        {
            this.EntityType = type;
            this.Multiplicity = multiplicity;
        }

        /// <summary>
        /// Initializes a new instance of the AssociationEnd class with a given RoleName, EntityType, multiplicity and OnDeleteAction
        /// </summary>
        /// <param name="roleName">The RoleName for the association end</param>
        /// <param name="type">The EntityType this association end refers to</param>
        /// <param name="multiplicity">Mulitipliciy of this association end</param>
        /// <param name="onDeleteAction">OnDelete value</param>
        public AssociationEnd(string roleName, EntityType type, EndMultiplicity multiplicity, OperationAction onDeleteAction)
            : this(roleName, type, multiplicity)
        {
            this.DeleteBehavior = onDeleteAction;
        }

        /// <summary>
        /// Gets or sets the role name of the association end.
        /// </summary>
        public string RoleName { get; set; }

        /// <summary>
        /// Gets or sets the EntityType of this association end.
        /// </summary>
        public EntityType EntityType { get; set; }

        /// <summary>
        /// Gets or sets the Multiplicity of this association end.
        /// </summary>
        public EndMultiplicity Multiplicity { get; set; }

        /// <summary>
        /// Gets or sets the OnDeleteAction Value of this association end.
        /// </summary>
        public OperationAction DeleteBehavior { get; set; }

        /// <summary>
        /// Performs an implicit conversion from <see cref="System.String"/> to <see cref="Microsoft.Test.Taupo.Contracts.EntityModel.AssociationEnd"/>.
        /// </summary>
        /// <param name="roleName">Name of the role.</param>
        /// <returns>The result of the conversion.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Not needed here.")]
        public static implicit operator AssociationEnd(string roleName)
        {
            return new AssociationEndReference(roleName);
        }
    }
}


text:
import itk

# To verify that the lazy loading system works, we try to load
# a float image (declared in the module ITKCommon)
image = itk.Image.F3
image = itk.Image[itk.F, 3]
# And a normal band image (declared in the module LevelSets)
image = itk.Image.NBNIF33
image = itk.Image[itk.NormalBandNode.IF3, 3]
# The function __dir__ is overridden to load modules that
# were not loaded by the lazy loading system
itk.Image.__dir__()

redpajama_set_name: RedPajamaGithub


text:
package com.minecraftmarket.minecraftmarket.common.api.models;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Item {
    private final long id;
    private final String name;
    private final String description;
    private final String icon;
    private final String url;
    private final String price;
    private final String sale_price;
    private final long order;

    @JsonCreator
    public Item(@JsonProperty("id") long id,
                @JsonProperty("name") String name,
                @JsonProperty("gui_description") String description,
                @JsonProperty("gui_icon") String icon,
                @JsonProperty("gui_url") String url,
                @JsonProperty("price") String price,
                @JsonProperty("sale_price") String sale_price,
                @JsonProperty("order") long order) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.icon = icon;
        this.url = url;
        this.price = price;
        this.sale_price = sale_price;
        this.order = order;
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public String getIcon() {
        return icon;
    }

    public String getUrl() {
        return url;
    }

    public String getPrice() {
        return price;
    }

    public String getSalePrice() {
        return sale_price;
    }

    public boolean hasSale(){
    	return !price.equals(sale_price);
    }

    public long getOrder() {
        return order;
    }

    @Override
    public String toString() {
        return "ID='" + getId() + "' " +
                "Name='" + getName() + "' " +
                "Description='" + getDescription() + "' " +
                "Icon='" + getIcon() + "' " +
                "Url='" + getUrl() + "' " +
                "Price='" + getPrice() + "' " +
                "Order='" + getOrder() + "'";
    }
}


text:
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#ifndef RUST_CRATE_MAP_H
#define RUST_CRATE_MAP_H

#include "rust_log.h"
#include <stdint.h>

struct mod_entry {
    const char* name;
    uint32_t* state;
};

class cratemap;

class cratemap_v0 {
    friend class cratemap;
    const mod_entry *m_entries;
    const cratemap* m_children[1];
};

class cratemap {
private:
    int32_t m_version;
    const void *m_annihilate_fn;
    const mod_entry* m_entries;
    const cratemap* m_children[1];

    inline int32_t version() const {
        switch (m_version) {
        case 1:     return 1;
        default:    return 0;
        }
    }

public:
    typedef const cratemap *const *iterator;

    inline const void *annihilate_fn() const {
        switch (version()) {
        case 0: return NULL;
        case 1: return m_annihilate_fn;
        default: assert(false && "Unknown crate map version!");
            return NULL; // Appease -Werror=return-type
        }
    }

    inline const mod_entry *entries() const {
        switch (version()) {
        case 0: return reinterpret_cast<const cratemap_v0 *>(this)->m_entries;
        case 1: return m_entries;
        default: assert(false && "Unknown crate map version!");
            return NULL; // Appease -Werror=return-type
        }
    }

    inline const iterator begin() const {
        switch (version()) {
        case 0:
            return &reinterpret_cast<const cratemap_v0 *>(this)->
                m_children[0];
        case 1:
            return &m_children[1];
        default: assert(false && "Unknown crate map version!");
            return NULL; // Appease -Werror=return-type
        }
    }

    inline const iterator end() const {
        iterator i = begin();
        while (*i)
            i++;
        return i;
    }
};

void iter_module_map(const mod_entry* map,
                     void (*fn)(const mod_entry* entry, void *cookie),
                     void *cookie);

void iter_crate_map(const cratemap* map,
                    void (*fn)(const mod_entry* entry, void *cookie),
                    void *cookie);

//
// Local Variables:
// mode: C++
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//

#endif /* RUST_CRATE_MAP_H */


text:
/*

# Spoofing MMSI

*query-version: 3*

List of MMSIs that experience substantial ID spoofing

By ID spoofing, we mean two or more vessels that are using the same MMSI at the same time.

All the messages for an MMSI are grouped into sets of tracks that are contiguous spatially and temporally.
Each continuous track has a unique seg_id field added.  Some tracks contain invalid lan/lon (like 91, 181) and
are put into a special 'BAD' segment.

The test for spoofing is fairly naive - we simple compute the extent of each segment in time, add them all up,
and compare that to the extent of time that the vessel is active.  If the segment time is longer than the
active time, then we know that some of the segments must overlap, and this is the indication of ID spoofing.

## Query:

*/
select mmsi from
(
SELECT
  a.mmsi AS mmsi,
  active_days,
  message_count,
  total_days,
  segment_count,
  segment_days,
  segment_days / LEAST(total_days, float(active_days)) AS spoof_ratio,
  segment_days - LEAST(total_days, float(active_days)) AS overlap_days,
  (segment_days - LEAST(total_days, float(active_days))) / LEAST(total_days, float(active_days)) AS spoof_percent,
  (segment_days / LEAST(total_days, float(active_days))) * (segment_days - LEAST(total_days, float(active_days))) as spoof_factor
FROM (
  SELECT
    mmsi,
    COUNT(*) AS active_days,
    SUM(message_count) AS message_count,
    (MAX(max_timestamp) - MIN(min_timestamp)) / 86400 AS total_days
  FROM (
    SELECT
      mmsi,
      UTC_USEC_TO_DAY(timestamp) AS day,
      COUNT(*) message_count,
      MIN(TIMESTAMP_TO_SEC(timestamp)) AS min_timestamp,
      MAX(TIMESTAMP_TO_SEC(timestamp)) AS max_timestamp
    FROM (TABLE_DATE_RANGE([{classify_table_name}], TIMESTAMP('{start_date}'), TIMESTAMP('{end_date}')))
    WHERE
      RIGHT(seg_id, 3) != 'BAD'
      AND data_source IS NULL
    GROUP BY
      mmsi,
      day )
  GROUP BY
    mmsi ) a
JOIN (
  SELECT
    mmsi,
    COUNT(*) segment_count,
    SUM(max_timestamp - min_timestamp) / 86400 AS segment_days
  FROM (
    SELECT
      mmsi,
      COUNT(*) AS message_count,
      MIN(TIMESTAMP_TO_SEC(timestamp)) AS min_timestamp,
      MAX(TIMESTAMP_TO_SEC(timestamp)) AS max_timestamp
    FROM (TABLE_DATE_RANGE([{classify_table_name}], TIMESTAMP('{start_date}'), TIMESTAMP('{end_date}')))
    WHERE
      RIGHT(seg_id, 3) != 'BAD'
      AND data_source IS NULL
    GROUP BY
      mmsi,
      seg_id )
  GROUP BY
    mmsi ) b
ON
  a.mmsi = b.mmsi
)
where active_days > 3 and spoof_percent > 0.01


text:
<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/preferred_location"
        android:title="@string/action_map"
        app:showAsAction="never" />
</menu>


text:
package org.red5.cache.impl;

import org.apache.mina.core.buffer.IoBuffer;
import org.red5.cache.ICacheable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

/**
 * Provides an implementation of a cacheable object.
 *
 * @author The Red5 Project
 * @author Paul Gregoire (mondain@gmail.com)
 */
public class CacheableImpl implements ICacheable {

    protected static Logger log = LoggerFactory.getLogger(CacheableImpl.class);

    protected ApplicationContext applicationContext;

    private byte[] bytes;

    private String name;

    private boolean cached;

    public CacheableImpl(Object obj) {
        IoBuffer tmp = IoBuffer.allocate(1024, true);
        tmp.setAutoExpand(true);
        tmp.putObject(obj);
        bytes = new byte[tmp.capacity()];
        tmp.get(bytes);
        cached = true;
        tmp.free();
        tmp = null;
    }

    public CacheableImpl(IoBuffer buffer) {
        if (log.isDebugEnabled()) {
            log.debug("Buffer is direct: {} capacity: {}", buffer.isDirect(), buffer.capacity());
            log.debug("Buffer limit: {} remaining: {} position: {}", new Object[] { buffer.limit(), buffer.remaining(), buffer.position() });
        }
        bytes = new byte[buffer.capacity()];
        buffer.rewind();
        int i = 0;
        while (i < buffer.limit()) {
            buffer.position(i);
            while (buffer.remaining() > 0) {
                bytes[i++] = buffer.get();
            }
        }
        cached = true;
        if (log.isDebugEnabled()) {
            log.debug("Buffer size: " + buffer.capacity());
        }
        buffer = null;
    }

    public void addRequest() {
        log.info("Adding request for: " + name);
    }

    /** {@inheritDoc} */
    @Override
    public byte[] getBytes() {
        return bytes;
    }

    /** {@inheritDoc} */
    @Override
    public IoBuffer getByteBuffer() {
        return IoBuffer.wrap(bytes).asReadOnlyBuffer();
    }

    /** {@inheritDoc} */
    @Override
    public String getName() {
        return name;
    }

    /** {@inheritDoc} */
    @Override
    public boolean isCached() {
        return cached;
    }

    /** {@inheritDoc} */
    @Override
    public void setCached(boolean cached) {
        this.cached = cached;
    }

    /** {@inheritDoc} */
    @Override
    public void setName(String name) {
        this.name = name;
    }

}


text:
@interface RUFriendDetailViewController () {
    BOOL showBeers; // the opposite of view is "frequents"
    NSMutableArray * beers;
    NSMutableArray * bars;
}
@end

@implementation RUFriendDetailViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    showBeers = YES;

    beers = [[RUDBManager getSharedInstance] getBeers];
    bars = [[RUDBManager getSharedInstance] getBars];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view delegate

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (showBeers) {
        [[beers objectAtIndex:indexPath.row] toggleLikeFor: self.thisFriendsName];

        if ([[beers objectAtIndex:indexPath.row] islikedByUserWithName:self.thisFriendsName]) {
            [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
        }

    } else {

        [[bars objectAtIndex:indexPath.row] toggleFrequentFor: self.thisFriendsName];

        if ([[bars objectAtIndex:indexPath.row] isFrequentedByUserWithName:self.thisFriendsName]) {
            [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
        }

    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (showBeers)
        return [beers count];
    else
        return [bars count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell10";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (showBeers) {
        cell.textLabel.text = [[beers objectAtIndex:indexPath.row] name];

        if ([[beers objectAtIndex:indexPath.row] islikedByUserWithName:self.thisFriendsName]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    } else {
        cell.textLabel.text = [[bars objectAtIndex:indexPath.row] name];

        if ([[bars objectAtIndex:indexPath.row] isFrequentedByUserWithName:self.thisFriendsName]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }

    return cell;
}

#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

- (IBAction) switchTapped:(id)sender {
    showBeers = !showBeers;
    [self.tableView reloadData];

    if (showBeers) {
        self.navigationItem.rightBarButtonItem.title = @"Bars";
    } else {
        self.navigationItem.rightBarButtonItem.title = @"Beers";
    }

}

@end


text:
/*global self, log, initializeWebWorker */
/*jshint globalstrict: true*/
"use strict";

/**
* Bubble sort, sometimes incorrectly referred to as sinking sort,
* is a simple sorting algorithm that works by repeatedly stepping
* through the list to be sorted, comparing each pair of adjacent
* items and swapping them if they are in the wrong order. The pass
* through the list is repeated until no swaps are needed, which
* indicates that the list is sorted.
*
* http://en.wikipedia.org/wiki/Bubble_sort
*/
var BubbleSort = function(A, descending, TEST_MODE) {
    if (TEST_MODE) {
        log('GROUP', ['Start sorting. A =', A, 'Size: ', A.length]);
    }

    for (var i = 0; i < A.length - 1; i++) {
        if (TEST_MODE) {
            log('GROUP_COLLAPSED', ['Loop' + (i+1)]);
        }

        for (var j = A.length - 1; j > i; j--) {
            if (descending ? A[j] > A[j - 1] : A[j] < A[j - 1]) {
                if (TEST_MODE) {
                    log('GROUP_COLLAPSED', ['A[', j - 1, '] <-> A[', j, ']']);
                }

                var t = A[j];
                A[j] = A[j - 1];
                A[j - 1] = t;

                if (TEST_MODE) {
                    log('LOG', ['A =', A]);
                    log('GROUP_END');
                }
            }
        }
        if (TEST_MODE) {
            log('LOG', ['A =', A]);
            log('GROUP_END');
        }
    }

    if (TEST_MODE) {
        log('INFO', ['Sorted array =', A]);
        log('GROUP_END');
    }
    return A;
};

self.importScripts('/js/worker.js');
initializeWebWorker(BubbleSort);


text:
package ws;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WsApplication.class)
public class WsApplicationTests {

	@Test
	public void contextLoads() {
	}

}


text:
exports.isAuthenticated = function(req, res, next) {
    if (req.isAuthenticated()) { return next(); }

    req.session.redirectTo = req.originalUrl;
    res.redirect('/login');
};


text:
var CSSTree = global.CSSTree = require( '../' );
var munit = global.munit = require( 'munit' );

// Only stop test suite when running make test
if ( ! process.env.NODE_TEST_NO_SKIP ) {
	munit.defaults.settings.stopOnFail = true;
}

// Run tests
munit.render( __dirname + '/../test/', {
	junit: __dirname + '/results/',
	junitPrefix: process.version.replace( /\./g, '_' )
});


text:
/*!
 * Start Bootstrap - Scrolling Nav HTML Template (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

/** {
    border:1px solid red !important;
}*/

body {
    width: 100%;
    height: 100%;
}

html {
    width: 100%;
    height: 100%;
}

@media(min-width:767px) {
    .navbar {
        padding: 20px 0;
        -webkit-transition: background .5s ease-in-out,padding .5s ease-in-out;
        -moz-transition: background .5s ease-in-out,padding .5s ease-in-out;
        transition: background .5s ease-in-out,padding .5s ease-in-out;
    }

    .top-nav-collapse {
        padding: 0;
    }
}

/* Demo Sections - You can use these as guides or delete them - the scroller will work with any sort of height, fixed, undefined, or percentage based.
The padding is very important to make sure the scrollspy picks up the right area when scrolled to. Adjust the margin and padding of sections and children
of those sections to manage the look and feel of the site. */

.intro-section {
    height: auto;
    padding-top: 10%;
    padding-bottom: 5%;
    text-align: center;
    /*background: #fff;*/
    background-image: url(https://upload.wikimedia.org/wikipedia/commons/1/14/Mumbai_Skyline_at_Night.jpg);
    background-size: 100% 100%;
    color: #fff;
}

.blog-section {
    height: auto;
    padding-top: 3%;
    padding-bottom: 5%;
    text-align: center;
    background: #ddd;
}

.projects-section {
    height: auto;
    padding-top: 3%;
    padding-bottom: 5%;
    text-align: center;
    background: #eee;
}

.stuff-section {
    height: auto;
    padding-top: 3%;
    padding-bottom: 5%;
    text-align: center;
    background: #ddd;
    /*background-image: url(../img/countriesToLive.svg);
*/
}

.contact-section {
    height: auto;
    padding-top: 3%;
    padding-bottom: 5%;
    text-align: center;
    background: #fff;
}

.footer-section {
    height: auto;
    text-align: center;
    background: #111;
    color: #fff;
}

a .fa {
color: #555;
margin-left: 10px;
margin-right: 10px;
}

.row-top-bottom-margin {
    margin-top: 15px;
    margin-bottom: 15px;
}

.p-section-font {
    font-size: 18px;
}

.project-col-padding {
    padding-left: 30px;
    padding-right: 30px;
}


text:
package com.facebook.buck.distributed;

import com.facebook.buck.distributed.thrift.BuildJobStateFileHashEntry;
import com.facebook.buck.distributed.thrift.BuildJobStateFileHashes;
import com.facebook.buck.io.ArchiveMemberPath;
import com.facebook.buck.io.MorePaths;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.rules.ActionGraph;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.Cell;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.keys.DefaultRuleKeyFactory;
import com.facebook.buck.rules.keys.RuleKeyFieldLoader;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.cache.FileHashCache;
import com.facebook.buck.util.cache.ProjectFileHashCache;
import com.facebook.buck.util.cache.StackedFileHashCache;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * Responsible for extracting file hash and {@link RuleKey} information from the {@link ActionGraph}
 * and presenting it as a Thrift data structure.
 */
public class DistBuildFileHashes {
  // Map<CellIndex, BuildJobStateFileHashes>.
  private final Map<Integer, RecordedFileHashes> remoteFileHashes;
  private final LoadingCache<ProjectFilesystem, DefaultRuleKeyFactory> ruleKeyFactories;

  private final ListenableFuture<ImmutableList<RecordedFileHashes>> fileHashes;
  private final ListenableFuture<ImmutableMap<BuildRule, RuleKey>> ruleKeys;

  public DistBuildFileHashes(
      ActionGraph actionGraph,
      SourcePathResolver sourcePathResolver,
      SourcePathRuleFinder ruleFinder,
      StackedFileHashCache originalHashCache,
      DistBuildCellIndexer cellIndexer,
      ListeningExecutorService executorService,
      int keySeed,
      final Cell rootCell) {

    this.remoteFileHashes = new HashMap<>();

    StackedFileHashCache recordingHashCache =
        originalHashCache.newDecoratedFileHashCache(
            originalCache -> {
              Path fsRootPath = originalCache.getFilesystem().getRootPath();
              RecordedFileHashes fileHashes =
                  getRemoteFileHashes(cellIndexer.getCellIndex(fsRootPath));
              if (rootCell.getKnownRoots().contains(fsRootPath)) {
                Cell cell = rootCell.getCell(fsRootPath);
                return RecordingProjectFileHashCache.createForCellRoot(
                    originalCache, fileHashes, new DistBuildConfig(cell.getBuckConfig()));
              } else {
                return RecordingProjectFileHashCache.createForNonCellRoot(
                    originalCache, fileHashes);
              }
            });

    this.ruleKeyFactories =
        createRuleKeyFactories(sourcePathResolver, ruleFinder, recordingHashCache, keySeed);
    this.ruleKeys = ruleKeyComputation(actionGraph, this.ruleKeyFactories, executorService);
    this.fileHashes =
        fileHashesComputation(
            Futures.transform(this.ruleKeys, Functions.constant(null)),
            ImmutableList.copyOf(this.remoteFileHashes.values()),
            executorService);
  }

  public RecordedFileHashes getRemoteFileHashes(Integer cellIndex) {
    if (!remoteFileHashes.containsKey(cellIndex)) {
      RecordedFileHashes fileHashes = new RecordedFileHashes(cellIndex);
      remoteFileHashes.put(cellIndex, fileHashes);
    }

    return remoteFileHashes.get(cellIndex);
  }

  public static LoadingCache<ProjectFilesystem, DefaultRuleKeyFactory> createRuleKeyFactories(
      final SourcePathResolver sourcePathResolver,
      final SourcePathRuleFinder ruleFinder,
      final FileHashCache fileHashCache,
      final int keySeed) {

    return CacheBuilder.newBuilder()
        .build(
            new CacheLoader<ProjectFilesystem, DefaultRuleKeyFactory>() {
              @Override
              public DefaultRuleKeyFactory load(ProjectFilesystem key) throws Exception {
                return new DefaultRuleKeyFactory(
                    new RuleKeyFieldLoader(keySeed), fileHashCache, sourcePathResolver, ruleFinder);
              }
            });
  }

  private static ListenableFuture<ImmutableMap<BuildRule, RuleKey>> ruleKeyComputation(
      ActionGraph actionGraph,
      final LoadingCache<ProjectFilesystem, DefaultRuleKeyFactory> ruleKeyFactories,
      ListeningExecutorService executorService) {
    List<ListenableFuture<Map.Entry<BuildRule, RuleKey>>> ruleKeyEntries = new ArrayList<>();
    for (final BuildRule rule : actionGraph.getNodes()) {
      ruleKeyEntries.add(
          executorService.submit(
              () ->
                  Maps.immutableEntry(
                      rule, ruleKeyFactories.get(rule.getProjectFilesystem()).build(rule))));
    }
    ListenableFuture<List<Map.Entry<BuildRule, RuleKey>>> ruleKeyComputation =
        Futures.allAsList(ruleKeyEntries);
    return Futures.transform(
        ruleKeyComputation,
        new Function<List<Map.Entry<BuildRule, RuleKey>>, ImmutableMap<BuildRule, RuleKey>>() {
          @Override
          public ImmutableMap<BuildRule, RuleKey> apply(List<Map.Entry<BuildRule, RuleKey>> input) {
            return ImmutableMap.copyOf(input);
          }
        },
        executorService);
  }

  private static ListenableFuture<ImmutableList<RecordedFileHashes>> fileHashesComputation(
      ListenableFuture<Void> ruleKeyComputationForSideEffect,
      final ImmutableList<RecordedFileHashes> remoteFileHashes,
      ListeningExecutorService executorService) {
    return Futures.transform(
        ruleKeyComputationForSideEffect,
        new Function<Void, ImmutableList<RecordedFileHashes>>() {
          @Override
          public ImmutableList<RecordedFileHashes> apply(Void input) {
            return ImmutableList.copyOf(remoteFileHashes);
          }
        },
        executorService);
  }

  public List<BuildJobStateFileHashes> getFileHashes() throws IOException, InterruptedException {
    try {

      ImmutableList<BuildJobStateFileHashes> hashes =
          fileHashes
              .get()
              .stream()
              .map(recordedHash -> recordedHash.getRemoteFileHashes())
              .filter(x -> x.getEntriesSize() > 0)
              .collect(MoreCollectors.toImmutableList());
      checkNoDuplicates(hashes);
      return hashes;
    } catch (ExecutionException e) {
      Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
      Throwables.throwIfInstanceOf(e.getCause(), InterruptedException.class);
      throw new RuntimeException(e.getCause());
    }
  }

  private void checkNoDuplicates(ImmutableList<BuildJobStateFileHashes> hashes) {
    for (BuildJobStateFileHashes hash : hashes) {
      if (hash.isSetEntries()) {
        Maps.uniqueIndex(hash.entries, entry -> entry.getPath().getPath().toString());
      }
    }
  }

  /** Creates a {@link FileHashCache} that returns the hash codes cached on the remote end. */
  public static ProjectFileHashCache createFileHashCache(
      ProjectFileHashCache decoratedFileHashCache, BuildJobStateFileHashes remoteFileHashes) {
    return new RemoteStateBasedFileHashCache(decoratedFileHashCache, remoteFileHashes);
  }

  public static ImmutableMap<Path, BuildJobStateFileHashEntry> indexEntriesByPath(
      final ProjectFilesystem projectFilesystem, BuildJobStateFileHashes remoteFileHashes) {
    if (!remoteFileHashes.isSetEntries()) {
      return ImmutableMap.of();
    }
    return FluentIterable.from(remoteFileHashes.entries)
        .filter(input -> !input.isPathIsAbsolute() && !input.isSetArchiveMemberPath())
        .uniqueIndex(
            input ->
                projectFilesystem.resolve(
                    MorePaths.pathWithPlatformSeparators(input.getPath().getPath())));
  }

  public static ImmutableMap<ArchiveMemberPath, BuildJobStateFileHashEntry>
      indexEntriesByArchivePath(
          final ProjectFilesystem projectFilesystem, BuildJobStateFileHashes remoteFileHashes) {
    if (!remoteFileHashes.isSetEntries()) {
      return ImmutableMap.of();
    }
    return FluentIterable.from(remoteFileHashes.entries)
        .filter(input -> !input.isPathIsAbsolute() && input.isSetArchiveMemberPath())
        .uniqueIndex(
            input ->
                ArchiveMemberPath.of(
                    projectFilesystem.resolve(
                        MorePaths.pathWithPlatformSeparators(input.getPath().getPath())),
                    Paths.get(input.getArchiveMemberPath())));
  }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CodeFixes
{
    /// <summary>
    /// Context for code fixes provided by an <see cref="CodeFixProvider"/>.
    /// </summary>
    public struct CodeFixContext
    {
        private readonly Document _document;
        private readonly Project _project;
        private readonly TextSpan _span;
        private readonly ImmutableArray<Diagnostic> _diagnostics;
        private readonly CancellationToken _cancellationToken;
        private readonly Action<CodeAction, ImmutableArray<Diagnostic>> _registerCodeFix;

        /// <summary>
        /// Document corresponding to the <see cref="CodeFixContext.Span"/> to fix.
        /// </summary>
        public Document Document { get { return _document; } }

        /// <summary>
        /// Project corresponding to the diagnostics to fix.
        /// </summary>
        internal Project Project { get { return _project; } }

        /// <summary>
        /// Text span within the <see cref="CodeFixContext.Document"/> to fix.
        /// </summary>
        public TextSpan Span { get { return _span; } }

        /// <summary>
        /// Diagnostics to fix.
        /// NOTE: All the diagnostics in this collection have the same <see cref="CodeFixContext.Span"/>.
        /// </summary>
        public ImmutableArray<Diagnostic> Diagnostics { get { return _diagnostics; } }

        /// <summary>
        /// CancellationToken.
        /// </summary>
        public CancellationToken CancellationToken { get { return _cancellationToken; } }

        /// <summary>
        /// Creates a code fix context to be passed into <see cref="CodeFixProvider.RegisterCodeFixesAsync(CodeFixContext)"/> method.
        /// </summary>
        /// <param name="document">Document to fix.</param>
        /// <param name="span">Text span within the <paramref name="document"/> to fix.</param>
        /// <param name="diagnostics">
        /// Diagnostics to fix.
        /// All the diagnostics must have the same <paramref name="span"/>.
        /// Additionally, the <see cref="Diagnostic.Id"/> of each diagnostic must be in the set of the <see cref="CodeFixProvider.FixableDiagnosticIds"/> of the associated <see cref="CodeFixProvider"/>.
        /// </param>
        /// <param name="registerCodeFix">Delegate to register a <see cref="CodeAction"/> fixing a subset of diagnostics.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <exception cref="ArgumentNullException">Throws this exception if any of the arguments is null.</exception>
        /// <exception cref="ArgumentException">
        /// Throws this exception if the given <paramref name="diagnostics"/> is empty,
        /// has a null element or has an element whose span is not equal to <paramref name="span"/>.
        /// </exception>
        public CodeFixContext(
            Document document,
            TextSpan span,
            ImmutableArray<Diagnostic> diagnostics,
            Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix,
            CancellationToken cancellationToken)
            : this(document, span, diagnostics, registerCodeFix, verifyArguments: true, cancellationToken: cancellationToken)
        {
        }

        /// <summary>
        /// Creates a code fix context to be passed into <see cref="CodeFixProvider.RegisterCodeFixesAsync(CodeFixContext)"/> method.
        /// </summary>
        /// <param name="document">Document to fix.</param>
        /// <param name="diagnostic">
        /// Diagnostic to fix.
        /// The <see cref="Diagnostic.Id"/> of this diagnostic must be in the set of the <see cref="CodeFixProvider.FixableDiagnosticIds"/> of the associated <see cref="CodeFixProvider"/>.
        /// </param>
        /// <param name="registerCodeFix">Delegate to register a <see cref="CodeAction"/> fixing a subset of diagnostics.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <exception cref="ArgumentNullException">Throws this exception if any of the arguments is null.</exception>
        public CodeFixContext(
            Document document,
            Diagnostic diagnostic,
            Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix,
            CancellationToken cancellationToken)
            : this(document, diagnostic.Location.SourceSpan, ImmutableArray.Create(diagnostic), registerCodeFix, verifyArguments: true, cancellationToken: cancellationToken)
        {
        }

        internal CodeFixContext(
            Document document,
            TextSpan span,
            ImmutableArray<Diagnostic> diagnostics,
            Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix,
            bool verifyArguments,
            CancellationToken cancellationToken)
            : this (document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, cancellationToken)
        {
        }

        internal CodeFixContext(
            Project project,
            ImmutableArray<Diagnostic> diagnostics,
            Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix,
            CancellationToken cancellationToken)
            : this(document: null, project: project, span: default(TextSpan), diagnostics: diagnostics, registerCodeFix: registerCodeFix, verifyArguments: false, cancellationToken: cancellationToken)
        {
        }

        private CodeFixContext(
            Document document,
            Project project,
            TextSpan span,
            ImmutableArray<Diagnostic> diagnostics,
            Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix,
            bool verifyArguments,
            CancellationToken cancellationToken)
        {
            if (verifyArguments)
            {
                if (document == null)
                {
                    throw new ArgumentNullException(nameof(document));
                }

                if (registerCodeFix == null)
                {
                    throw new ArgumentNullException(nameof(registerCodeFix));
                }

                VerifyDiagnosticsArgument(diagnostics, span);
            }

            _document = document;
            _project = project;
            _span = span;
            _diagnostics = diagnostics;
            _registerCodeFix = registerCodeFix;
            _cancellationToken = cancellationToken;
        }

        internal CodeFixContext(
            Document document,
            Diagnostic diagnostic,
            Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix,
            bool verifyArguments,
            CancellationToken cancellationToken)
            : this(document, diagnostic.Location.SourceSpan, ImmutableArray.Create(diagnostic), registerCodeFix, verifyArguments, cancellationToken)
        {
        }

        /// <summary>
        /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user.
        /// </summary>
        /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param>
        /// <param name="diagnostic">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param>
        public void RegisterCodeFix(CodeAction action, Diagnostic diagnostic)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            if (diagnostic == null)
            {
                throw new ArgumentNullException(nameof(diagnostic));
            }

            _registerCodeFix(action, ImmutableArray.Create(diagnostic));
        }

        /// <summary>
        /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user.
        /// </summary>
        /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param>
        /// <param name="diagnostics">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param>
        public void RegisterCodeFix(CodeAction action, IEnumerable<Diagnostic> diagnostics)
        {
            if (diagnostics == null)
            {
                throw new ArgumentNullException(nameof(diagnostics));
            }

            RegisterCodeFix(action, diagnostics.ToImmutableArray());
        }

        /// <summary>
        /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user.
        /// </summary>
        /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param>
        /// <param name="diagnostics">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param>
        public void RegisterCodeFix(CodeAction action, ImmutableArray<Diagnostic> diagnostics)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            VerifyDiagnosticsArgument(diagnostics, _span);

            // TODO:
            // - Check that all diagnostics are unique (no duplicates).
            // - Check that supplied diagnostics form subset of diagnostics originally
            //   passed to the provider via CodeFixContext.Diagnostics.

            _registerCodeFix(action, diagnostics);
        }

        private static void VerifyDiagnosticsArgument(ImmutableArray<Diagnostic> diagnostics, TextSpan span)
        {
            if (diagnostics.IsDefault)
            {
                throw new ArgumentException(nameof(diagnostics));
            }

            if (diagnostics.Length == 0)
            {
                throw new ArgumentException(WorkspacesResources.DiagnosticsCannotBeEmpty, nameof(diagnostics));
            }

            if (diagnostics.Any(d => d == null))
            {
                throw new ArgumentException(WorkspacesResources.DiagnosticCannotBeNull, nameof(diagnostics));
            }

            if (diagnostics.Any(d => d.Location.SourceSpan != span))
            {
                throw new ArgumentException(string.Format(WorkspacesResources.DiagnosticMustHaveMatchingSpan, span.ToString()), nameof(diagnostics));
            }
        }
    }
}


text:
SystemJS.config({
    'transpiler': 'plugin-babel',
    'map': {
        'plugin-babel': 'systemjs-plugin-babel/plugin-babel.js',
        'systemjs-babel-build': 'systemjs-plugin-babel/systemjs-babel-browser.js',
        'app': '../scripts/app.js',
        'data': '../scripts/data.js',
        'jquery': '../bower_components/jquery/dist/jquery.js',
        'tether': '../bower_components/tether/dist/js/tether.min.js',
        'bootstrap': '../bower_components/bootstrap/dist/js/bootstrap.min.js',
        'sammy': '../bower_components/sammy/lib/min/sammy-latest.min.js',
        'handlebars': '../bower_components/handlebars/handlebars.min.js',
        'template': '../scripts/data/handlebars-template.js',
        'requester': '../scripts/data/requester.js',
        'tests': './tests.js'
    },
    'meta': {
        'bootstrap': {
            globals: {
                Tether: 'tether'
            }
        }
    }
});

System.import('tests');


text:
/****************************************************************
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
****************************************************************/
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int s = 0;
        int res = INT_MIN;
        for (int i = 0; i < nums.size(); i++) {
            s += nums[i];
            res = max(s, res);
            if (s < 0) s = 0;
        }
        return res;
    }
};


text:
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import Http404

from models import Presentation

def list(request):
	presentations = Presentation.objects.all()

	return render_to_response('presentations/presentation_list.html', { 'presentations': presentations }, context_instance=RequestContext(request))

def detail(request, slug, topic):
	presentation = Presentation.objects.get(slug=slug)
	slides = presentation.slide_set.all()

	return render_to_response('presentations/presentation_detail.html', { 'object': presentation, 'slides': slides }, context_instance=RequestContext(request))


text:
@interface UINavigationController (RTL)

@end


text:
UploadThrobberView = Backbone.View.extend({
    events: {
    },

    initialize: function () {
        this.render();
    },

    render: function () {
        this.$el.html(render('application/upload_throbber'));
    }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<checkstyle version="6.11.2">
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/BackPressureStatsTracker.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/ExecutionGraphHolder.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/files/MimeTypes.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/files/StaticFileServerHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/AbstractExecutionGraphRequestHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/AbstractJobVertexRequestHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/AbstractJsonRequestHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/AbstractSubtaskAttemptRequestHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/AbstractSubtaskRequestHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/checkpoints/CheckpointConfigHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/checkpoints/CheckpointStatsCache.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/checkpoints/CheckpointStatsDetailsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/checkpoints/CheckpointStatsDetailsSubtasksHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/checkpoints/CheckpointStatsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/ClusterOverviewHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/ConstantTextHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/CurrentJobIdsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/CurrentJobsOverviewHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/DashboardConfigHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/HandlerRedirectUtils.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JarAccessDeniedHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JarActionHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JarDeleteHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JarListHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JarPlanHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JarRunHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JarUploadHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobAccumulatorsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobCancellationHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobCancellationWithSavepointHandlers.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobConfigHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobDetailsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobExceptionsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobManagerConfigHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobPlanHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobStoppingHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobVertexAccumulatorsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobVertexBackPressureHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobVertexDetailsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JobVertexTaskManagersHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JsonFactory.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/RequestHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/RequestHandlerException.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/SubtaskCurrentAttemptDetailsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/SubtaskExecutionAttemptAccumulatorsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/SubtaskExecutionAttemptDetailsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/SubtasksAllAccumulatorsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/SubtasksTimesHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/TaskManagerLogHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/TaskManagersHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/history/HistoryServer.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/history/HistoryServerArchiveFetcher.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/history/HistoryServerStaticFileServerHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/HttpRequestHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/JobManagerRetriever.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/metrics/AbstractMetricsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/metrics/JobManagerMetricsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/metrics/JobMetricsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/metrics/JobVertexMetricsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/metrics/MetricFetcher.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/metrics/MetricStore.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/metrics/TaskManagerMetricsHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/NotFoundException.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/OperatorBackPressureStats.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/PipelineErrorHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/RuntimeMonitorHandler.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/RuntimeMonitorHandlerBase.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/StackTraceSample.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/StackTraceSampleCoordinator.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/utils/MutableIOMetrics.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/utils/WebFrontendBootstrap.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/WebMonitorConfig.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/WebRuntimeMonitor.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-runtime-web/src/test/resources/log4j-test.properties">
</file>
</checkstyle>


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

namespace FluentCassandra.Types
{
    internal class MapTypeConverter<TKey, TValue> : CassandraObjectConverter<Dictionary<TKey, TValue>>
        where TKey : CassandraObject
        where TValue : CassandraObject
    {
        protected virtual string CollectionStringBegin { get { return "{"; } }

        protected virtual string CollectionStringEnd { get { return "}"; } }

        protected virtual string KeyValueSeparator{ get { return ":"; } }

        public override bool CanConvertFrom(Type sourceType)
        {
            return sourceType == typeof(byte[]) ||
                 sourceType.GetInterfaces().Contains(typeof(IDictionary<TKey, TValue>)) ||
                 sourceType.GetInterfaces().Contains(typeof(IEnumerable<KeyValuePair<TKey, TValue>>)) ||
                 sourceType.GetInterfaces().Contains(typeof(IEnumerable<object>));
        }

        public override bool CanConvertTo(Type destinationType)
        {
            return destinationType == typeof(byte[]) ||
                destinationType == typeof(Dictionary<TKey, TValue>) ||
                destinationType == typeof(Dictionary<CassandraObject, CassandraObject>) ||
                destinationType == typeof(List<KeyValuePair<TKey, TValue>>) ||
                destinationType == typeof(List<KeyValuePair<CassandraObject, CassandraObject>>) ||
                destinationType == typeof(KeyValuePair<CassandraObject, CassandraObject>[]) ||
                destinationType == typeof(List<object>) ||
                destinationType == typeof(object[]) ||
                destinationType == typeof(string);
        }

        public override Dictionary<TKey, TValue> ConvertFromInternal(object value)
        {
            if (value is byte[])
            {
                var components = new Dictionary<TKey, TValue>();

                var keyTypeHint = typeof(TKey);
                var valueTypeHint = typeof (TValue);

                using (var bytes = new MemoryStream((byte[])value))
                {
                    // number of key / value pairs
                    var numEntriesBytes = new byte[2];
                    if (bytes.Read(numEntriesBytes, 0, 2) <= 0)
                        return components;

                    var nEntries = BitConverter.ToUInt16(numEntriesBytes, 0);
                    for (var i = 0; i < nEntries; i++)
                    {
                        //get the length of the key
                        var keyLengthBytes = new byte[2];
                        bytes.Read(keyLengthBytes, 0, 2);
                        var keyLength = BitConverter.ToUInt16(keyLengthBytes, 0);

                        //read the content of the key into a buffer
                        var keyBuffer = new byte[keyLength];
                        bytes.Read(keyBuffer, 0, keyLength);
                        var entryKey = CassandraObject.GetCassandraObjectFromDatabaseByteArray(keyBuffer, keyTypeHint);

                        //get the length of the value
                        var valueLengthBytes = new byte[2];
                        bytes.Read(valueLengthBytes, 0, 2);
                        var valueLength = BitConverter.ToUInt16(valueLengthBytes, 0);

                        //read the content of the key into a buffer
                        var valueBuffer = new byte[valueLength];
                        bytes.Read(valueBuffer, 0, valueLength);
                        var entryValue = CassandraObject.GetCassandraObjectFromDatabaseByteArray(valueBuffer, valueTypeHint);

                        components.Add((TKey)entryKey, (TValue)entryValue);
                    }
                }

                return components;
            }

            if (value.GetType().GetInterfaces().Contains(typeof(IEnumerable<object>)))
                return new Dictionary<TKey, TValue>(((IEnumerable<object>)value).Cast<KeyValuePair<TKey, TValue>>().ToDictionary(k => k.Key, v => v.Value));

            if (value.GetType().GetInterfaces().Contains(typeof(IEnumerable<KeyValuePair<TKey, TValue>>)))
                return new Dictionary<TKey, TValue>(((IEnumerable<KeyValuePair<TKey, TValue>>)value).ToDictionary(k => k.Key, v => v.Value));

            return null;
        }

        public override object ConvertToInternal(Dictionary<TKey, TValue> value, Type destinationType)
        {
            if (destinationType == typeof(string))
                return CollectionStringBegin + String.Join(",", value.Select(x => string.Format("{0}{1}{2}", x.Key, KeyValueSeparator, x.Value))) + CollectionStringEnd; //should format the map into a JSON-esque object

            if (destinationType == typeof(byte[]))
            {
                var components = value;

                using (var bytes = new MemoryStream())
                {
                    //write the number of elements
                    var elements = (ushort)components.Count;
                    bytes.Write(BitConverter.GetBytes(elements), 0, 2);

                    foreach (var c in components)
                    {

                        var keyBytes = c.Key.ToBigEndian();

                        //key length
                        var keyLength = (ushort)keyBytes.Length;
                        bytes.Write(BitConverter.GetBytes(keyLength), 0, 2);

                        //key value
                        bytes.Write(keyBytes, 0, keyLength);

                        var valueBytes = c.Value.ToBigEndian();

                        // value length
                        var valueLength = (ushort)valueBytes.Length;
                        bytes.Write(BitConverter.GetBytes(valueLength), 0, 2);

                        // value
                        bytes.Write(valueBytes, 0, valueLength);
                    }

                    return bytes.ToArray();
                }

            }

            if (destinationType == typeof(KeyValuePair<CassandraObject, CassandraObject>[]))
                return value.ToArray();

            if (destinationType == typeof(object[]))
                return value.Cast<object>().ToArray();

            if (destinationType == typeof(List<KeyValuePair<CassandraObject, CassandraObject>>) || destinationType == typeof(List<KeyValuePair<TKey, TValue>>))
                return value.ToList();

            if (destinationType == typeof (Dictionary<TKey, TValue>) ||
                destinationType == typeof (Dictionary<CassandraObject, CassandraObject>))
                return value;

            if (destinationType == typeof(List<object>))
                return value.Cast<object>().ToList();

            return null;
        }

        public override byte[] ToBigEndian(Dictionary<TKey, TValue> value)
        {
            var components = value;

            using (var bytes = new MemoryStream())
            {
                //write the number of elements
                var elements = (ushort)components.Count;
                bytes.Write(ConvertEndian(BitConverter.GetBytes(elements)), 0, 2);

                foreach (var c in components)
                {

                    var keyBytes = c.Key.ToBigEndian();

                    //key length
                    var keyLength = (ushort)keyBytes.Length;
                    bytes.Write(ConvertEndian(BitConverter.GetBytes(keyLength)), 0, 2);

                    //key value
                    bytes.Write(keyBytes, 0, keyLength);

                    var valueBytes = c.Value.ToBigEndian();

                    // value length
                    var valueLength = (ushort)valueBytes.Length;
                    bytes.Write(ConvertEndian(BitConverter.GetBytes(valueLength)), 0, 2);

                    // value
                    bytes.Write(valueBytes, 0, valueLength);
                }

                return bytes.ToArray();
            }
        }

        public override Dictionary<TKey, TValue> FromBigEndian(byte[] value)
        {
            var components = new Dictionary<TKey, TValue>();

            var keyTypeHint = typeof(TKey);
            var valueTypeHint = typeof(TValue);
            if (value == null) return components;
            using (var bytes = new MemoryStream((byte[])value))
            {
                // number of key / value pairs
                var numEntriesBytes = new byte[2];
                if (bytes.Read(numEntriesBytes, 0, 2) <= 0)
                    return components;

                var nEntries = BitConverter.ToUInt16(ConvertEndian(numEntriesBytes), 0);
                for (var i = 0; i < nEntries; i++)
                {
                    //get the length of the key
                    var keyLengthBytes = new byte[2];
                    bytes.Read(keyLengthBytes, 0, 2);
                    var keyLength = BitConverter.ToUInt16(ConvertEndian(keyLengthBytes), 0);

                    //read the content of the key into a buffer
                    var keyBuffer = new byte[keyLength];
                    bytes.Read(keyBuffer, 0, keyLength);
                    var entryKey = CassandraObject.GetCassandraObjectFromDatabaseByteArray(keyBuffer, keyTypeHint);

                    //get the length of the value
                    var valueLengthBytes = new byte[2];
                    bytes.Read(valueLengthBytes, 0, 2);
                    var valueLength = BitConverter.ToUInt16(ConvertEndian(valueLengthBytes), 0);

                    //read the content of the key into a buffer
                    var valueBuffer = new byte[valueLength];
                    bytes.Read(valueBuffer, 0, valueLength);
                    var entryValue = CassandraObject.GetCassandraObjectFromDatabaseByteArray(valueBuffer, valueTypeHint);

                    components.Add((TKey)entryKey, (TValue)entryValue);
                }
            }

            return components;
        }
    }
}


text:
var keystone = require('keystone'),
	utils = require('keystone-utils'),
	snowcoins = require('wallets'),
	snowlist = snowcoins.get('lists'),
	fs = require('fs'),
	async = require('async'),
	crypto = require('crypto'),
	_ = require('lodash'),
	request = require('request'),
	Wallet = snowlist.wallets,
	ClientConnect = snowlist.clients,
	CurrentWallets = snowlist.attended,
	Offline = snowlist.unattended,
	iprange = require('range_check');

//console.log(keystone.list('ClientConnect'));

var SnowAuth = {
	_options: {
		key:false,
		ip:false,
		authlevel:11,
		isAuthorized:false,
		owner:false
	}
	//this.set('agenda', );

}

/**
 * Initialises SnowAuth in encapsulated mode.
 *
 * Options expects  {key,ip,nonce} to authorize later.
 *
 * First time running the nonce will be empty
 *
 * Returns `this` to allow chaining.
 *
 * @param {Object} options
 * @api public
 */

SnowAuth.init = function(options) {

	this.options(options);

	return this;

}

/**
 * authorizes requester
 *
 * Returns this if true and kicks error if false
 *
 * @param {Int} auth level of function
 * @param {Function} Callback
 * @api public
 */

SnowAuth.auth = function(level,callback) {
	var thisobject = this,
		ip = this.get('ip'),
		key = this.get('key'),
		user=false,
		ClientConnect = keystone.list('ClientConnect');
	var args = Array.prototype.slice.call(arguments),
		cb  = args.pop();
	//loop through each roadblock with async
	//if anything fails send an error straight back to user with snowfail and return false
	async.series([
		function(next) {
			//grap data from  key first
			ClientConnect.model.findOne()
				.where('apikey', key)
				.exec(function(err, data) {
					if(data) {
						user=data;
						thisobject.set('authlevel',user.authlevel);
						thisobject.set('owner',user.owner);
						thisobject.set('_id',user._id);
						thisobject.set('name',user.name);
						next();
					} else {
						console.log('no key found');
						return (SnowAuth.iscallback(cb) ? cb('Valid API key required'):thisobject);
					}
				});
		},
		function(next) {
			//now check the ip vs registered range
			//console.log(ip,user.ip);
			//console.log('pass ip check',iprange.in_range(ip, user.ip));
			if(!ip || !iprange.in_range(ip, user.ip)) {
				return (SnowAuth.iscallback(cb) ? cb('Failed IP Check'):thisobject);
			} else {
				next();
			}
		},
		function(next) {
			//if there is a level check it
			if(typeof level === 'number') {
				if(SnowAuth.checkauth(level))
					next();
				else
					return (SnowAuth.iscallback(cb) ? cb('Failed Level Authorization Check'):thisobject);
			} else {
				next();
			}
		}
	],
	function(err) {
		//this user is good so just return the ret variable set earlier
		thisobject.set('isAuthorized',true)
		return (SnowAuth.iscallback(cb) ? cb(null,thisobject):thisobject);
	});

}

/**
 * check auth level
 *
 * return true / false
 *
 * @param {Integer} value
 * @api public
 */
SnowAuth.checkauth = function(level) {
	if(this.get('authlevel')<=level)
		return true;
	else
		return false;
}

/**
 * return function
 *
 * return this if not a function
 *
 * @param {Function} value
 * @param {Object} self
 * @api public
 */
SnowAuth.doreturn = function(ret,self) {
	if(typeof ret === 'function') {
		return ret(self);
	} else {
		if(self)ret=self;
		return ret;
	}
}

/**
 * Is the callback a function
 *
 * ####Example:
 *
 *     SnowAuth.iscallback(cb) // is this a callback
 *
 * @param {Function} value
 * @api public
 */
SnowAuth.iscallback = function (checkme) {
	return typeof checkme === 'function' ? true:false;
}

/**
 * Sets SnowAuth options
 *
 * ####Example:
 *
 *     SnowAuth.set('api', 'rpc') // sets the 'api' option to `rpc`
 *
 * @param {String} key
 * @param {String} value
 * @api public
 */
 SnowAuth.set = function(key, value) {

	if (arguments.length == 1) {
		return this._options[key];
	}

	if (remappedOptions[key]) {
		console.log('Warning: the `' + key + '` option has been deprecated. Please use `' + remappedOptions[key] + '` instead.\n\n' +
			'Support for `' + key + '` will be removed in a future version.');
		key = remappedOptions[key];
	}

	// handle special settings if needed
	switch (key) {
		case 'api':
			if(value!=this.get('api') && api!='')
			{
				var myapi = this.useapi(value);
				if(myapi.success==true) {
					api = myapi.api;
				}
				else {
					console.log(myapi.err);
				}
			}
			else
			{
				//console.log('keep current api');
			}
			break;
	}

	this._options[key] = value;
	return this;
};

/**
 * Sets multiple SnowAuth options.
 *
 * ####Example:
 *
 *     SnowAuth.set({test: value}) // sets the 'test' option to `value`
 *
 * @param {Object} options
 * @api public
 */

SnowAuth.options = function(options) {
	if (!arguments.length)
		return this._options;
	if (utils.isObject(options)) {
		var keys = Object.keys(options),
			i = keys.length,
			k;
		while (i--) {
			k = keys[i];
			this.set(k, options[k]);
		}
	}
	return this._options;
};

/**
 * Gets a path option, expanded to include process.cwd() if it is relative
 *
 * ####Example:
 *
 *     SnowAuth.getPath(path) // returns the 'test' value
 *
 * @param {String} key
 * @method get
 * @api public
 */

SnowAuth.getPath = function(key, defaultValue) {
	var path = this.get(key);
	path = ('string' == typeof path && path.substr(0,1) != '/') ? process.cwd() + '/' + path : path;
	return path;
}

/**
 * Gets SnowAuth options
 *
 * ####Example:
 *
 *     SnowAuth.get('test') // returns the 'test' value
 *
 * @param {String} key
 * @method get
 * @api public
 */

SnowAuth.get = SnowAuth.set;

/**
 * Deprecated options that have been mapped to new keys
 */
var remappedOptions = {};

/**
 * simple encrypt - creates iv from password - change to createCipheriv to add your own
 *
 * ####Example:
 *
 *     SnowAuth.encrypt(text,password) //
 *
 * @param {String} text
 * @param {String} password
 * @method get
 * @api public
 */

SnowAuth.encrypt = function(text,password) {
  var cipher = crypto.createCipher('aes-256-cbc',password)
  var crypted = cipher.update(text,'utf8','hex')
  crypted += cipher.final('hex');
  return crypted;
}

/**
 * simple decrypt -  - change to createDecipheriv if you changed encrypt
 *
 * ####Example:
 *
 *     SnowAuth.decrypt(text,password) //
 *
 * @param {String} text
 * @param {String} password
 * @method get
 * @api public
 */
SnowAuth.decrypt = function(text,password) {
  var decipher = crypto.createDecipher('aes-256-cbc',password)
  var dec = decipher.update(text,'hex','utf8')
  dec += decipher.final('utf8');
  return dec;
}

/**
 * The exports object is an instance of SnowAuth.
 *
 * @api public
 */

var SnowAuth = module.exports = SnowAuth;
/**
 * 2014 snowkeeper
 * github.com/snowkeeper
 * npmjs.org/snowkeeper
 *
 * Peace :0)
 *
 * */


text:
    POST blogs

## Description
Creates a new Story.

***

## Requires authentication
**[OAuth][]**

***

## Parameters

Essential information:

- **title** _(required)_ — Title for the blog post.
- **body** _(required)_ — Content of the blog post.

Optional information:

- **latitude** — Latitude for the blog post.
- **longitude** — Longitude for the blog post.
- **tags** — Comma separated list of tags.
- **photo_ids** — Comma separated list of Photo ID values to post with the blog.

***

## Return format
New created Story information in **[full format][]**.

***

## Errors
All known errors cause the resource to return HTTP error code header together with a JSON array containing at least 'status' and 'error' keys describing the source of error.

- **400 Bad Request** — One or more of the required fields was missing.
- **422 Unprocessable Entity** — One or more of the required fields didn't include valid data.

***

## Example
**Request**

    POST /v1/blogs

**Body**

    title=My+Vacation&body=I+went+on+a+vacation+to+Hawaii&photo_ids=251

**Return**
``` json
{
  "id": 40186,
  "title": "My Vacation",
  "body": "I went on a vacation to Hawaii",
  "created_at": "2012-06-07T17:10:57-04:00",
  "latitude": null,
  "longitude": null,
  "user": {
    "id": 173,
    "username": "vovko",
    "firstname": "Vladimir",
    "lastname": "Drizhepolov",
    "city": "Toronto",
    "country": "Canada",
    "fullname": "Vladimir Drizhepolov",
    "userpic_url": "http://acdn.500px.net/173.jpg",
    "upgrade_status": 2
  },
  "tags": null,
  "photos": [
    {
      "id": 251,
      "name": "Untitled",
      "rating": 59.7,
      "created_at": "2012-06-05T17:40:48-04:00",
      "category": 0,
      "votes_count": 1,
      "image_url": "http://pcdn.500px.net/8309863/49a60b97f30125b223f4e38ab53c6525435888f2/4.jpg"
    }
  ]
}
```

[OAuth]: https://github.com/500px/api-documentation/tree/master/authentication
[full format]: https://github.com/500px/api-documentation/blob/master/basics/formats_and_terms.md#full-format


text:
SYNONYM

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

#### Published in
Ann. K. K. Naturhist. Hofmus. 11:163. 1896

#### Original name
null

### Remarks
null


text:
package com.denkovski.mihail.les.quatres;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.TextureLoader;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.denkovski.mihail.les.quatres.ChipMatch.ScreenRatio;
import com.denkovski.mihail.les.quatres.ChipMatch.ScreenSize;

public class AssetsLoader {

	public ChipMatch game;
	// AssetManager

	public TextureAtlas atlas;

	public Texture background_pattern, dark_tint;

	// Puzzle Renderer
	public TextureRegion redcircle, yellowcircle, greencircle, orangecircle, jokercircle, puzzle_grid, redcircles, yellowcircles, greencircles, orangecircles, jokercircles, background, bg2;

	// Scores
	public Texture[] scores = new Texture[6];

    // Tutorial Menu Renderer
    public Texture tutorial_banner;

    // Main Menu
	public TextureRegion main_menu_background, main_menu_action_button_normal, main_menu_action_button_pressed, main_menu_zen_button_normal, main_menu_zen_button_pressed,
	main_menu_options_button_normal, main_menu_options_button_pressed, share_button_normal, share_button_pressed,
	rate_button_normal, rate_button_pressed, sampleads, leaderboards_button_normal, leaderboards_button_pressed;

	// Pause Menu
	public TextureRegion pause_foreground, exit_button_normal, exit_button_pressed, retry_button_normal, retry_button_pressed, game_over_banner, yourscoreis;

	// EndLevelMenu
	public TextureRegion yellow_frame, level_finished_banner;
    public TextureRegion continue_button_normal, continue_button_pressed;

	// Leaderboards and Achievements
	public TextureRegion leaderboard_banner_button_normal, leaderboard_banner_button_pressed, achievements_banner_button_normal, achievements_banner_button_pressed;

	// UI Renderer
	public TextureRegion woodback, woodframe, progressbar, back_button, menu_text;
	public TextureRegion back_button_pressed, back_button_normal;

	public Texture main_menu_wood_frame, progress_bar_slot, wood_back, wood_frame_bottom, progress_bar, wood_frame_top, pause_menu_wood_frame, main_menu_heading;

    public AssetManager assetManager;

	public AssetsLoader(ChipMatch game) {
		this.game = game;
        assetManager = new AssetManager();
	}

	/*
	 * Supported densities and resolutions
	 *
	 * mdpi {
	 * 		320 x 480   1.5     3:2
	 *
	 *
	 * 		480 x 640 4:3 ??
	 *
	 * }
	 *
	 * hdpi {
	 * 		480 x 800   1.666   15:9
	 *      600 x 800   4:3 ???
	 *      480 x 854   1.777   16:9
	 *
	 *      540 x 960   1.777   16:9
	 *      640 x 960 ? 1.5     3:2
	 * }
	 *
	 * xhdpi {
	 * 		600x1024    1.71
	 *      768x1024    4:3
	 * 		720x1280    1.777   16:9
	 *      768x1280    1.666   15:9
	 * 		800x1280    1.6	    16:10
	 * }
	 *
	 * xxhdpi {
	 * 		1080x1920   1.777   16:9
	 * 		1200x1920   1.6	    16:10
	 * }
	 *
	 *
	 * xxhdpi {
	 * 		2560x1440   1.777   16:9
	 * 		2560x1600   1.6	    16:10
	 * }
	 *
	 */

	public String density, density2;

	public void loadAssets() {

		// Puzzle Renderer
		if(game.screenSize == ScreenSize.mdpi) {
    		density = "hdpi";
		}
		if(game.screenSize == ScreenSize.hdpi) {
    		density = "hdpi";
    	} else if(game.screenSize == ScreenSize.xhdpi) {
    		density = "xhdpi";
    	} else if(game.screenSize == ScreenSize.xxhdpi) {
    		density = "xxhdpi";
    	}

        TextureLoader.TextureParameter param = new TextureLoader.TextureParameter();
        param.minFilter = TextureFilter.Linear;

        assetManager.load(density + "/textures/atlas/" + density + ".atlas", TextureAtlas.class);
		assetManager.load("green_felt_pattern.png", Texture.class, param);

		// Assets NOT relative to aspect ratio
		if(Gdx.graphics.getWidth() <= 650) { // mdpi
            density2 = "hdpi";
		} else
			if(Gdx.graphics.getWidth() <= 960) { // hdpi
                density2 = "xhdpi";
		} else if(Gdx.graphics.getWidth() <= 1250) { // xhdpi
                density2 = "xxhdpi";
		} else if(Gdx.graphics.getWidth() <= 1650) { // xxhdpi
            density2 = "xxhdpi";
		}

        // Assets relative to aspect ratio
        assetManager.load("relative/"+density2+"/puzzlescreen/wood_frame_top.png", Texture.class, param);
        assetManager.load("relative/"+density2+"/puzzlescreen/wood_frame_bottom.png", Texture.class, param);
        assetManager.load("relative/"+density2+"/puzzlescreen/wood_back.png", Texture.class, param);
        assetManager.load("relative/"+density2+"/puzzlescreen/progress_bar_slot.png", Texture.class, param);
        assetManager.load("relative/"+density2+"/puzzlescreen/progress_bar.png", Texture.class, param);

        assetManager.load("hdpi/textures/scores/+100.png", Texture.class, param);
        assetManager.load("hdpi/textures/scores/+100.png", Texture.class, param);
        assetManager.load("hdpi/textures/scores/+200.png", Texture.class, param);
        assetManager.load("hdpi/textures/scores/+300.png", Texture.class, param);
        assetManager.load("hdpi/textures/scores/+400.png", Texture.class, param);
        assetManager.load("hdpi/textures/scores/+500.png", Texture.class, param);
        assetManager.load("hdpi/textures/scores/+600.png", Texture.class, param);
        assetManager.load(density + "/textures/tutorial_menu_renderer/tutorial_banner.png", Texture.class, param);

        // Main Menu

    	if(game.screenSize == ScreenSize.mdpi) {
    		assetManager.load("mdpi/textures/main_menu/4to3/wood_frame.png", Texture.class, param);
        } else
        	if(game.screenSize == ScreenSize.hdpi) {
        	if(game.screenRatio == ScreenRatio.r16t9)
                assetManager.load("hdpi/textures/main_menu/16to9/wood_frame.png", Texture.class, param);
    		else if(game.screenRatio == ScreenRatio.r4t3)
                assetManager.load("hdpi/textures/main_menu/4to3/wood_frame.png", Texture.class, param);
        } else if(game.screenSize == ScreenSize.xhdpi) {
        	if(game.screenRatio == ScreenRatio.r16t9)
                assetManager.load("xhdpi/textures/main_menu/16to9/wood_frame.png", Texture.class, param);
    		else if(game.screenRatio == ScreenRatio.r4t3)
                assetManager.load("xhdpi/textures/main_menu/4to3/wood_frame.png", Texture.class, param);
        } else if(game.screenSize == ScreenSize.xxhdpi) {
                assetManager.load("xxhdpi/textures/main_menu/16t9/wood_frame.png", Texture.class, param);
        }

        assetManager.load("dark_tint.png", Texture.class);
        assetManager.load(density+"/textures/wood_frame.png", Texture.class, param);
    }

    public void getAssets()
    {
        atlas = assetManager.get(density + "/textures/atlas/" + density + ".atlas", TextureAtlas.class);

        // Scores
        puzzle_grid = atlas.findRegion("grid");
        redcircle = atlas.findRegion("red_circle");
        yellowcircle = atlas.findRegion("black_circle");
        orangecircle = atlas.findRegion("orange_circle");
        jokercircle = atlas.findRegion("joker_circle");
        greencircle = atlas.findRegion("blue_circle");
        redcircles = atlas.findRegion("red_circle_s");
        yellowcircles = atlas.findRegion("black_circle_s");
        orangecircles = atlas.findRegion("orange_circle_s");
        jokercircles = atlas.findRegion("joker_circle_s");
        greencircles = atlas.findRegion("blue_circle_s");

        menu_text = atlas.findRegion("menu_text");
        back_button_normal = atlas.findRegion("back_button");
        back_button_pressed = atlas.findRegion("back_button_pressed");

        main_menu_heading = new Texture(Gdx.files.internal(density+"/textures/chip_match_heading.png"));
        main_menu_action_button_normal = atlas.findRegion("action_button");
        main_menu_action_button_pressed = atlas.findRegion("action_button_pressed");
        main_menu_zen_button_normal = atlas.findRegion("relax_button");
        main_menu_zen_button_pressed = atlas.findRegion("relax_button_pressed");
        main_menu_options_button_normal = atlas.findRegion("more_games_button");
        main_menu_options_button_pressed = atlas.findRegion("more_games_button_pressed");
        share_button_normal = atlas.findRegion("share_button");
        share_button_pressed = atlas.findRegion("share_button_pressed");
        rate_button_normal = atlas.findRegion("rate_button");
        rate_button_pressed = atlas.findRegion("rate_button_pressed");
        leaderboards_button_normal = atlas.findRegion("leaderboard");
        leaderboards_button_pressed = atlas.findRegion("leaderboard_pressed");

        exit_button_normal = atlas.findRegion("exit_button");
        exit_button_pressed = atlas.findRegion("exit_button_pressed");
        retry_button_normal = atlas.findRegion("retry_button");
        retry_button_pressed = atlas.findRegion("retry_button_pressed");
        game_over_banner = atlas.findRegion("game_over_banner");
        yourscoreis = atlas.findRegion("YourScoreIs");

        dark_tint = assetManager.get("dark_tint.png", Texture.class);
        pause_menu_wood_frame = assetManager.get(density+"/textures/wood_frame.png", Texture.class);

        continue_button_normal = atlas.findRegion("continue_button");
        continue_button_pressed = atlas.findRegion("continue_button_pressed");
        yellow_frame = atlas.findRegion("yellow_frame");
        level_finished_banner = atlas.findRegion("level_finished_banner");

        leaderboard_banner_button_normal = atlas.findRegion("leaderboard_banner_button");
        leaderboard_banner_button_pressed = atlas.findRegion("leaderboard_banner_button_pressed");
        achievements_banner_button_normal = atlas.findRegion("achievements_banner_button");
        achievements_banner_button_pressed = atlas.findRegion("achievements_banner_button_pressed");

        background_pattern = assetManager.get("green_felt_pattern.png", Texture.class);
        background_pattern.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
        wood_frame_top = assetManager.get("relative/"+density2+"/puzzlescreen/wood_frame_top.png", Texture.class);
        wood_frame_bottom = assetManager.get("relative/"+density2+"/puzzlescreen/wood_frame_bottom.png", Texture.class);
        wood_back = assetManager.get("relative/"+density2+"/puzzlescreen/wood_back.png", Texture.class);
        progress_bar_slot = assetManager.get("relative/"+density2+"/puzzlescreen/progress_bar_slot.png", Texture.class);
        progress_bar = assetManager.get("relative/"+density2+"/puzzlescreen/progress_bar.png", Texture.class);

        scores[0] = assetManager.get("hdpi/textures/scores/+100.png", Texture.class);
        scores[0] = assetManager.get("hdpi/textures/scores/+200.png", Texture.class);
        scores[0] = assetManager.get("hdpi/textures/scores/+300.png", Texture.class);
        scores[0] = assetManager.get("hdpi/textures/scores/+400.png", Texture.class);
        scores[0] = assetManager.get("hdpi/textures/scores/+500.png", Texture.class);
        scores[0] = assetManager.get("hdpi/textures/scores/+600.png", Texture.class);

        if(game.screenSize == ScreenSize.mdpi) {
            main_menu_wood_frame = assetManager.get("mdpi/textures/main_menu/4to3/wood_frame.png", Texture.class);
        } else if(game.screenSize == ScreenSize.hdpi) {
            if(game.screenRatio == ScreenRatio.r16t9)
                main_menu_wood_frame = assetManager.get("hdpi/textures/main_menu/16to9/wood_frame.png", Texture.class);
            else if(game.screenRatio == ScreenRatio.r4t3)
                main_menu_wood_frame = assetManager.get("hdpi/textures/main_menu/4to3/wood_frame.png", Texture.class);
        } else if(game.screenSize == ScreenSize.xhdpi) {
            if(game.screenRatio == ScreenRatio.r16t9)
                main_menu_wood_frame = assetManager.get("xhdpi/textures/main_menu/16to9/wood_frame.png", Texture.class);
            else if(game.screenRatio == ScreenRatio.r4t3)
                main_menu_wood_frame = assetManager.get("xhdpi/textures/main_menu/4to3/wood_frame.png", Texture.class);
        } else if(game.screenSize == ScreenSize.xxhdpi) {
            main_menu_wood_frame = assetManager.get("xxhdpi/textures/main_menu/16t9/wood_frame.png", Texture.class);
        }
        tutorial_banner = assetManager.get(density + "/textures/tutorial_menu_renderer/tutorial_banner.png", Texture.class);

        redcircle.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        yellowcircle.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        greencircle.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        orangecircle.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        jokercircle.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        puzzle_grid.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        redcircles.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        yellowcircles.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        greencircles.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        orangecircles.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        jokercircles.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        main_menu_action_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        main_menu_action_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        main_menu_zen_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        main_menu_zen_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        main_menu_options_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        main_menu_options_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        share_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        share_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        rate_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        rate_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        leaderboards_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        leaderboards_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        exit_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        exit_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        retry_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        retry_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        game_over_banner.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        continue_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        continue_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        yellow_frame.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        level_finished_banner.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        leaderboard_banner_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        leaderboard_banner_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        achievements_banner_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        achievements_banner_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        menu_text.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        back_button_pressed.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
        back_button_normal.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);

        tutorial_banner.setFilter(TextureFilter.Linear,TextureFilter.Linear);
    }

}


text:
import * as chai from "chai"
import { board } from "./../../src/board"
import { rule } from "./../../src/rule"
const { Name, Unit, Board } = board
const { ResolvedResult, Executed, Replaced } = rule

const should = chai.should()

import * as mockMap from "../mock/map"
import { MockOrder } from "../mock/mock-order"
import { MockRule } from "./../mock/mock-rule"

const [Army, Fleet] = mockMap.militaryBranches
const [spain, naples, apulia, western] = mockMap.provinces
const [spa, spaSc, nap, apu, wes] = mockMap.locations
const map = mockMap.map

class MockOrder2 extends MockOrder {
  replaced: boolean
  constructor (unit: board.Unit<string, board.Name>, replaced?: boolean) {
    super(unit)
    this.replaced = replaced || false
  }
}

describe("A rule", () => {
  const unit = new Unit(Fleet, nap, "France")
  const board = new Board(map, "State", [unit], [], [])

  describe("when resolving an invalid order", () => {
    it("uses a default order", () => {
      const unit1 = new Unit(Fleet, nap, "France")
      const unit2 = new Unit(Army, spa, "France")
      const board = new Board(map, "State", [unit1, unit2], [], [])

      const rule: any = new MockRule()
      rule.errorOfOrder = (b: typeof board, order: MockOrder2) => {
        return (order.unit === unit1 || order.replaced) ? null : "Invalid"
      }
      rule.defaultOrderOf = (b: typeof board, unit: board.Unit<string, board.Name>) => {
        return new MockOrder2(unit, true)
      }
      rule.resolveProcedure = (b: typeof board, orders: Set<MockOrder2>) => {
        return {
          result: new ResolvedResult(
            board,
            [...orders].map(order => new Executed(order, "Resolved")),
            true
          )
        }
      }

      const result = (<MockRule>rule).resolve(
        board, new Set([new MockOrder2(unit1), new MockOrder2(unit2)])
      ).result

      should.not.equal(result, null)
      if (result) {
        result.results.should.deep.equal(new Set([
          new Executed(new MockOrder2(unit1), "Resolved"),
          new Replaced(new MockOrder2(unit2), "Invalid", new MockOrder2(unit2, true), "Resolved")
        ]))
      }
    })
  })
  describe("when the set of orders are invalid", () => {
    it("does not resolve the orders", () => {
      const rule: any = new MockRule()
      rule.errorOfOrders = (b: typeof board, orders: Set<MockOrder>) => "Invalid";
      (<MockRule>rule).resolve(board, new Set([new MockOrder(unit)])).should.deep.equal({
        err: "Invalid"
      })
    })
  })
  describe("when several unit that require an order do not have orders", () => {
    it("uses a default order.", () => {
      const unit1 = new Unit(Fleet, nap, "France")
      const unit2 = new Unit(Army, spa, "France")
      const board = new Board(map, "State", [unit1, unit2], [], [])

      const rule: any = new MockRule()
      rule.unitsRequiringOrder = (b: typeof board) => board.units
      rule.defaultOrderOf = (b: typeof board, unit: board.Unit<string, board.Name>) => {
        const o = new MockOrder(unit)
        return o
      }
      rule.resolveProcedure = (b: typeof board, orders: Set<MockOrder>) => {
        return {
          result: new ResolvedResult(
            board,
            [...orders].map(order => new Executed(order, "Resolved")),
            true
          )
        }
      }
      const result = rule.resolve(board, new Set()).result

      should.not.equal(null, result)
      if (result) {
        result.results.should.deep.equal(new Set([
          new Executed(new MockOrder(unit1), "Resolved"),
          new Executed(new MockOrder(unit2), "Resolved")
        ]))
      }
    })
    it("retuns an error if there are no default order.", () => {
      const rule: any = new MockRule()
      rule.unitsRequiringOrder = (b: typeof board) => board.units
      try {
        rule.resolve(board, new Set())
      } catch (e) {
        e.should.deep.equal("F Nap: no order")
      }
    })
  })
})


text:
.. _overview_v2:

Overview
########

The Zephyr kernel lies at the heart of every Zephyr application. It provides
a low footprint, high performance, multi-threaded execution environment
with a rich set of available features. The rest of the Zephyr ecosystem,
including device drivers, networking stack, and application-specific code,
uses the kernel's features to create a complete application.

The configurable nature of the kernel allows you to incorporate only those
features needed by your application, making it ideal for systems with limited
amounts of memory (as little as 2 KB!) or with simple multi-threading
requirements (such as a set of interrupt handlers and a single background task).
Examples of such systems include: embedded sensor hubs, environmental sensors,
simple LED wearables, and store inventory tags.

Applications requiring more memory (50 to 900 KB), multiple communication
devices (like WiFi and Bluetooth Low Energy), and complex multi-threading,
can also be developed using the Zephyr kernel. Examples of such systems
include: fitness wearables, smart watches, and IoT wireless gateways.

.. toctree::
   :maxdepth: 1

   source_tree.rst
   changes.rst