text:
import settings
import argparse
import csv
import easypost
import os
import requests
import shutil
import time

from slugify import slugify

"""
Program to take a CSV of book orders and use the EasyPost API to buy and create
labels for each order.

NOTE: There are custom values here for Hello Web App that should be overridden
if you're using this for your own items.
"""

def import_csv():
    csv_rows = []

    # import csv
    print "Importing CSV."
    with open('orders.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            csv_rows.append(row)

    # remove the first row as it's just header information
    csv_rows.pop(0)
    return csv_rows

def setup_customs(canada, type):
    if type == "1":
        customs_item1 = easypost.CustomsItem.create(**settings.HWA1_DESCRIPTION)
    elif type == "2":
        customs_item1 = easypost.CustomsItem.create(**settings.HWA2_DESCRIPTION)
    elif type == "12":
        customs_item1 = easypost.CustomsItem.create(**settings.DOUBLE_ITEM_DESCRIPTION)

    eel_pfc = 'NOEEI 30.37(a)'
    if canada:
        eel_pfc = 'NOEEI 30.36'

    customs_info = easypost.CustomsInfo.create(
        eel_pfc = eel_pfc,
        customs_certify = True,
        customs_signer = 'Tracy Osborn',
        contents_type = 'merchandise',
        customs_items = [customs_item1,]
    )

    return customs_info

def setup_shipment(row, from_address, days_advance, type, customs=None):
    #print "Setting up the shipment."

    to_address = easypost.Address.create(
      name = row[0],
      street1 = row[1],
      street2 = row[2],
      city = row[3],
      state = row[4],
      zip = row[5],
      country = row[6],
    )

    if not row[7]:
        raise ValueError("Missing package type.")

    if type == "1":
        weight = "10"
    elif type == "2":
        weight = "13"
    elif type == "12":
        weight = "21"

    parcel = easypost.Parcel.create(
      predefined_package = 'Parcel',
      weight = weight,
    )

    shipment = easypost.Shipment.create(
      to_address = to_address,
      from_address = from_address,
      parcel = parcel,
      customs_info = customs,
      options = {
          'special_rates_eligibility':'USPS.MEDIAMAIL',
          'date_advance': days_advance,
      }
    )

    return shipment

def buy_postage(shipment, speed="normal"):
    """
    Can choose from several different shipping rates:
    - normal (Media Mail for US, first for International)
    - premium (Priority for US, not offered for International)
    - urgent (Overnight for US, not offered for International)
    """

    if speed == "premium":
        shipment.buy(rate=shipment.lowest_rate(carriers=['USPS'], services=['Priority']))
    elif speed == "urgent":
        shipment.buy(rate=shipment.lowest_rate(carriers=['USPS'], services=['Express']))
    else:
        shipment.buy(rate=shipment.lowest_rate(carriers=['USPS'],))

    #print "Speed: %s" % shipment.rate
    return shipment

def export_postage(label_url, file_name):
    url = label_url

    response = requests.get(url, stream=True)
    with open(file_name, 'wb') as out_file:
        shutil.copyfileobj(response.raw, out_file)
    del response

def main():
    # Will default to creating labels for today that will need to be shipped
    # within 24 hours. Add the days argument to change the date.t
    parser = argparse.ArgumentParser(description='Create shipping labels from EasyPost.com.')
    parser.add_argument('--days', dest='days', metavar='N', type=int, help='Days from now that you want to ship the label(s). Default is today.', default=0)

    args = parser.parse_args()
    days_advance = args.days

    easypost.api_key = os.getenv('EASYPOST_API_KEY')
    if not easypost.api_key:
        raise ValueError("Missing EASYPOST_API_KEY env var.")

    date = time.strftime("%Y-%m-%d")
    from_address = easypost.Address.create(**settings.FROM_ADDRESS)

    # import csv
    csv_rows = import_csv()

    # create folder for labels
    directory = "labels/%s" % date
    if not os.path.exists(directory):
        os.makedirs(directory)

    # set up logging file
    file = open(os.path.join(directory, "log.csv"), "a")

    # track the total cost
    total_cost = 0

    for i, row in enumerate(csv_rows):
        print i, row
        domestic = False
        canada = False
        customs = []
        name = row[0]

        # set file name (so we can check whether it's already been created)
        file_name = "%s/img-%s.png" % (directory, slugify(name))
        if os.path.isfile(file_name):
            print "Label exists!"
            continue

        # set variables for speed, location, and which books
        type = row[7]
        speed = row[8]
        if row[6] == "US":
            domestic = True
        elif row[6] == "CA":
            canada = True

        # set up customs for international
        if not domestic:
            customs = setup_customs(canada, type)

        # set up the shipment
        shipment = setup_shipment(row, from_address, days_advance, type, customs)

        # buy the postage
        shipment = buy_postage(shipment, speed)

        # print label
        label_url = shipment["postage_label"]["label_url"]
        selected_service = shipment["selected_rate"]["service"]
        selected_rate = shipment["selected_rate"]["rate"]
        tracking_code = shipment["tracker"]["tracking_code"]

        print "Label URL: %s" % label_url
        print "Selected rate: USPS %s $%s" % (selected_service, selected_rate)
        print "Tracking code: %s" % tracking_code

        #print "Exporting image."
        export_postage(label_url, file_name)

        file.write(u"%s,%s,$%s,%s,%s\n" % (name.decode('ascii', 'ignore'), tracking_code, label_url, selected_service, selected_rate))
        total_cost += float(selected_rate)
        print "Total cost so far: $%s" % total_cost
        print "------"

    file.write("$%s" % total_cost)
    file.close()

if __name__ == "__main__":
    main()


text:
/**
The following batches are equivalent:

var beautify_js = require('js-beautify');
var beautify_js = require('js-beautify').js;
var beautify_js = require('js-beautify').js_beautify;

var beautify_css = require('js-beautify').css;
var beautify_css = require('js-beautify').css_beautify;

var beautify_html = require('js-beautify').html;
var beautify_html = require('js-beautify').html_beautify;

All methods returned accept two arguments, the source string and an options object.
**/

function get_beautify(js_beautify, css_beautify, html_beautify) {
    // the default is js
    var beautify = function(src, config) {
        return js_beautify.js_beautify(src, config);
    };

    // short aliases
    beautify.js = js_beautify.js_beautify;
    beautify.css = css_beautify.css_beautify;
    beautify.html = html_beautify.html_beautify;

    // legacy aliases
    beautify.js_beautify = js_beautify.js_beautify;
    beautify.css_beautify = css_beautify.css_beautify;
    beautify.html_beautify = html_beautify.html_beautify;

    return beautify;
}

if (typeof define === "function" && define.amd) {
    // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
    define([
        "./lib/beautify",
        "./lib/beautify-css",
        "./lib/beautify-html"
    ], function(js_beautify, css_beautify, html_beautify) {
        return get_beautify(js_beautify, css_beautify, html_beautify);
    });
} else {
    (function(mod) {
        var js_beautify = require('./lib/beautify');
        var css_beautify = require('./lib/beautify-css');
        var html_beautify = require('./lib/beautify-html');

        mod.exports = get_beautify(js_beautify, css_beautify, html_beautify);

    })(module);
}

redpajama_set_name: RedPajamaGithub


text:
package com.vk.api.sdk.exceptions;

public class ApiAppsSubscriptionNotFoundException extends ApiException {
    public ApiAppsSubscriptionNotFoundException(String message) {
        super(1256, "Subscription not found", message);
    }
}


text:
namespace Bloom.Browser.Modules.LibraryModule.ViewModels
{
    /// <summary>
    /// View model for TilesView.xaml
    /// </summary>
    public class TilesViewModel
    {
    }
}


text:
static class UtilAlgumaCoisa {
    public static void ProcessaTeclas(Keys key, SpeechSynthesizer sintetiza) {
        if (key >= Keys.NumPad0 && key <= Keys.NumPad9) sintetiza.SpeakAsync(((char)(48 + Keys.NumPad0 - key)).ToString());
        if (key >= Keys.D0 && key <= Keys.D9) sintetiza.SpeakAsync(((char)(48 + Keys.D0 - key)).ToString());
    }
}

//https://pt.stackoverflow.com/q/141045/101


text:
package com.hacklechalet.gravitris;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.Fixture;
import org.jbox2d.dynamics.joints.DistanceJointDef;

import javax.microedition.khronos.opengles.GL10;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.Vector;

/**
 * Created by krozark on 25/05/13.
 */
public class Wall  extends  PhysiqueObject{
    // Our vertices.
    private Vector2<Float> top_left; //0,0
    private Vector2<Float> top_right;//1,0
    private Vector2<Float> bottom_left;//1,1
    private Vector2<Float> bottom_right;//0,1
    // The order we like to connect them.
    private short[] indices = { 0, 1, 2, 2, 1, 3 };

    public final static int DIRECTION_TOP = 1;
    public final static int DIRECTION_RIGHT = 2;
    public final static int DIRECTION_BOTTOM = 3;
    public final static int DIRECTION_LEFT = 4;

    float[] colors = {
            1f, 0f, 0f, 1f, // vertex 0 red
            0f, 1f, 0f, 1f, // vertex 1 green
            0f, 0f, 1f, 1f, // vertex 2 blue
            1f, 0f, 1f, 1f, // vertex 3 magenta
    };

    // Our vertex buffer.
    private FloatBuffer vertexBuffer;
    // Our index buffer.
    private ShortBuffer indexBuffer;
    private FloatBuffer colorBuffer;

    private Vector<Fixture> joinFixtureList;

    private float X;
    private float Y;

    public Wall(float x,float y,float posx,float posy)
    {
        super(posx,posy, BodyType.STATIC);

        top_left = new Vector2<Float>(0f,0f);
        top_right = new Vector2<Float>((float)1*x,0f);
        bottom_left = new Vector2<Float>(0f, (float)1*y);
        bottom_right = new Vector2<Float>((float)1*x,(float)1*y);

        // short is 2 bytes, therefore we multiply the number if
        // vertices with 2.
        ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
        ibb.order(ByteOrder.nativeOrder());
        indexBuffer = ibb.asShortBuffer();
        indexBuffer.put(indices);
        indexBuffer.position(0);

        ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
        cbb.order(ByteOrder.nativeOrder());
        colorBuffer = cbb.asFloatBuffer();
        colorBuffer.put(colors);
        colorBuffer.position(0);

        setSize(x,y);
        shape.setAsBox(toMet(x/2),toMet(y/2));
        fixtureDef.shape = shape;
        fixture = body.createFixture(fixtureDef);
        //majPosition();

        joinFixtureList = new Vector<Fixture>();
    }

    private void setPosition(float x,float y)
    {
        top_left.x = x*X;
        top_left.y = y*Y;

        top_right.x = x*X+X;
        top_right.y = y*Y;

        bottom_left.x = x*X;
        bottom_left.y = y*Y+Y;

        bottom_right.x = x*X+X;
        bottom_right.y = y*Y+Y;
    }

    private void majPosition()
    {
        Vec2 origine = body.getPosition();
        setPosition(toPix(origine.x),toPix(origine.y));
    }

    private void setRotation(float angle)
    {

    }

    public Vector2<Float> getPosition()
    {
        return new Vector2<Float>(top_left.x+X,top_left.y+Y);
    }

    private void setSize(float x,float y)
    {
        X=x;
        Y=y;
    }

    private void next()
    {
        majPosition();
        setRotation(-toDeg(body.getAngle()));
    }

    public void draw(GL10 gl) {
        next();

        float matrixVertices[] = {
                top_left.x,  top_left.y, 0.0f,  // 0, Top Left
                top_right.x,  top_right.y, 0.0f,  // 3, Top Right
                bottom_left.x, bottom_left.y, 0.0f,  // 1, Bottom Left
                bottom_right.x, bottom_right.y, 0.0f,  // 2, Bottom Right
        };
        // a float is 4 bytes, therefore we multiply the number if
        // vertices with 4.
        ByteBuffer vbb = ByteBuffer.allocateDirect(matrixVertices.length * 4);
        vbb.order(ByteOrder.nativeOrder());
        vertexBuffer = vbb.asFloatBuffer();
        vertexBuffer.put(matrixVertices);
        vertexBuffer.position(0);

        // Counter-clockwise winding.
        gl.glFrontFace(GL10.GL_CCW);
        // Enable face culling.
        gl.glEnable(GL10.GL_CULL_FACE);
        // What faces to remove with the face culling.
        gl.glCullFace(GL10.GL_BACK);

        // Enabled the vertices buffer for writing and to be used during
        // rendering.
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        // Specifies the location and data format of an array of vertex
        // coordinates to use when rendering.
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);

        gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // NEW LINE ADDED.
        // Point out the where the color buffer is.
        gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer); // NEW LINE ADDED

        gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_SHORT, indexBuffer);

        // Disable the vertices buffer.
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        // Disable face culling.
        gl.glDisable(GL10.GL_CULL_FACE);
    }
}


text:
import { Component, OnInit, HostListener } from '@angular/core';
import { AppComponent } from 'app/app.component';
import { Product, Brand } from 'app/shared/models';
import { ProductService } from 'app/services/product.service';

@Component({
    selector: 'app-home',
    templateUrl: 'home.component.html'
})
export class HomeComponent implements OnInit {
    fixedCols: number;
    fitListHeight: string;
    fitListWidth: string;
    featured: Product[];
    news: Product[];
    brands: Brand[];

    constructor(private productService: ProductService) {
        this.onResizeChanged(window);
		AppComponent.setPage('Home');
    }

    @HostListener('window:resize', ['$event'])
    onResize(event) {
      this.onResizeChanged(event.target);
    }

    ngOnInit() {
        this.productService
            .getFeatured()
            .subscribe(result => {
                this.featured = result;
            });
        this.productService
            .getNews()
            .subscribe(result => {
                this.news = result;
            });
        this.productService
            .getBrands()
            .subscribe(result => {
                this.brands = result;
            });
    }

    onResizeChanged(event: any) {
        const w = event.innerWidth;
        this.fixedCols = w < 600 ? 1 : w < 1200 ? 2 : 3;
        this.fitListWidth = (w - this.fixedCols - 1) + 'px';
        this.fitListHeight = (w / this.fixedCols * 1.2) + 'px';
    }
}


text:
title: '**Nicole Krauss** <br> *Forest Dark*'
published: true
start_at: 2017-09-15 19:00:00
image_path:
book_category:
program: '-writers-and-readers'
ticketed: true
related_books:
  - forest-dark
---

**SOLD OUT, but there will be a stand-by ticket line at the event. Nicole's 8pm book signing will be open to all.**

**In conversation with [James Wood](http://www.brooklinebooksmith-shop.com/search/author/%22Wood%2C%20James%22). ****This event will take place in the Used Book Cellar.**

New York Times bestselling author of *The History of Love* Nicole Krauss conjures an achingly beautiful novel about personal transformation, interweaving the stories of an older lawyer and a young novelist whose transcendental search leads them to the same Israeli desert.


text:
package org.apache.spark.sql.catalyst.optimizer

import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
import org.apache.spark.sql.catalyst.expressions.Expression
import org.apache.spark.sql.catalyst.expressions.aggregate._
import org.apache.spark.sql.catalyst.plans.PlanTest
import org.apache.spark.sql.catalyst.plans.logical.{LocalRelation, LogicalPlan}
import org.apache.spark.sql.catalyst.rules.RuleExecutor

class EliminateDistinctSuite extends PlanTest {

  object Optimize extends RuleExecutor[LogicalPlan] {
    val batches =
      Batch("Operator Optimizations", Once,
        EliminateDistinct) :: Nil
  }

  val testRelation = LocalRelation('a.int)

  Seq(
    Max(_),
    Min(_),
    BitAndAgg(_),
    BitOrAgg(_),
    First(_, ignoreNulls = true),
    First(_, ignoreNulls = false),
    Last(_, ignoreNulls = true),
    Last(_, ignoreNulls = false),
    CollectSet(_: Expression)
  ).foreach {
    aggBuilder =>
      val agg = aggBuilder('a)
      test(s"Eliminate Distinct in $agg") {
        val query = testRelation
          .select(agg.toAggregateExpression(isDistinct = true).as('result))
          .analyze
        val answer = testRelation
          .select(agg.toAggregateExpression(isDistinct = false).as('result))
          .analyze
        assert(query != answer)
        comparePlans(Optimize.execute(query), answer)
      }
  }
}


text:
@interface DeviceManagerViewController : BaseCellTableViewController

@end


text: eval `dircolors "${ZSH}/custom/dircolors-solarized/dircolors.ansi-dark"`


text:
package org.apache.flink.state.changelog;

import org.apache.flink.runtime.state.changelog.SequenceNumber;
import org.apache.flink.runtime.state.changelog.StateChangelogWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.NavigableMap;
import java.util.TreeMap;

/**
 * A helper class to track changelog usage by {@link ChangelogKeyedStateBackend}. A changelog
 * segment is not used when:
 *
 *

 *
All the checkpoints using it were subsumed, and
 *
Is was materialized (and therefore will not be used in future checkpoints)
 *

 *
 *
At this point, {@link org.apache.flink.runtime.state.changelog.StateChangelogWriter} is
 * notified and will {@link org.apache.flink.runtime.state.changelog.StateChangelogWriter#truncate
 * truncate} the changelog. That implies discarding any (changelog) state that is not known to JM.
 */
class ChangelogTruncateHelper {
    private static final Logger LOG = LoggerFactory.getLogger(ChangelogTruncateHelper.class);

    private final StateChangelogWriter<?> stateChangelogWriter;
    private final NavigableMap<Long, SequenceNumber> checkpointedUpTo = new TreeMap<>();

    private SequenceNumber subsumedUpTo;

    private SequenceNumber materializedUpTo;

    ChangelogTruncateHelper(StateChangelogWriter<?> stateChangelogWriter) {
        this.stateChangelogWriter = stateChangelogWriter;
    }

    /**
     * Set the highest {@link SequenceNumber} of changelog used by the given checkpoint.
     *
     * @param lastUploadedTo exclusive
     */
    public void checkpoint(long checkpointId, SequenceNumber lastUploadedTo) {
        checkpointedUpTo.put(checkpointId, lastUploadedTo);
    }

    /** Handle checkpoint subsumption, potentially {@link #truncate() truncating} the changelog. */
    public void checkpointSubsumed(long checkpointId) {
        SequenceNumber sqn = checkpointedUpTo.get(checkpointId);
        LOG.debug("checkpoint {} subsumed, max sqn: {}", checkpointId, sqn);
        if (sqn != null) {
            subsumedUpTo = sqn;
            checkpointedUpTo.headMap(checkpointId, true).clear();
            truncate();
            stateChangelogWriter.subsume(checkpointId);
        }
    }

    /**
     * Handle changelog materialization, potentially {@link #truncate() truncating} the changelog.
     *
     * @param upTo exclusive
     */
    public void materialized(SequenceNumber upTo) {
        materializedUpTo = upTo;
        truncate();
    }

    private void truncate() {
        if (subsumedUpTo != null && materializedUpTo != null) {
            SequenceNumber to =
                    subsumedUpTo.compareTo(materializedUpTo) < 0 ? subsumedUpTo : materializedUpTo;
            LOG.debug(
                    "truncate changelog to {} (subsumed up to: {}, materialized up to: {})",
                    to,
                    subsumedUpTo,
                    materializedUpTo);
            stateChangelogWriter.truncate(to);
        }
    }
}


text:
package org.apache.beam.sdk.util;

import static com.google.common.base.Preconditions.checkArgument;

import java.io.IOException;
import org.apache.beam.sdk.options.GcsOptions;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.util.gcsfs.GcsPath;

/**
 * GCP implementation of {@link PathValidator}. Only GCS paths are allowed.
 */
public class GcsPathValidator implements PathValidator {

  private GcsOptions gcpOptions;

  private GcsPathValidator(GcsOptions options) {
    this.gcpOptions = options;
  }

  public static GcsPathValidator fromOptions(PipelineOptions options) {
    return new GcsPathValidator(options.as(GcsOptions.class));
  }

  /**
   * Validates the the input GCS path is accessible and that the path
   * is well formed.
   */
  @Override
  public String validateInputFilePatternSupported(String filepattern) {
    GcsPath gcsPath = getGcsPath(filepattern);
    checkArgument(gcpOptions.getGcsUtil().isGcsPatternSupported(gcsPath.getObject()));
    String returnValue = verifyPath(filepattern);
    verifyPathIsAccessible(filepattern, "Could not find file %s");
    return returnValue;
  }

  /**
   * Validates the the output GCS path is accessible and that the path
   * is well formed.
   */
  @Override
  public String validateOutputFilePrefixSupported(String filePrefix) {
    String returnValue = verifyPath(filePrefix);
    verifyPathIsAccessible(filePrefix, "Output path does not exist or is not writeable: %s");
    return returnValue;
  }

  @Override
  public String verifyPath(String path) {
    GcsPath gcsPath = getGcsPath(path);
    checkArgument(gcsPath.isAbsolute(), "Must provide absolute paths for Dataflow");
    checkArgument(!gcsPath.getObject().contains("//"),
        "Dataflow Service does not allow objects with consecutive slashes");
    return gcsPath.toResourceName();
  }

  private void verifyPathIsAccessible(String path, String errorMessage) {
    GcsPath gcsPath = getGcsPath(path);
    try {
      checkArgument(gcpOptions.getGcsUtil().bucketAccessible(gcsPath),
        errorMessage, path);
    } catch (IOException e) {
      throw new RuntimeException(
          String.format("Unable to verify that GCS bucket gs://%s exists.", gcsPath.getBucket()),
          e);
    }
  }

  private GcsPath getGcsPath(String path) {
    try {
      return GcsPath.fromUri(path);
    } catch (IllegalArgumentException e) {
      throw new IllegalArgumentException(String.format(
          "%s expected a valid 'gs://' path but was given '%s'",
          gcpOptions.getRunner().getSimpleName(), path), e);
    }
  }
}


text:
<?php

namespace Telegram\Bot\Objects;

/**
 * Class ChatPermissions.
 *
 * @link https://core.telegram.org/bots/api#chatpermissions
 *
 * @property bool|null $canSendMessages       (Optional). True, if the user is allowed to send text messages, contacts, locations and venues
 * @property bool|null $canSendMediaMessages  (Optional). True, if the user is allowed to send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages
 * @property bool|null $canSendPolls          (Optional). True, if the user is allowed to send polls, implies can_send_messages
 * @property bool|null $canSendOtherMessages  (Optional). True, if the user is allowed to send animations, games, stickers and use inline bots, implies can_send_media_messages
 * @property bool|null $canAddWebPagePreviews (Optional). True, if the user is allowed to add web page previews to their messages, implies can_send_media_messages
 * @property bool|null $canChangeInfo         (Optional). True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups
 * @property bool|null $canInviteUsers        (Optional). True, if the user is allowed to invite new users to the chat
 * @property bool|null $canPinMessages        (Optional). True, if the user is allowed to pin messages. Ignored in public supergroups
 */
class ChatPermissions extends BaseObject
{
    /**
     * {@inheritdoc}
     */
    public function relations()
    {
        return [];
    }
}


text:
from setuptools import setup, find_packages

setup(
    name='frasco-twitter',
    version='0.1',
    url='http://github.com/frascoweb/frasco-twitter',
    license='MIT',
    author='Maxime Bouroumeau-Fuseau',
    author_email='maxime.bouroumeau@gmail.com',
    description="Twitter integration for Frasco",
    packages=find_packages(),
    zip_safe=False,
    platforms='any',
    install_requires=[
        'frasco-users'
    ]
)


text:
layout: default
---

My creative works & inspiration

First major open source contribution

UX Development on Easterns Digital Initittive team

Spokane advicate & organizer 2017 DjangoCon US

VR cardboard Vinyl sticker wrap

Organized 2016 & 17 frontend competition in Spokane

Eagle icon for EWU  Gitlabs

My web III Makey Makey project: codepen

Icon concept for VR

Washington State + Spokane + Marmot = icon

Experimentation with hand lettering

Prototype UI design for EWU Dining app

Heart coffee, Portland

Breaking out my old school ink set

My 8bit art project more images on flickr

Persona photo layout


text:
import React from 'react';
import ReactDOM from 'react-dom';
import RestParameters from './RestParameters';

describe('rest parameters', () => {
  it('renders without crashing', () => {
    const div = document.createElement('div');
    ReactDOM.render(<RestParameters />, div);
  });
});


text:
package org.culturegraph.mf.stream.converter.bib;

import org.culturegraph.mf.exceptions.FormatException;
import org.culturegraph.mf.framework.DefaultStreamPipe;
import org.culturegraph.mf.framework.ObjectReceiver;
import org.culturegraph.mf.framework.StreamReceiver;
import org.culturegraph.mf.framework.annotations.Description;
import org.culturegraph.mf.framework.annotations.FluxCommand;
import org.culturegraph.mf.framework.annotations.In;
import org.culturegraph.mf.framework.annotations.Out;
import org.culturegraph.mf.iso2709.Iso2709Format;
import org.culturegraph.mf.iso2709.RecordBuilder;
import org.culturegraph.mf.iso2709.RecordFormat;
import org.culturegraph.mf.stream.converter.xml.MarcXmlHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Encodes a stream in MARC21 format.
 *

 * MARC21 supports two types of fields: reference fields and data fields.
 * Reference fields consist of a name tag and a single value. Data fields have a
 * name tag, two indicators and consist of subfields which have an identifier
 * each.
 *

 * The {@code Marc21Encoder} encodes a stream as follows:
 *

 *
top-level literals are encoded as reference fields. Their name must match
 *   the requirements for reference field tags in ISO 2709:2008 records.
 *
 *
entities are encoded as data fields. Only one level of entities is
 *   supported. The entity name must consist of a three letter tag name followed
 *   by two indicator characters. The tag name must follow the requirements for
 *   data field tags in ISO 2709:2008 records.
 *
 *
Literals in entities are encoded as subfields. The literal name is used
 *   as subfield indicator and must therefore be a single character.
 *
 *
If a literal named "leader" is encountered it is treated as a ISO
 *   2709:2008 record label and some of its contents (record status,
 *   implementation codes, user system characters) are copied into the generated
 *   record
 *
 *
literal named "type", which may be produced by {@link MarcXmlHandler}
 *   are ignored.
 *

 *
 *
The stream expected by the encoder is compatible to the streams emitted by
 * the {@link Marc21Decoder} and the {@link MarcXmlHandler}.
 *

 *
 *
The record identifier in {@code startRecord} is ignored. To add an
 * identifier to the MARC21 record a reference field with tag name 001 need to
 * be added.
 *
 * @throws FormatException
 *             if the stream cannot be converted into a MARC21 record.
 *
 * @author Christoph Böhme
 *
 */
@In(StreamReceiver.class)
@Out(String.class)
@Description("Encodes MARC21 records")
@FluxCommand("encode-marc21")
public final class Marc21Encoder extends
		DefaultStreamPipe<ObjectReceiver<String>> {

	private static Logger LOG = LoggerFactory.getLogger(Marc21Encoder.class);

	private static final RecordFormat MARC21 = new RecordFormat();

	public static final String LEADER_LITERAL = "leader";
	public static final String TYPE_LITERAL = "type";

	private final RecordBuilder builder = new RecordBuilder(MARC21);
	private final int nameLength;

	private boolean inField;

	static {
		MARC21.setIndicatorLength(2);
		MARC21.setIdentifierLength(2);
		MARC21.setFieldLengthLength(4);
		MARC21.setFieldStartLength(5);
		MARC21.setImplDefinedPartLength(0);
	}

	public Marc21Encoder() {
		super();
		nameLength = Iso2709Format.TAG_LENGTH + MARC21.getIndicatorLength();
	}

	@Override
	public void startRecord(final String identifier) {
		inField = false;
		builder.reset();
	}

	@Override
	public void endRecord() {
		getReceiver().process(builder.toString());
	}

	@Override
	public void startEntity(final String name) {
		if (name.length() != nameLength) {
			throw new FormatException("invalid entity name: " + name);
		}

		final String tag = name.substring(0, Iso2709Format.TAG_LENGTH);
		final String indicators = name.substring(Iso2709Format.TAG_LENGTH);
		builder.startField(tag, indicators);
		inField = true;
	}

	@Override
	public void endEntity() {
		inField = false;
		builder.endField();
	}

	@Override
	public void literal(final String name, final String value) {
		if (inField) {
			builder.appendSubfield(name, value);
		} else {
			if (LEADER_LITERAL.equals(name)) {
				setRecordLabel(value);
			} else if (TYPE_LITERAL.equals(name)) {
				// MarcXmlHandler may output `type` literals. The
				// information in these literals is not included in
				// marc21 records. Therefore, we need to ignore
				// these literals here.
				return;
			} else {
				builder.appendReferenceField(name, value);
			}
		}
	}

	private void setRecordLabel(final String value) {
		if (value.length() != Iso2709Format.RECORD_LABEL_LENGTH) {
			throw new FormatException("leader must be 24 characters long");
		}
		builder.setRecordStatus(value.charAt(Iso2709Format.RECORD_STATUS_POS));
		builder.setImplCodes(value.substring(Iso2709Format.IMPL_CODES_START,
				Iso2709Format.IMPL_CODES_END));
		builder.setSystemChars(value.substring(
				Iso2709Format.SYSTEM_CHARS_START,
				Iso2709Format.SYSTEM_CHARS_END));
	}

}


text:
class ProjectUser < ActiveRecord::Base

  belongs_to :project
  belongs_to :user
  auto_subscribes :user, :to => :project

  after_save :check_role, :remove_updates, :subscribe_to_assessment_sections_later
  after_destroy :remove_updates
  validates_uniqueness_of :user_id, :scope => :project_id, :message => "already a member of this project"
  validates_presence_of :project, :user
  validates_rules_from :project, :rule_methods => [:has_time_zone?]
  validate :user_invited?

  CURATOR_CHANGE_NOTIFICATION = "curator_change"
  ROLES = %w(curator manager)
  ROLES.each do |role|
    const_set role.upcase, role
    scope role.pluralize, where(:role => role)
  end

  notifies_subscribers_of :project, :on => :save, :notification => CURATOR_CHANGE_NOTIFICATION,
    :include_notifier => true,
    # don't bother queuing this if there's no relevant role change
    :queue_if => Proc.new {|pu|
      pu.role_changed? && (ROLES.include?(pu.role) || pu.user_id == pu.project.user_id)
    },
    # check to make sure role status hasn't changed since queuing
    :if => Proc.new {|pu| ROLES.include?(pu.role) || pu.user_id == pu.project.user_id}

  def to_s
    "<ProjectUser #{id} project: #{project_id} user: #{user_id} role: #{role}>"
  end

  def project_observations
    project.project_observations.includes(:observation).where("observations.user_id = ?", user_id).scoped
  end

  def remove_updates
    return true unless role_changed? && role.blank?
    Update.where(
      :notifier_type => "ProjectUser",
      :notifier_id => id,
      :resource_type => "Project",
      :resource_id => project_id).destroy_all
    true
  end

  def subscribe_to_assessment_sections_later
    return true unless role_changed? && !role.blank?
    delay(:priority => USER_INTEGRITY_PRIORITY).subscribe_to_assessment_sections
    true
  end

  def subscribe_to_assessment_sections
    AssessmentSection.includes(:assessment).where("assessments.project_id = ?", project).find_each do |as|
      Subscription.create(:resource => as, :user => user)
    end
  end

  def has_time_zone?
    user.time_zone?
  end

  def is_curator?
    role == 'curator' || is_manager? || is_admin?
  end

  def is_manager?
    role == 'manager' || is_admin?
  end

  def is_admin?
    user_id == project.user_id
  end

  def user_invited?
    return true unless project
    return true if project.preferred_membership_model == Project::MEMBERSHIP_OPEN
    uid = user_id || user.try(:id)
    pid = project_id || project.try(:id)
    unless ProjectUserInvitation.where(:invited_user_id => uid, :project_id => pid).exists?
      errors.add(:user, "hasn't been invited to this project")
    end
  end

  def update_observations_counter_cache
    update_attributes(:observations_count => project_observations.count)
  end

  # set taxa_count on project user, which is the number of taxa observed by this user, favoring the curator ident
  def update_taxa_counter_cache
    sql = <<-SQL
      SELECT count(DISTINCT COALESCE(i.taxon_id, o.taxon_id))
      FROM project_observations po
        JOIN observations o ON po.observation_id = o.id
        LEFT OUTER JOIN taxa ot ON ot.id = o.taxon_id
        LEFT OUTER JOIN identifications i ON po.curator_identification_id = i.id
        LEFT OUTER JOIN taxa it ON it.id = i.taxon_id
      WHERE
        po.project_id = #{project_id}
        AND o.user_id = #{user_id}
        AND (
          -- observer's ident taxon is species or lower
          ot.rank_level <= #{Taxon::SPECIES_LEVEL}
          -- curator's ident taxon is species or lower
          OR it.rank_level <= #{Taxon::SPECIES_LEVEL}
        )
    SQL
    update_attributes(:taxa_count => ProjectUser.connection.execute(sql)[0]['count'].to_i)
  end

  def check_role
    return true unless role_changed?
    if role_was.blank?
      Project.delay(:priority => USER_INTEGRITY_PRIORITY).update_curator_idents_on_make_curator(project_id, id)
    elsif role.blank?
      Project.delay(:priority => USER_INTEGRITY_PRIORITY).update_curator_idents_on_remove_curator(project_id, id)
    end
    true
  end

  def self.update_observations_counter_cache_from_project_and_user(project_id, user_id)
    return unless project_user = ProjectUser.first(:conditions => {
      :project_id => project_id,
      :user_id => user_id
    })
    project_user.update_observations_counter_cache
  end

  def self.update_taxa_counter_cache_from_project_and_user(project_id, user_id)
    return unless project_user = ProjectUser.first(:conditions => {
      :project_id => project_id,
      :user_id => user_id
    })
    project_user.update_taxa_counter_cache
  end

  def self.update_taxa_obs_and_observed_taxa_count_after_update_observation(observation_id, user_id)
    unless obs = Observation.find_by_id(observation_id)
      return
    end
    unless usr = User.find_by_id(user_id)
      return
    end
    obs.project_observations.each do |po|
      if project_user = ProjectUser.first(:conditions => {
        :project_id => po.project_id,
        :user_id => user_id
      })
        project_user.update_taxa_counter_cache
        project_user.update_observations_counter_cache
        Project.update_observed_taxa_count(po.project_id)
      end
    end
  end
end


text:
namespace agent
{
  class Agent;
  namespace goal
  {
    class MoveToPosition : public GoalComposite<Agent>
    {
    private:
      world::Position destination_;

    public:

      MoveToPosition(std::weak_ptr<Agent> owner, world::Position gPos)
	: GoalComposite<Agent>(owner, EType::move_to_position),
	  destination_(gPos)
      {}

      auto activate() -> void;
      auto process() -> EStat;
      auto terminate() -> void
      {}

    };
  } // namespace goal
} // namespace agent

#endif


text:
package org.apache.shardingsphere.elasticjob.infra.yaml.config;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;

/**
 * Factory for {@link YamlConfigurationConverter}.
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class YamlConfigurationConverterFactory {

    private static final Map<Class<?>, YamlConfigurationConverter<?, ?>> CONVERTERS = new LinkedHashMap<>();

    static {
        ServiceLoader.load(YamlConfigurationConverter.class).forEach(each -> CONVERTERS.put(each.configurationType(), each));
    }

    /**
     * Find {@link YamlConfigurationConverter} for specific configuration type.
     *
     * @param configurationType type of configuration
     * @param <T> type of configuration
     * @param <Y> type of YAML configuration
     * @return converter for specific configuration type
     */
    @SuppressWarnings("unchecked")
    public static <T, Y extends YamlConfiguration<T>> Optional<YamlConfigurationConverter<T, Y>> findConverter(final Class<T> configurationType) {
        return Optional.ofNullable((YamlConfigurationConverter<T, Y>) CONVERTERS.get(configurationType));
    }
}


text:
import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { JhiMetricsMonitoringModalComponent } from './metrics-modal.component';
import { JhiMetricsService } from './metrics.service';

@Component({
    selector: 'jhi-metrics',
    templateUrl: './metrics.component.html'
})
export class JhiMetricsMonitoringComponent implements OnInit {
    metrics: any = {};
    cachesStats: any = {};
    servicesStats: any = {};
    updatingMetrics = true;
    JCACHE_KEY: string;

    constructor(
        private modalService: NgbModal,
        private metricsService: JhiMetricsService
    ) {
        this.JCACHE_KEY = 'jcache.statistics';
    }

    ngOnInit() {
        this.refresh();
    }

    refresh() {
        this.updatingMetrics = true;
        this.metricsService.getMetrics().subscribe((metrics) => {
            this.metrics = metrics;
            this.updatingMetrics = false;
            this.servicesStats = {};
            this.cachesStats = {};
            Object.keys(metrics.timers).forEach((key) => {
                const value = metrics.timers[key];
                if (key.includes('web.rest') || key.includes('service')) {
                    this.servicesStats[key] = value;
                }
            });
            Object.keys(metrics.gauges).forEach((key) => {
                if (key.includes('jcache.statistics')) {
                    const value = metrics.gauges[key].value;
                    // remove gets or puts
                    const index = key.lastIndexOf('.');
                    const newKey = key.substr(0, index);

                    // Keep the name of the domain
                    this.cachesStats[newKey] = {
                        'name': this.JCACHE_KEY.length,
                        'value': value
                    };
                }
            });
        });
    }

    refreshThreadDumpData() {
        this.metricsService.threadDump().subscribe((data) => {
            const modalRef  = this.modalService.open(JhiMetricsMonitoringModalComponent, { size: 'lg'});
            modalRef.componentInstance.threadDump = data;
            modalRef.result.then((result) => {
                // Left blank intentionally, nothing to do here
            }, (reason) => {
                // Left blank intentionally, nothing to do here
            });
        });
    }

    filterNaN(input) {
        if (isNaN(input)) {
            return 0;
        }
        return input;
    }

}


text:
class Update < ActiveRecord::Migration
  def change
  	change_column :downloads, :bpm, :integer, :null => false
  	change_column :downloads, :genre, :string, :null => false
  end
end


text:
import abc

class Builder(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def make_title(self):
        pass

    @abc.abstractmethod
    def make_string(self):
        pass

    @abc.abstractmethod
    def make_items(self):
        pass

    @abc.abstractmethod
    def close(self):
        pass

class TextBuilder(Builder):
    def __init__(self):
        self.text = []

    def make_title(self, string):
        self.text.append('=' * 40)
        self.text.append(string)
        self.text.append('-' * 40)

    def make_string(self, string):
        self.text.append(string)

    def make_items(self, string_list):
        for string in string_list:
            self.text.append('- {}'.format(string))

    def close(self):
        self.text.append('=' * 40)

    def get_result(self):
        return '\n'.join(self.text)

class HTMLBuilder(Builder):
    def __init__(self):
        self.html = []

    def make_title(self, string):
        s = '''

        <title>{0}</title>

{0}

        '''.format(string)
        self.html.append(s)

    def make_string(self, string):
        self.html.append('
{}
'.format(string))

    def make_items(self, string_list):
        self.html.append('
')
        for string in string_list:
            self.html.append('
{}
'.format(string))
        self.html.append('
')

    def close(self):
        s = '''

        '''
        self.html.append(s)

    def get_result(self):
        return '\n'.join(self.html)

class Director:
    def __init__(self, builder):
        self.builder = builder

    def construct(self):
        self.builder.make_title('Builder Pattern Sample')
        self.builder.make_string('Sample Description')
        self.builder.make_items(['alma', 'blue', 'cirros'])
        self.builder.close()

if __name__ == '__main__':
    text_builder = TextBuilder()
    text_director = Director(text_builder)
    text_director.construct()
    print(text_builder.get_result())

    html_builder = HTMLBuilder()
    html_director = Director(html_builder)
    html_director.construct()
    print(html_builder.get_result())

    '''
========================================
Builder Pattern Sample
----------------------------------------
Sample Description
- alma
- blue
- cirros
========================================

        <title>Builder Pattern Sample</title>

Builder Pattern Sample

Sample Description

alma

blue

cirros

    '''


text:
$packageName = 'nsis.install'
$installerType = 'exe'
$silentArgs = '/S'
$url = 'https://sourceforge.net/projects/nsis/files/NSIS%203%20Pre-release/3.0b2/nsis-3.0b2-setup.exe/download'
$checksum = '2ac0eaf28d4d384496e8ff2984451391f85c06c6'
$checksumType = 'sha1'
$validExitCodes = @(0)

Install-ChocolateyPackage -PackageName "$packageName" `
                          -FileType "$installerType" `
                          -SilentArgs "$silentArgs" `
                          -Url "$url" `
                          -ValidExitCodes $validExitCodes `
                          -Checksum "$checksum" `
                          -ChecksumType "$checksumType"


text:
"""
    Onshape REST API

    The Onshape REST API consumed by all clients.  # noqa: E501

    The version of the OpenAPI document: 1.113
    Contact: api-support@onshape.zendesk.com
    Generated by: https://openapi-generator.tech
"""

from __future__ import absolute_import
import re  # noqa: F401
import sys  # noqa: F401

import six  # noqa: F401
import nulltype  # noqa: F401

from onshape_client.oas.model_utils import (  # noqa: F401
    ModelComposed,
    ModelNormal,
    ModelSimple,
    date,
    datetime,
    file_type,
    int,
    none_type,
    str,
    validate_get_composed_info,
)

try:
    from onshape_client.oas.models import btm_in_context_query2254
except ImportError:
    btm_in_context_query2254 = sys.modules[
        "onshape_client.oas.models.btm_in_context_query2254"
    ]
try:
    from onshape_client.oas.models import btm_individual_query138
except ImportError:
    btm_individual_query138 = sys.modules[
        "onshape_client.oas.models.btm_individual_query138"
    ]
try:
    from onshape_client.oas.models import btm_individual_query_with_occurrence_base904
except ImportError:
    btm_individual_query_with_occurrence_base904 = sys.modules[
        "onshape_client.oas.models.btm_individual_query_with_occurrence_base904"
    ]

class BTMIndividualQueryBase139(ModelNormal):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.

    Attributes:
      allowed_values (dict): The key is the tuple path to the attribute
          and the for var_name this is (var_name,). The value is a dict
          with a capitalized key describing the allowed value and an allowed
          value. These dicts store the allowed enum values.
      attribute_map (dict): The key is attribute name
          and the value is json key in definition.
      discriminator_value_class_map (dict): A dict to go from the discriminator
          variable value to the discriminator class name.
      validations (dict): The key is the tuple path to the attribute
          and the for var_name this is (var_name,). The value is a dict
          that stores validations for max_length, min_length, max_items,
          min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
          inclusive_minimum, and regex.
      additional_properties_type (tuple): A tuple of classes accepted
          as additional properties values.
    """

    allowed_values = {}

    validations = {}

    additional_properties_type = None

    @staticmethod
    def openapi_types():
        """
        This must be a class method so a model may have properties that are
        of type self, this ensures that we don't create a cyclic import

        Returns
            openapi_types (dict): The key is attribute name
                and the value is attribute type.
        """
        return {
            "bt_type": (str,),  # noqa: E501
            "deterministic_id_list": (BTMIndividualQueryBase139,),  # noqa: E501
            "deterministic_ids": ([str],),  # noqa: E501
            "import_microversion": (str,),  # noqa: E501
            "node_id": (str,),  # noqa: E501
            "query": (BTMIndividualQueryBase139,),  # noqa: E501
            "query_string": (str,),  # noqa: E501
        }

    @staticmethod
    def discriminator():
        return {
            "bt_type": {
                "BTMIndividualQuery-138": btm_individual_query138.BTMIndividualQuery138,
                "BTMInContextQuery-2254": btm_in_context_query2254.BTMInContextQuery2254,
            },
        }

    attribute_map = {
        "bt_type": "btType",  # noqa: E501
        "deterministic_id_list": "deterministicIdList",  # noqa: E501
        "deterministic_ids": "deterministicIds",  # noqa: E501
        "import_microversion": "importMicroversion",  # noqa: E501
        "node_id": "nodeId",  # noqa: E501
        "query": "query",  # noqa: E501
        "query_string": "queryString",  # noqa: E501
    }

    @staticmethod
    def _composed_schemas():
        return None

    required_properties = set(
        [
            "_data_store",
            "_check_type",
            "_from_server",
            "_path_to_item",
            "_configuration",
        ]
    )

    def __init__(
        self,
        _check_type=True,
        _from_server=False,
        _path_to_item=(),
        _configuration=None,
        **kwargs
    ):  # noqa: E501
        """btm_individual_query_base139.BTMIndividualQueryBase139 - a model defined in OpenAPI

        Keyword Args:
            _check_type (bool): if True, values for parameters in openapi_types
                                will be type checked and a TypeError will be
                                raised if the wrong type is input.
                                Defaults to True
            _path_to_item (tuple/list): This is a list of keys or values to
                                drill down to the model in received_data
                                when deserializing a response
            _from_server (bool): True if the data is from the server
                                False if the data is from the client (default)
            _configuration (Configuration): the instance to use when
                                deserializing a file_type parameter.
                                If passed, type conversion is attempted
                                If omitted no type conversion is done.
            bt_type (str): [optional]  # noqa: E501
            deterministic_id_list (BTMIndividualQueryBase139): [optional]  # noqa: E501
            deterministic_ids ([str]): [optional]  # noqa: E501
            import_microversion (str): [optional]  # noqa: E501
            node_id (str): [optional]  # noqa: E501
            query (BTMIndividualQueryBase139): [optional]  # noqa: E501
            query_string (str): [optional]  # noqa: E501
        """

        self._data_store = {}
        self._check_type = _check_type
        self._from_server = _from_server
        self._path_to_item = _path_to_item
        self._configuration = _configuration

        for var_name, var_value in six.iteritems(kwargs):
            if (
                var_name not in self.attribute_map
                and self._configuration is not None
                and self._configuration.discard_unknown_keys
                and self.additional_properties_type is None
            ):
                # discard variable.
                continue
            setattr(self, var_name, var_value)

    @classmethod
    def get_discriminator_class(cls, from_server, data):
        """Returns the child class specified by the discriminator"""
        discriminator = cls.discriminator()
        discr_propertyname_py = list(discriminator.keys())[0]
        discr_propertyname_js = cls.attribute_map[discr_propertyname_py]
        if from_server:
            class_name = data[discr_propertyname_js]
        else:
            class_name = data[discr_propertyname_py]
        class_name_to_discr_class = discriminator[discr_propertyname_py]
        return class_name_to_discr_class.get(class_name)


text:
package org.optaplanner.core.impl.heuristic.selector.common.decorator;

import java.util.Map;

import org.optaplanner.core.impl.heuristic.selector.Selector;
import org.optaplanner.core.impl.score.director.ScoreDirector;

public class FixedSelectorProbabilityWeightFactory<Solution_, Selector_ extends Selector>
        implements SelectionProbabilityWeightFactory<Solution_, Selector_> {

    private final Map<Selector_, Double> fixedProbabilityWeightMap;

    public FixedSelectorProbabilityWeightFactory(Map<Selector_, Double> fixedProbabilityWeightMap) {
        this.fixedProbabilityWeightMap = fixedProbabilityWeightMap;
    }

    @Override
    public double createProbabilityWeight(ScoreDirector<Solution_> scoreDirector, Selector_ selector) {
        return fixedProbabilityWeightMap.get(selector);
    }

}


text:
//=============================================================================
// Copyright © Jason Heddings, All Rights Reserved
// $Id: TimeOfDayFilterTest.cs 81 2013-11-06 04:44:58Z jheddings $
//=============================================================================
using System;
using Flynn.Core.Filters;
using NUnit.Framework;

namespace Flynn.Core.UnitTest.Filters {

    [TestFixture]
    public class TimeOfDayFilterTest {

        ///////////////////////////////////////////////////////////////////////
        [Test]
        public void DefaultValuesTest() {
            TimeOfDayFilter filter = new TimeOfDayFilter();

            for (int hour = 0; hour < 24; hour++) {
                for (int minute = 0; minute < 60; minute++) {
                    for (int second = 0; second < 60; second++) {
                        TimeSpan when = new TimeSpan(hour, minute, second);
                        Assert.IsTrue(filter.Accept(when));
                    }
                }
            }
        }

        ///////////////////////////////////////////////////////////////////////
        [Test]
        public void SimpleFilterTest() {
            TimeOfDayFilter filter = new TimeOfDayFilter();
            filter.Start = new TimeSpan(10, 0, 0);
            filter.Stop = new TimeSpan(18, 0, 0);

            TimeSpan noon = new TimeSpan(12, 0, 0);
            Assert.IsTrue(filter.Accept(noon));

            TimeSpan night = new TimeSpan(20, 0, 0);
            Assert.IsFalse(filter.Accept(night));
        }

        ///////////////////////////////////////////////////////////////////////
        [Test]
        public void WrapMidnightTest() {
            TimeOfDayFilter filter = new TimeOfDayFilter();
            filter.Start = new TimeSpan(22, 0, 0);
            filter.Stop = new TimeSpan(6, 0, 0);

            TimeSpan night = new TimeSpan(2, 0, 0);
            Assert.IsTrue(filter.Accept(night));

            TimeSpan noon = new TimeSpan(12, 0, 0);
            Assert.IsFalse(filter.Accept(noon));
        }
    }
}


text:
/**
 * Author: Claude Abounegm
 */
#include <Shadow.h>
#include <standard/Thread.h>
#include <stddef.h>
#include <stdlib.h>

// METHOD SIGNATURES //
//*HELPERS*
/**
 * The method that will be execute in the new spawned thread.
 * This is a wrapper which calls the actual thread start on the
 * Shadow side. It is here to allow the Thread.native.ll to set
 * the current Thread-Local-Storage thread to the newly spawned
 * thread.
**/
void* _shadow_standard__Thread_threadStart(shadow_Thread_t*);
// METHOD SIGNATURES //

shadow_Pointer_t* __shadow_standard__Thread_spawn(shadow_Thread_t* _this)
{
	return _shadow_natives__Pointer_create(malloc(1), SHADOW_CAN_FREE);
}


text:
This gem provides a command to list out your rspec tests.

## Installation

Add this line to your application's Gemfile in the test group:

    gem 'rspec_lister'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rspec_lister

## Usage

Run `rspec_lister` and you will be presented with a list of rspec
tests that your app has. For example:

    spec/lib/foo_spec.rb:3
    spec/lib/foo_spec.rb:6
    spec/lib/foo_spec.rb:9
    spec/lib/foo_spec.rb:12
    spec/lib/bar_spec.rb:10
    spec/lib/bar_spec.rb:12
    etc...

This list can then be fed to other programs that can operate on it.
Since I think it has value in itself, making a gem for it.

If `rspec_lister` is run with arguments, only list specs in that spec directory.
For example, `rspec_lister spec/models` will only list specs that live under
`spec/models`.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
help() {
    echo "setup.sh -- setup ivim"
    echo "Usage: setup.sh -i|-m|-u|-n"
    echo "-i -- install ivim"
    echo "-m -- install ivim_mini for vim"
    echo "-u -- install ivim_mini for neovim"
    echo "-n -- update ivim"
    exit 0
}

color_print() {
    printf '\033[0;31m%s\033[0m\n' "$1"
}

warn() {
    color_print "$1" >&2
}

die() {
    warn "$1"
    exit 1
}

logo() {
    color_print "Thank you for installing ivim!"
    color_print '    _       _         '
    color_print '   (_)   __(_)___ ___ '
    color_print '  / / | / / / __ `__ \'
    color_print ' / /| |/ / / / / / / /'
    color_print '/_/ |___/_/_/ /_/ /_/ '
    color_print '                      '
}

require() {
    color_print "Checking requirements for ivim..."
    if [ $1 = 0 ]; then
        color_print "Checking Vim version..."
        vim --version | grep -E 7.[3-9]\|8.[0-9] || die "Your vim's version is too low!\nPlease download higher version(7.3+) from http://www.vim.org/download.php"
    elif [ $1 = 1 ]; then
        color_print "Checking Vim version..."
        vim --version | grep -E 8.[0-9] || die "Your vim's version is too low!\nPlease download higher version(8.0+) from http://www.vim.org/download.php"
    else
        color_print "Checking NeoVim version..."
        nvim --version || die "Please install NeoVim according to https://github.com/neovim/neovim/wiki/Installing-Neovim"
    fi
    color_print "Checking if git exists..."
    which git || die "No git installed!\nPlease install git from http://git-scm.com/downloads/"
    color_print "Check if ctags exists..."
    which ctags || warn "No ctags installed!\nPlease install ctags form http://ctags.sourceforge.net/ after ivim intallation!"
}

install() {
    color_print "Cloning ivim..."
    rm -rf $HOME/.ivim
    git clone https://github.com/houzy/ivim.git $HOME/.ivim
    if [ $1 = 0 ]; then
        ln -s $HOME/.ivim/vimrc $HOME/.vimrc
    elif [ $1 = 1 ]; then
        ln -s $HOME/.ivim/vimrc_mini $HOME/.vimrc
    else
        mkdir -p $HOME/.config/nvim
        ln -s $HOME/.ivim/vimrc_mini $HOME/.config/nvim/init.vim
    fi
    color_print "Installing vim-plug..."
    if [ $1 = 2 ]; then
        curl -fLo ~/.config/nvim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
    else
        curl -fLo ~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
    fi
    color_print "Installing colortheme..."
    if [ $1 = 0 ]; then
        git clone https://github.com/kristijanhusak/vim-hybrid-material.git $HOME/.vim/bundle/vim-hybrid-material
    elif [ $1 = 1 ]; then
        git clone https://github.com/arcticicestudio/nord-vim.git $HOME/.vim/plugged/nord-vim
    else
        git clone https://github.com/arcticicestudio/nord-vim.git $HOME/.config/nvim/plugged/nord-vim
    fi
    color_print "Installing plugins using vim-plug..."
    if [ $1 = 2 ]; then
        nvim +PlugUpdate +qal
    else
        vim +PlugUpdate +qal
    fi
    color_print "ivim has been installed. Just enjoy vimming!"
}

update() {
    color_print "updating ivim..."
    git pull origin master
    color_print "updating plugins..."
    if [ -e $HOME/.config/nvim/init.vim ]; then
        nvim +PlugUpdate +qal
    fi
    if [ -e $HOME/.vimrc ]; then
        vim +PlugUpdate +qal
    fi
}

if [ $# -ne 1 ]; then
    help
fi

while getopts ":imun" opts; do
    case $opts in
        i)
            logo
            require 0
            install 0
            ;;
        m)
            logo
            require 1
            install 1
            ;;
        u)
            logo
            require 2
            install 2
            ;;
        n)
            update
            ;;
        :)
            help;;
        ?)
            help;;
    esac
done


text:
file_sufix=pp
format_style=Webkit
clang_version=3.6
formatter=clang-format-${clang_version}

check_clang_format() {
    if hash ${formatter} 2>/dev/null; then
        echo "INFO: Format all .*${file_sufix} to ${format_style} style"
    else
        echo "ERROR: Could not find ${formatter}. Please, check if is installed"
        exit 1
    fi
}

format_files() {
    for file in $(find -type f -name "*${file_sufix}"); do
        echo "INFO: Format file ${file}"
        ${formatter} -i -style=${format_style} $file
    done
}

main () {
    check_clang_format
    format_files
    exit 0
}

main


text:
This plugin exposes certian device settings for the RealSense SR300 camera TouchDesigner.

It is intended to run alongside Touch's native Realsense TOP and CHOP. Device settings set by this plugin carry over to the other Realsense instances.

#### Features
* Depth texture: 32bit float @variable fps
* Device controls:
   * Accuracy
   * Laser projector power
   * Filter options
   * Motion-range tradeoff

Documentation of the device parameters can be found [here](https://software.intel.com/sites/landingpage/realsense/camera-sdk/v1.1/documentation/html/index.html?member_functions_f200_and_sr300_device_pxccapture.html).

The depth texture values are in the range of 0 - 2047. At the moment you need to configure the TOP settings manually:
* 640 x 480
* 32bit float (Mono)

Tested with TouchDesigner 099, RealSense SDK 2016 R2, SR300 camera, and Windows 10.

#### Licensing
SenseTOP code is released under the [MIT License](https://github.com/kamindustries/SenseTOP/blob/master/LICENSE).


text:
<?php

namespace SionModel\Form\View\Helper;

use Zend\Form\ElementInterface;
use TwbBundle\Form\View\Helper\TwbBundleFormRow;

class SionFormRow extends TwbBundleFormRow
{
    /**
     * Render element's help block, especially for moderation-mode form rendering
     * This makes sure that JTranslate doesn't try translating the content
     * @param ElementInterface $oElement
     * @return string
     */
    protected function renderHelpBlock(ElementInterface $oElement)
    {
        $this->setTranslatorEnabled(false);
        $return = parent::renderHelpBlock($oElement);
        $this->setTranslatorEnabled(true);
        return $return;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns:pluginDescriptor xmlns:ns="urn:report.allurefw.org">
    <name>custom-logo-plugin</name>
</ns:pluginDescriptor>


text:
dojo.provide("Ozone.apis.tests.module");
//This file loads in all the test definitions.

try{
	//Load in the demoFunctions module test.
//	dojo.require("Ozone.eventing.tests.functions.demoFunctions");
	//Load in the widget tests.
//	dojo.require("Ozone.eventing.tests.widgets.DemoWidget");

    if(dojo.isBrowser){
        //Define the HTML file/module URL to import as a 'remote' test.
        doh.registerUrl("Ozone.apis.tests.AllApisTests",
                      dojo.moduleUrl("Ozone", "apis/tests/AllApisTests.html"));
    }
}catch(e){
	doh.debug(e);
}


text:
using Windows.UI.Xaml.Controls;
using Example.ThemifyIcons.UWP.ViewModel;

namespace Example.ThemifyIcons.UWP
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        public MainViewModel ViewModel => (MainViewModel) DataContext;

        private void FilterText_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            ViewModel.Filter(FilterText.Text);
        }

        private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0)
                return;

            ViewModel.CurrentIcon = (IconDescription)e.AddedItems[0];
        }
    }
}


text:
import {
  bootstrap,
  Inject,
  Component,
  View,
  Bindable,
  Runnable,
  RouterContent,
  decorate,
  i18nConfig
} from 'dali';

import {MenuBar} from 'menu-bar/MenuBar';
import {Module1} from 'module1/Module1';
import {Module2} from 'module2/Module2';
import {Module3} from 'module3/Module3';

@i18nConfig({
  locale: 'en-US',
  timezone: 'Europe/Madrid',
  currency: 'EUR',
  loader: 'data/locale-en-us.json'
  /*translations: {
    en_US : {
      app : {
        title: 'My first Dali app :)',
        total: 'Total: {{total, plural, =0 { You have no new messages } =1 { You have one new message } other { You have # new messages }}}',
        gender: '{{friendGender, gender, male { Invite him } female { Invite her } other { Invite them }}}'
      }
    }
  }*/
})
@Component({
  name: 'app'
})
@View({
  templateUrl: 'main_view.html'
})
@Runnable
@Inject(RouterContent, MenuBar)
class App {
  @Bindable
  title = "app.title";

  @Bindable
  date = new Date();

  @Bindable
  number = 100000;
}

bootstrap(App);


text:
<form role="form" class="ui-form">

            Name
            <input type="text"
                   ng-model="activeInstance.definition.name"
                   ng-blur="processModelNameValue()"
                   data-name="name"
                   id="ModelName"
                   name="ModelName"
                   placeholder="model name"
                   class="model-instance-name form-control ui-input"
                   ng-class="{ 'is-invalid': isJNameValid()}" />

          <button ng-click="saveModelInstance()"
                  ng-disabled="!isJNameValid()"
                  id="instance-save-button"
                  class="instance-detail-pocket-button instance-save-button"
                  data-modelId="{{ activeInstance.id }}" >Save Model</button>

                The name needs to conform with javascript conventions

  <button
          type="button"
          class="model-instance-header-btn btn-block"
          title="Details" >

Details

  </button>

          Plural

        <input type="text"
               ng-model="activeInstance.name"
               data-name="plural"
               id="ModelPlural"
               name="ModelPlural"
               class="ui-input" />

          Base model

        <input class="ui-input"
                type="text"
                data-name="base"
                ng-model="activeInstance.definition.base"
                ng-change="handleBaseBlur()" />

          Data source

        <select ng-model="activeInstance.config.dataSource"
                data-name="config.dataSource"
                name="dataSource"
                ng-options="dataSource.name as dataSource.name for dataSource in mainNavDatasources"
                class="model-instance-editor-input">
          <option value="">- none -</option>
        </select>

            <input
              type="checkbox"
              ng-model="activeInstance.config.public"
              data-name="config.public"
              name="public"
              ng-class="{ checked: activeInstance.config.public }">

            public

            <input
              type="checkbox"
              data-name="strict"
              name="strict"
              ng-model="activeInstance.definition.strict"
              ng-class="{ checked: activeInstance.definition.strict }">

            strict

</form>


text:
package roomNotice

// MonthConsume .
type MonthConsume struct {
	Uid    int64
	Ruid   int64
	Amount int64
	Date   int64
}

// TaskFinish .
type TaskFinish struct {
	Finish int64
}


text:
#ifndef AudioDestination_h
#define AudioDestination_h

#include "platform/PlatformExport.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/WTFString.h"

namespace WebCore {

class AudioIOCallback;

// AudioDestination is an abstraction for audio hardware I/O.
// The audio hardware periodically calls the AudioIOCallback render() method asking it to render/output the next render quantum of audio.
// It optionally will pass in local/live audio input when it calls render().

class PLATFORM_EXPORT AudioDestination {
public:
    // Pass in (numberOfInputChannels > 0) if live/local audio input is desired.
    // Port-specific device identification information for live/local input streams can be passed in the inputDeviceId.
    static PassOwnPtr<AudioDestination> create(AudioIOCallback&, const String& inputDeviceId, unsigned numberOfInputChannels, unsigned numberOfOutputChannels, float sampleRate);

    virtual ~AudioDestination() { }

    virtual void start() = 0;
    virtual void stop() = 0;
    virtual bool isPlaying() = 0;

    // Sample-rate conversion may happen in AudioDestination to the hardware sample-rate
    virtual float sampleRate() const = 0;
    static float hardwareSampleRate();

    // maxChannelCount() returns the total number of output channels of the audio hardware.
    // A value of 0 indicates that the number of channels cannot be configured and
    // that only stereo (2-channel) destinations can be created.
    // The numberOfOutputChannels parameter of AudioDestination::create() is allowed to
    // be a value: 1 <= numberOfOutputChannels <= maxChannelCount(),
    // or if maxChannelCount() equals 0, then numberOfOutputChannels must be 2.
    static unsigned long maxChannelCount();
};

} // namespace WebCore

#endif // AudioDestination_h


text:
package com.tutorial.sparksql

import com.tutorial.utils.SparkCommon

/**
  * Created by ved on 29/1/16.
  */
object CreatingDataFarmes {

  val sc = SparkCommon.sparkContext

  /**
    * Create a Scala Spark SQL Context.
    */
  val sqlContext = new org.apache.spark.sql.SQLContext(sc)

  def main(args: Array[String]) {
    /**
      * Create the DataFrame
      */
    val df = sqlContext.read.json("src/main/resources/cars.json")

    /**
      * Show the Data
      */
    df.show()

  }
}


text:
namespace net {

namespace {

// Takes the list of entries and an offset, and returns an index into the array.
// If |offset| is positive, just returns |offset|.  If it's negative, it
// indicates a position relative to the end of the array.
size_t GetIndex(const std::vector<NetLogEntry>& entries, int offset) {
  if (offset >= 0)
    return static_cast<size_t>(offset);

  size_t abs_offset = static_cast<size_t>(-offset);
  // If offset indicates a position before the start of the array, just return
  // the end of the list.
  if (abs_offset > entries.size())
    return entries.size();
  return entries.size() - abs_offset;
}

}  // namespace

::testing::AssertionResult LogContainsEvent(
    const std::vector<NetLogEntry>& entries,
    int offset,
    NetLogEventType expected_event,
    NetLogEventPhase expected_phase) {
  size_t index = GetIndex(entries, offset);
  if (index >= entries.size())
    return ::testing::AssertionFailure() << index << " is out of bounds.";
  const NetLogEntry& entry = entries[index];
  if (expected_event != entry.type) {
    return ::testing::AssertionFailure()
           << "Actual event: " << NetLogEventTypeToString(entry.type)
           << ". Expected event: " << NetLogEventTypeToString(expected_event)
           << ".";
  }
  if (expected_phase != entry.phase) {
    return ::testing::AssertionFailure()
           << "Actual phase: " << static_cast<int>(entry.phase)
           << ". Expected phase: " << static_cast<int>(expected_phase) << ".";
  }
  return ::testing::AssertionSuccess();
}

::testing::AssertionResult LogContainsBeginEvent(
    const std::vector<NetLogEntry>& entries,
    int offset,
    NetLogEventType expected_event) {
  return LogContainsEvent(entries, offset, expected_event,
                          NetLogEventPhase::BEGIN);
}

::testing::AssertionResult LogContainsEndEvent(
    const std::vector<NetLogEntry>& entries,
    int offset,
    NetLogEventType expected_event) {
  return LogContainsEvent(entries, offset, expected_event,
                          NetLogEventPhase::END);
}

::testing::AssertionResult LogContainsEntryWithType(
    const std::vector<NetLogEntry>& entries,
    int offset,
    NetLogEventType type) {
  size_t index = GetIndex(entries, offset);
  if (index >= entries.size())
    return ::testing::AssertionFailure() << index << " is out of bounds.";
  const NetLogEntry& entry = entries[index];
  if (entry.type != type)
    return ::testing::AssertionFailure() << "Type does not match.";
  return ::testing::AssertionSuccess();
}

::testing::AssertionResult LogContainsEntryWithTypeAfter(
    const std::vector<NetLogEntry>& entries,
    int start_offset,
    NetLogEventType type) {
  for (size_t i = GetIndex(entries, start_offset); i < entries.size(); ++i) {
    const NetLogEntry& entry = entries[i];
    if (entry.type == type)
      return ::testing::AssertionSuccess();
  }
  return ::testing::AssertionFailure();
}

size_t ExpectLogContainsSomewhere(const std::vector<NetLogEntry>& entries,
                                  size_t min_offset,
                                  NetLogEventType expected_event,
                                  NetLogEventPhase expected_phase) {
  size_t min_index = GetIndex(entries, min_offset);
  size_t i = 0;
  for (; i < entries.size(); ++i) {
    const NetLogEntry& entry = entries[i];
    if (entry.type == expected_event && entry.phase == expected_phase)
      break;
  }
  EXPECT_LT(i, entries.size());
  EXPECT_GE(i, min_index);
  return i;
}

size_t ExpectLogContainsSomewhereAfter(const std::vector<NetLogEntry>& entries,
                                       size_t start_offset,
                                       NetLogEventType expected_event,
                                       NetLogEventPhase expected_phase) {
  size_t i = GetIndex(entries, start_offset);
  for (; i < entries.size(); ++i) {
    const NetLogEntry& entry = entries[i];
    if (entry.type == expected_event && entry.phase == expected_phase)
      break;
  }
  EXPECT_LT(i, entries.size());
  return i;
}

absl::optional<std::string> GetOptionalStringValueFromParams(
    const NetLogEntry& entry,
    base::StringPiece path) {
  if (!entry.params.is_dict())
    return absl::nullopt;

  const std::string* result = entry.params.FindStringPath(path);
  if (!result)
    return absl::nullopt;

  return *result;
}

absl::optional<bool> GetOptionalBooleanValueFromParams(const NetLogEntry& entry,
                                                       base::StringPiece path) {
  if (!entry.params.is_dict())
    return absl::nullopt;
  return entry.params.FindBoolPath(path);
}

absl::optional<int> GetOptionalIntegerValueFromParams(const NetLogEntry& entry,
                                                      base::StringPiece path) {
  if (!entry.params.is_dict())
    return absl::nullopt;
  return entry.params.FindIntPath(path);
}

absl::optional<int> GetOptionalNetErrorCodeFromParams(
    const NetLogEntry& entry) {
  return GetOptionalIntegerValueFromParams(entry, "net_error");
}

std::string GetStringValueFromParams(const NetLogEntry& entry,
                                     base::StringPiece path) {
  auto result = GetOptionalStringValueFromParams(entry, path);
  if (!result) {
    ADD_FAILURE() << "No string parameter " << path;
    return "";
  }
  return *result;
}

int GetIntegerValueFromParams(const NetLogEntry& entry,
                              base::StringPiece path) {
  auto result = GetOptionalIntegerValueFromParams(entry, path);
  if (!result) {
    ADD_FAILURE() << "No int parameter " << path;
    return -1;
  }
  return *result;
}

bool GetBooleanValueFromParams(const NetLogEntry& entry,
                               base::StringPiece path) {
  auto result = GetOptionalBooleanValueFromParams(entry, path);
  if (!result) {
    ADD_FAILURE() << "No bool parameter " << path;
    return -1;
  }
  return *result;
}

int GetNetErrorCodeFromParams(const NetLogEntry& entry) {
  auto result = GetOptionalNetErrorCodeFromParams(entry);
  if (!result) {
    ADD_FAILURE() << "No net_error parameter";
    return -1;
  }
  return *result;
}

}  // namespace net


text:
package ca.ualberta.cs.scandaloutraveltracker.views;

import org.osmdroid.api.IMapController;
import org.osmdroid.bonuspack.overlays.MapEventsOverlay;
import org.osmdroid.bonuspack.overlays.MapEventsReceiver;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;

import ca.ualberta.cs.scandaloutraveltracker.R;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 	Allows the user to pick a spot on a map to be able to save it as the new expense location.
 * 	If a location is passed to this activity as two intents, one latitude and one longitude, then
 * 	it is displayed as the previous location
 * @author Team3ScandalouStopwatch
 *
 */
public class SetExpenseLocationActivity extends MenuActivity {
	private LocationManager lm;
	private MapView map;
	private TextView locationTV;
	private IMapController mapController;
	private MapEventsReceiver mapReceiver;
	private Marker newLocation;
	private Marker currentLocation = null;
	private Button currentButton;
	private Location previousLocation;

	/**
	 * 	Called when the activity is created. Sets up the map and adds a marker if a location
	 * 	was passed as intents to the activity. A listener is also made for long clicks on
	 * 	spots on the map that sets a marker and the spot long clicked on as the new location.
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_location);
        currentButton = (Button) findViewById(R.id.goCurrentButton);
        currentButton.setText("Prev");

		//https://github.com/osmdroid/osmdroid/wiki/How-to-use-the-osmdroid-library 2015-03-30
		map = (MapView) findViewById(R.id.map);
        map.setTileSource(TileSourceFactory.MAPNIK);
        map.setBuiltInZoomControls(true);
        map.setMultiTouchControls(true);
        mapController = map.getController();
        mapController.setZoom(9);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationTV = (TextView) findViewById(R.id.displayPickedLocationTextView);

        //sets start point to current expense location, gps location if available, else it will default to around Edmonton
        Intent intent = getIntent();
        previousLocation = new Location("Expense Location");
        previousLocation.setLatitude(intent.getDoubleExtra("latitude", 999));
        previousLocation.setLongitude(intent.getDoubleExtra("longitude", 999));
        GeoPoint startPoint;
        try {
        	if ((previousLocation.getLatitude() == 999)||(previousLocation.getLongitude() == 999)){
        		throw new NullPointerException();
        	}
    		startPoint = new GeoPoint(previousLocation);
    		currentLocation = new Marker(map);
        	currentLocation.setPosition(startPoint);
        	currentLocation.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
        	currentLocation.setTitle("Current Expense Location");
        	currentLocation.showInfoWindow();
			map.getOverlays().add(currentLocation);
			map.invalidate();
			locationTV.setText("Set Expense location\nLatitude: " +
					previousLocation.getLatitude() + "\nLongitude: "
						+ previousLocation.getLongitude());
			mapController.setCenter(startPoint);
    	}
	    catch (NullPointerException e) {
		    try {
		    	new GeoPoint(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER));
		    	startPoint = new GeoPoint(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER));
		    	mapController.setCenter(startPoint);
		    	}
		    catch (NullPointerException e2) {
		    	startPoint = new GeoPoint(53.533333, -113.5);
		    	mapController.setCenter(startPoint);
		    	}
    	}

        //http://stackoverflow.com/questions/16402722/longpress-on-osmdroid-map-is-not-working 2015-03-30
        mapReceiver = new MapEventsReceiver() {

        	// Does not need to do anything
			@Override
			public boolean singleTapConfirmedHelper(GeoPoint geo) {
				return false;
			}

			// Sets a marker to the current point and deletes old new expense location marker
			//https://code.google.com/p/osmbonuspack/wiki/Tutorial_0 2015-03-31
			@Override
			public boolean longPressHelper(GeoPoint geo) {
				locationTV.setText("Picked new expense location\nLatitude: " +
		        		geo.getLatitude() + "\nLongitude: " + geo.getLongitude());
				map.getOverlays().remove(newLocation);
				newLocation = new Marker(map);
				newLocation.setPosition(geo);
				newLocation.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
				newLocation.setTitle("New Expense Location");
				newLocation.showInfoWindow();
				map.getOverlays().add(newLocation);
				map.invalidate();
				return false;
			}
		};
		MapEventsOverlay OverlayEventos = new MapEventsOverlay(getBaseContext(), mapReceiver);
		map.getOverlays().add(OverlayEventos);
    }

    /**
     *  Called when prev button is clicked, the map goes to previous expense location if
     *  one was passed to the activity as an intent
     * @param v the current view
     */
    public void goCurrent(View v) {
    	if (currentLocation == null) {
    		Toast.makeText(getApplicationContext(),"Expense location not previously set",Toast.LENGTH_SHORT).show();
    		return;
    	}
    	GeoPoint startPoint = new GeoPoint(previousLocation);
        mapController.setCenter(startPoint);
    }

    /**
     *  Called when GPS is clicked, the map goes to current gps location
     * @param v the current view
     */
    public void goToGps(View v) {
        try {
        	new GeoPoint(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER));
    	}
    	catch (NullPointerException e) {
    		Toast.makeText(getApplicationContext(),"GPS currently not available",Toast.LENGTH_SHORT).show();
    		return;
    	}
        GeoPoint startPoint = new GeoPoint(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER));
        mapController.setCenter(startPoint);
    }

    /**
     *  Called when save new location is clicked. Saves the location that is set using the map by passing
     *  the new location back to the activity that called it as an intent
     * @param v the current view
     */
    public void saveLocation(View v) {
    	if (newLocation == null) {
    		Toast.makeText(getApplicationContext(),"Please pick a new location by long clicking a spot on the map."
    				,Toast.LENGTH_SHORT).show();
    		return;
    	}
    	Intent returnIntent = new Intent();
    	returnIntent.putExtra("latitude",newLocation.getPosition().getLatitude());
    	returnIntent.putExtra("longitude",newLocation.getPosition().getLongitude());
    	setResult(RESULT_OK,returnIntent);
    	finish();
    }
}


text:
package org.pikater.web.visualisation.definition;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.pikater.shared.util.Tuple;
import org.pikater.web.vaadin.gui.server.layouts.matrixlayout.IMatrixDataSource;
import org.pikater.web.visualisation.definition.result.AbstractDSVisSubresult;

/**
 * Holds all generated subresults/images and provides some basic (matrix-like)
 * interface for them. The matrix may not be complete (some positions may be
 * blank).
 *
 * @author SkyCrawl
 *
 * @param <I>
 *            The type to index subresults with.
 * @param <R>
 *            The subresult type.
 */
public class SubresultIndexer<I, R extends AbstractDSVisSubresult<I>>
		implements IMatrixDataSource<I, R>, Iterable<R> {
	private final Set<I> leftIndexSet;
	private final Set<I> topIndexSet;
	private final Map<Tuple<I, I>, R> indexesToSubresult;

	public SubresultIndexer() {
		this.leftIndexSet = new LinkedHashSet<I>(); // LinkedHashSet - hash,
													// don't use comparing and
													// keep the insertion order
		this.topIndexSet = new LinkedHashSet<I>(); // LinkedHashSet - hash,
													// don't use comparing and
													// keep the insertion order
		this.indexesToSubresult = new HashMap<Tuple<I, I>, R>();
	}

	@Override
	public Iterator<R> iterator() {
		return indexesToSubresult.values().iterator();
	}

	public boolean isSubresultRegistered(I leftIndex, I topIndex) {
		return this.indexesToSubresult.containsKey(new Tuple<I, I>(leftIndex,
				topIndex));
	}

	public void registerSubresult(I leftIndex, I topIndex, R subresult) {
		if (!isSubresultRegistered(leftIndex, topIndex)) {
			leftIndexSet.add(leftIndex);
			topIndexSet.add(topIndex);
			indexesToSubresult.put(new Tuple<I, I>(leftIndex, topIndex),
					subresult);
		} else {
			throw new IllegalArgumentException(
					String.format(
							"Result for '%s' (left) and '%s' (top) was already registered.",
							leftIndex.toString(), topIndex.toString()));
		}
	}

	@Override
	public Collection<I> getLeftIndexSet() {
		return leftIndexSet;
	}

	@Override
	public Collection<I> getTopIndexSet() {
		return topIndexSet;
	}

	@Override
	public R getElement(I leftIndex, I topIndex) {
		return indexesToSubresult.get(new Tuple<I, I>(leftIndex, topIndex));
	}
}