text:
<!DOCTYPE html>

    <title>Donne Martin</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

        <meta name="author" content="Donne Martin" />

        <meta property="og:site_name" content="Donne Martin" />
        <meta property="og:type" content="website"/>
        <meta property="og:title" content="Donne Martin"/>
        <meta property="og:url" content="."/>
        <meta property="og:description" content="Donne Martin"/>

        <link rel="stylesheet" href="./theme/css/bootstrap.min.css" type="text/css"/>

    <link href="./theme/css/pygments/monokai.css" rel="stylesheet">

    <link href="./theme/css/agency.css" rel="stylesheet">
    <link href="./theme/css/custom.css" rel="stylesheet">

    <link href="./theme/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Donne Martin

                        Likes

                        GitHub

                        About

                        Contact

                        Blog

                        Viz

                    A Brief Introduction to R Unit Testing with test_that

            <time datetime="2015-01-18T00:00:00-05:00"> Sun 18 January 2015</time>

Testing is a vital part of software development.  I've always been an advocate of Test Driven Development (TDD) and use nose for my python data analysis projects.  I've recently hooked up test_that to my R Snippets Repo.

Installing test_that

The easiest way to install and run test_that is by typing the following commands in the R console:

install.packages("devtools")
library(devtools)

To set up your package to use testthat, run:

devtools::use_testthat()

This creates a tests/testthat/ directory where tests live.  It also updates the DESCRIPTION file.

Tests are organised hierarchically:

Expectations are grouped into tests

Tests are organised in files

Running Tests

To execute tests, run:

devtools::test()

To skip a test, add the following within the test_that function body:

skip("reason for skipping")

Expectations

expect_true(x)  checks that an expression is true.

expect_false(x) checks that an expression is false.

expect_is(x, y) checks that an object inherit()s from a specified class

expect_equal(x, y)  check for equality with numerical tolerance

expect_equivalent(x, y) a more relaxed version of equals() that ignores attributes

expect_identical(x, y)  checks for exact equality

expect_matches(x, y)    matches a character vector against a regular expression.

expect_output(x, y) matches the printed output from an expression against a regular expression

expect_message(x, y)    checks that an expression shows a message

expect_warning(x, y)    expects that you get a warning

expect_error(x, y)  verifies that the expression throws an error.

Special Considerations

test_that does a good job ensuring that each test is run in its own environment and is self-contained.

The test_that documentation lists the following as exceptions:

The filesystem: creating and deleting files, changing the working directory, etc.

The search path: library(), attach().

Global options, like options() and par().

Code Snippets

The following abbreviated snippets of code test loading real world data sets from various sources to R.  The full source can be found in the R Snippets Repo.

Test whether a file was downloaded:

context("Reading Data")  # A context is a human readable file name
...
test_that("data is downloaded from URL", {
  fileDataUrl <- paste("https://d396qusza40orc.cloudfront.net/",
                       "getdata%2Fdata%2Fss06pid.csv",
                       sep="")
  fileDataDest <- "getdata-data-restaurants.xml"
  DownloadDataFromUrl(fileDataUrl,
                      fileDataDest)
  expect_true(file.exists(fileDataDest))
})

Test whether a computed result is the same as the baseline result:

...
test_that("data on number of baltimore restaurants by zip is read from xml", {
  zip <- 21217
  result <- NumBaltimoreRestaurants(zip)
  baseline <- 32
  expect_equal(result, baseline)
})

Test whether a computed result is the same as the baseline result, with a tolerance:

...
test_that("data on mean person weight replicate is read using sqldf", {
  result <- MeanProbabilityWeight()
  baseline <- 103.8886
  tolerance <- 10
  expect_equal(result, baseline, tolerance)
})

                    Copyright © Donne Martin 2014-Present

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package com.hsjawanda.gaeobjectify.json;

import static com.google.common.base.Preconditions.checkArgument;
import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.isNotBlank;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import com.hsjawanda.gaeobjectify.util.Constants;
import com.hsjawanda.gaeobjectify.util.GmapsPlaceType;

import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * Instances of this class are not threadsafe and therefore are not meant to be shared among
 * threads.
 *
 * @author Harshdeep S Jawanda (hsjawanda@gmail.com)
 *
 */
@Data
@Accessors(chain = true, fluent = true)
public class GmapsCall {

	@Setter(AccessLevel.NONE)
	private String location;

//	@Setter(AccessLevel.NONE)
	private String type;

	private Integer radius;

	private String name;

	private String keyword;

	private String placeId;

	private boolean rankByDistance = false;

	@Getter(AccessLevel.NONE)
	@Setter(AccessLevel.NONE)
	private Map<String, Object> params;

	public GmapsCall location(Double lat, Double lng) {
		checkArgument(Constants.latRange.contains(lat),
				"Latitude must be in the range " + Constants.latRange.toString());
		checkArgument(Constants.longRange.contains(lng),
				"Longitude must be in the range " + Constants.longRange.toString());
		this.location = String.format("%f,%f", lat.doubleValue(), lng.doubleValue());
		return this;
	}

	public GmapsCall type(GmapsPlaceType type) {
		if (null != type) {
			this.type = type.toString();
		} else {
			this.type = null;
		}
		return this;
	}

	public GmapsCall radius(int radius) {
		if (radius < 0) {
			radius = 500;
		}
		this.radius = radius;
		return this;
	}

	/**
	 * @return a read-only {@code Map} view.
	 */
	public Map<String, Object> asMap() {
		int reqdParams = null == this.name ? 0 : 1;
		reqdParams += null == this.keyword ? 0 : 1;
		reqdParams += null == this.type ? 0 : 1;
		if (this.rankByDistance && reqdParams == 0)
			throw new IllegalStateException("When rankByDistance is set, one or more of name, "
					+ "keyword and type must be specified as well");
		if (null == this.params) {
			this.params = new LinkedHashMap<>(6);
		}
		this.params.clear();
		if (null != this.location) {
			this.params.put("location", this.location);
		}
		if (null != this.radius && !this.rankByDistance) {
			this.params.put("radius", this.radius);
		}
		if (null != this.type) {
			this.params.put("type", this.type);
		}
		if (null != this.placeId) {
			this.params.put("placeid", this.placeId);
		}
		if (null != this.keyword) {
			this.params.put("keyword", this.keyword);
		}
		if (this.rankByDistance) {
			this.params.put("rankby", "distance");
		}
		if (isNotBlank(this.name)) {
			this.params.put("name", this.name);
		}
		return Collections.unmodifiableMap(this.params);
	}

}


text:
package boofcv.alg.filter.derivative.impl;

import boofcv.alg.misc.ImageMiscOps;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageSInt16;
import boofcv.struct.image.ImageUInt8;
import boofcv.testing.BoofTesting;
import org.junit.Test;

import java.util.Random;

/**
 * @author Peter Abeles
 */
public class TestGradientSobel_Outer {

	Random rand = new Random(234);

	int width = 200;
	int height = 250;

	/**
	 * See if the same results are returned by the simple naive algorithm
	 */
	@Test
	public void process_I8_naive() {

		for( int offY = 0; offY < 3; offY++ ) {
			for( int offX = 0; offX < 3; offX++ ) {
				int w = width+offX; int h = height+offY;
				ImageUInt8 img = new ImageUInt8(w, h);
				ImageMiscOps.fillUniform(img, new Random(0xfeed), 0, 100);

				ImageSInt16 derivX = new ImageSInt16(w, h);
				ImageSInt16 derivY = new ImageSInt16(w, h);

				ImageSInt16 derivX2 = new ImageSInt16(w, h);
				ImageSInt16 derivY2 = new ImageSInt16(w, h);

				GradientSobel_Naive.process(img, derivX2, derivY2);
				GradientSobel_Outer.process_I8(img, derivX, derivY);

				BoofTesting.assertEquals(derivX2, derivX, 0);
				BoofTesting.assertEquals(derivY2, derivY, 0);
			}
		}
	}

	@Test
	public void process_I8_sub_naive() {
		for( int offY = 0; offY < 3; offY++ ) {
			for( int offX = 0; offX < 3; offX++ ) {
				int w = width+offX; int h = height+offY;
				ImageUInt8 img = new ImageUInt8(w, h);
				ImageMiscOps.fillUniform(img, new Random(0xfeed), 0, 100);

				ImageSInt16 derivX = new ImageSInt16(w, h);
				ImageSInt16 derivY = new ImageSInt16(w, h);

				BoofTesting.checkSubImage(this, "process_I8_sub_naive", true, img, derivX, derivY);
			}
		}
	}

	public void process_I8_sub_naive(ImageUInt8 img, ImageSInt16 derivX, ImageSInt16 derivY) {
		ImageSInt16 derivX2 = new ImageSInt16(derivX.width, derivX.height);
		ImageSInt16 derivY2 = new ImageSInt16(derivX.width, derivX.height);

		GradientSobel_Naive.process(img, derivX2, derivY2);
		GradientSobel_Outer.process_I8_sub(img, derivX, derivY);

		BoofTesting.assertEquals(derivX2, derivX, 0);
		BoofTesting.assertEquals(derivY2, derivY, 0);
	}

	/**
	 * See if the same results are returned by ImageByte2D equivalent
	 */
	@Test
	public void process_F32_naive() {
		for( int offY = 0; offY < 3; offY++ ) {
			for( int offX = 0; offX < 3; offX++ ) {
				int w = width+offX; int h = height+offY;
				ImageFloat32 img = new ImageFloat32(w, h);
				ImageMiscOps.fillUniform(img, rand, 0f, 255f);

				ImageFloat32 derivX = new ImageFloat32(w, h);
				ImageFloat32 derivY = new ImageFloat32(w, h);

				ImageFloat32 derivX2 = new ImageFloat32(w, h);
				ImageFloat32 derivY2 = new ImageFloat32(w, h);

				GradientSobel_Naive.process(img, derivX2, derivY2);
				GradientSobel_Outer.process_F32(img, derivX, derivY);

				BoofTesting.assertEquals(derivX2, derivX, 1e-4f);
				BoofTesting.assertEquals(derivY2, derivY, 1e-4f);
			}
		}
	}
}


text:
class Synctv::Client::Resources::Media::View < Synctv::Client::Resource
  include Synctv::Client::Scopes

  self.prefix       = "/api/v2/media/"
end


text:
package org.apache.carbondata.processing.constants;

public final class DataProcessorConstants {
  /**
   *
   */
  public static final String CSV_DATALOADER = "CSV_DATALOADER";
  /**
   *
   */
  public static final String DATARESTRUCT = "DATARESTRUCT";
  /**
   * UPDATEMEMBER
   */
  public static final String UPDATEMEMBER = "UPDATEMEMBER";
  /**
   * number of days task should be in DB table
   */
  public static final String TASK_RETENTION_DAYS = "dataload.taskstatus.retention";
  /**
   * LOAD_FOLDER
   */
  public static final String LOAD_FOLDER = "Load_";
  /**
   * if bad record found
   */
  public static final long BAD_REC_FOUND = 223732673;
  /**
   * if bad record found
   */
  public static final long CSV_VALIDATION_ERRROR_CODE = 113732678;
  /**
   * Year Member val for data retention.
   */
  public static final String YEAR = "YEAR";

  private DataProcessorConstants() {

  }
}


text: console.log('filters loaded');


text:
Command line interface for accessing richard.

## Installation

Install it yourself as:

    $ gem install richard-cli

## Usage

    Usage:
      richard command [user_id]

    Commands:
      list - List current queue
      grab - Add yourself to the queue
      release - Removes you from the queue
      force_release - Force releases another user.  The user_id must be provided.
      is_it_my_turn - Returns 'Yes' or 'No'. It also returns status code 0 for 'Yes' and -1 for 'No'

## Contributing

1. Fork it ( https://github.com/[my-github-username]/richard-cli/fork )
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 a new Pull Request


text:
<?php

class Ebanx_Standard_Helper_Data extends Mage_Payment_Helper_Data
{
}


text:
package mapRed.inputAndOutput;

import static org.apache.hadoop.hbase.util.Bytes.toBytes;

import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class UniqueCounterTool extends Configured implements Tool {

	protected final static String INPUT_TABLE_NAME = "Exercise_InputAndOutput_Tokens";
	protected final static byte[] INPUT_FAMILY = toBytes("token");
	protected final static byte[] INPUT_COLUMN = toBytes("value");

	protected final static String OUTPUT_TABLE_NAME = "Exercise_InputAndOutput_Result";
	protected final static byte[] OUTPUT_FAMILY = toBytes("counts");
	protected final static byte[] OUTPUT_COLUMN = toBytes("count");

	@Override
	public int run(String[] args) throws Exception {
		Job job = Job.getInstance(getConf(), getClass().getSimpleName());
		job.setJarByClass(getClass());

		// TODO: Implement
		// HINT: utilize TableMapReduceUtil to set up mapper and reducer

		return job.waitForCompletion(true) ? 0 : 1;
	}

	public static void main(String[] args) throws Exception {
		int exitCode = ToolRunner.run(new UniqueCounterTool(), args);
		System.exit(exitCode);
	}
}


text:
//
//  FEPopupMenuItemCell.h
//  FEPopupMenuControllerDemo
//
//  Created by feeling on 16/1/29.
//  Copyright © 2016年 feeling. All rights reserved.
//

#import <UIKit/UIKit.h>

@class FEPopupMenuItem;

@interface FEPopupMenuItemCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIImageView *iconImageview;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleXCenterConstraint;

/**
 *  identifier for cell
 */
+ (NSString *)identifier;

/**
 *  nib
 */
+ (UINib *)nib;

/**
 *  fill the cell with item
 */
- (void)configCellWithItem:(FEPopupMenuItem *)item;

@end


text:
Transactions

    Filter
    <input type="text" ng-model = "tfilter" name="tfilter" class="form-control">

          Date

          Symbol

          Type

          Quantity

          Price

          Total


text:
package tehnut.lib;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class LendingLibrary {

    public static final Logger LOGGER = LogManager.getLogger();
}


text:
package ravtrix.backpackerbuddy;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;

import ravtrix.backpackerbuddy.helpers.Helpers;
import ravtrix.backpackerbuddy.helpers.HelpersPermission;
import ravtrix.backpackerbuddy.interfacescom.UserLocationInterface;

/**
 * Created by Ravinder on 9/13/16.
 */
public class UserLocation {

    private LocationManager locationManager;
    private LocationListener locationListener;
    private Activity context;
    private UserLocationInterface userLocationInterface;
    boolean gps_enabled = false;
    boolean network_enabled = false;
    private static final int LOCATION_REQUEST_CODE = 1;
    private boolean isFacebookSignUpCalling = false;
    private static int ONE_SECOND = 1000;

    public UserLocation(Activity context) {
        this.context = context;
    }

    /**
     * Start location service to collect latitude and longitude
     * @param userLocationInterface         Interface to detect when location is received
     */
    public void startLocationService(UserLocationInterface userLocationInterface) {
        this.userLocationInterface = userLocationInterface;

        if (context != null) {
            locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            setLocationListener();
            checkPermission();
        }
    }

    /**
     * Check if permission to use GPS is given, if not display option to enable
     */
    private void checkPermission() {

        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // Check for user's SDK Version. SDK version >= Marshmallow need permission access
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) !=
                            PackageManager.PERMISSION_GRANTED) {

                context.requestPermissions(new String[] {
                        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.INTERNET
                }, 0);
            } else {
                configureButton();
            }
        } else {
            configureButton();
        }
    }

    /**
     * Listener for location, listens for when location is changed
     */
    private void setLocationListener() {
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                final double longitude = location.getLongitude();
                final double latitude = location.getLatitude();
                stopListener();
                // Pass values over to sign up activity part 1
                userLocationInterface.onReceivedLocation(latitude, longitude);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
                // Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                //context.startActivity(intent);
            }
        };
    }

    /**
     * Cause location listener to start listening
     */
    public void configureButton() {
        try {

            if (!gps_enabled && !network_enabled && isFacebookSignUpCalling) {

                AlertDialog.Builder builder = Helpers.showAlertDialogWithTwoOptions(context, "Location Service", "Turn on location service so other users can see your current country", "No");
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        userLocationInterface.onReceivedLocation(0, 0); // permission denied, just use 0,0
                    }
                });
                builder.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // requesting permission to access location
                        HelpersPermission.showLocationRequest(context);
                    }
                });
                builder.show();

            } else {
                if (gps_enabled){
                    // One_Second passed because on location changed can be called multiple times in a few users
                    locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, null);
                    //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, UserLocation.ONE_SECOND, 1, locationListener);
                } else if (network_enabled) {
                    locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, locationListener, null);
                    //locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, UserLocation.ONE_SECOND, 1, locationListener);
                }
            }

        } catch (SecurityException e) {
            System.out.println(e.getMessage());
        }
    }

    private void stopListener() {
        try {
            // Turn off location listeners after successful location retrieval
            if (locationManager != null) {
                locationManager.removeUpdates(locationListener);
                locationManager = null;
                locationListener = null;
                context = null;
            }
        } catch (SecurityException e) {
            System.out.println(e.getMessage());
        }
    }

    public void setIsFacebookCalling(boolean isFacebookCalling) {
        this.isFacebookSignUpCalling = isFacebookCalling;
    }
}


text:
<?php
add_action( 'init', 'ninja_forms_register_email_admin' );
function ninja_forms_register_email_admin() {
	add_action( 'ninja_forms_post_process', 'ninja_forms_email_admin', 999 );
}

function ninja_forms_email_admin() {
	global $ninja_forms_processing;

	do_action( 'ninja_forms_email_admin' );

	$form_ID 			= $ninja_forms_processing->get_form_ID();
	$form_title 		= $ninja_forms_processing->get_form_setting( 'form_title' );
	$admin_mailto 		= $ninja_forms_processing->get_form_setting( 'admin_mailto' );
	$email_from_name 	= $ninja_forms_processing->get_form_setting( 'email_from_name' );
	$email_from 		= $ninja_forms_processing->get_form_setting( 'email_from' );
	$email_type 		= $ninja_forms_processing->get_form_setting( 'email_type' );
	$subject 			= $ninja_forms_processing->get_form_setting( 'admin_subject' );
	$message 			= $ninja_forms_processing->get_form_setting( 'admin_email_msg' );
	$email_reply 		= $ninja_forms_processing->get_form_setting( 'admin_email_replyto' );

	if ( $ninja_forms_processing->get_form_setting( 'admin_email_name' ) ){
		$email_from_name = $ninja_forms_processing->get_form_setting( 'admin_email_name' );
	}

	if ( $email_from_name AND $email_reply ) {
		$email_reply = $email_from_name . ' <' . $email_reply . '>';
	}

	if ( !$subject ){
		$subject = $form_title;
	}
	if ( !$message ){
		$message = '';
	}
	if ( !$email_type ){
		$email_type = '';
	}

	if ( $email_type !== 'plain' ){
		$message = apply_filters( 'ninja_forms_admin_email_message_wpautop', wpautop( $message ) );
	}

	$email_from = $email_from_name.' <'.$email_from.'>';

	$email_from = apply_filters( 'ninja_forms_admin_email_from', $email_from, $email_reply, $form_ID );

	$headers = array();
	$headers[] = 'From: ' . $email_from;
	if( $email_reply ) {
		$headers[] = 'Reply-To: ' . $email_reply;
	}
	$headers[] = 'Content-Type: text/' . $email_type;
	$headers[] = 'charset=utf-8';

	$attachments = false;
	if ($ninja_forms_processing->get_form_setting( 'admin_attachments' ) ) {
		$attachments = $ninja_forms_processing->get_form_setting( 'admin_attachments' );
	}

	if ( is_array( $admin_mailto ) AND !empty( $admin_mailto ) ){
		foreach( $admin_mailto as $to ) {
			if ( $attachments ) {
				wp_mail( $to, $subject, $message, $headers, $attachments );
			} else {
				wp_mail( $to, $subject, $message, $headers );
			}
		}
	}
}


text:
Given /"(.*)" is an anonymous user/ do |name|
  visit '/logout'
end

Given /^"(.*)" an unconfirmed user$/ do |name|
  When "I go to the registration form"
  And "I fill in \"login\" with \"#{name}\""
  And "I fill in \"email\" with \"#{name}@mail.com\""
  And "I fill in \"password\" with \"secret\""
  And "I fill in \"confirmation\" with \"secret\""
  When "I press \"Register\""
  Then "I should have a successful registration"
end

Given /^"(.*)" an unconfirmed user with password "(.*)"$/ do |name, password|
  When "I go to the registration form"
  And "I fill in \"login\" with \"#{name}\""
  And "I fill in \"email\" with \"#{name}@mail.com\""
  And "I fill in \"password\" with \"#{password}\""
  And "I fill in \"confirmation\" with \"#{password}\""
  When "I press \"Register\""
  Then "I should have a successful registration"
end

Given /^"(.*)" a confirmed user$/ do |name|
  Given "\"#{name}\" an unconfirmed user"
  And "I receive an email"
  And "I open the email"
  And "I should see \"confirm\" in the email"
  When "I follow \"confirm\" in the email"
  Then "I should see my account page"
  Then "a clear email queue"
  visit '/logout'
end

Given /^"(.*)" a confirmed user with password "(.*)"$/ do |name, password|
  Given "\"#{name}\" an unconfirmed user with password \"#{password}\""
  And "I receive an email"
  And "I open the email"
  And "I should see \"confirm\" in the email"
  When "I follow \"confirm\" in the email"
  Then "I should see my account page"
  visit '/logout'
end

Then /^I should see the registration form$/ do
  response.should contain('Login')
  response.should contain('Email')
  response.should contain('Password')
  response.should contain('Confirmation')
end

Then /^I should have a successful registration$/ do
  When 'I should see "Registration completed"'
end

Then /^I should have an unsuccessful registration$/ do
  When 'I should not see "Registration completed"'
end

Then /^I should be logged in$/ do
  When 'I should see "My Account"'
end

Then /^I should see my account page$/ do
  When 'I should see "My Account"'
end

Then /^I should not be logged in$/ do
  When 'I should not see "My Account"'
end

Then /^I should not see my account page$/ do
  When 'I should not see "My Account"'
end


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/address_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true">

        <Button
            android:id="@+id/go_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:text="@string/go_button"
            android:visibility="gone" />

        <EditText
            android:id="@+id/address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/go_button"
            android:hint="@string/address_hint"
            android:imeOptions="actionGo"
            android:inputType="textUri" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@color/white"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/go_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:clickable="true"
            android:contentDescription="@null"
            android:src="@drawable/toolbar_back_selector" />

        <ImageView
            android:id="@+id/forward"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:clickable="true"
            android:contentDescription="@null"
            android:src="@drawable/toolbar_forward_selector" />

        <ImageView
            android:id="@+id/refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:clickable="true"
            android:contentDescription="@null"
            android:src="@drawable/toolbar_refresh_selector" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/webview_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/toolbar"
        android:layout_below="@id/address_layout">

        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <ProgressBar
            android:id="@+id/progress_bar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:background="@drawable/progress_bar_layer_list"
            android:clickable="false"
            android:visibility="gone" />
    </FrameLayout>

</RelativeLayout>


text:
namespace gfx {
class GLContext;
class GLSurface;
}

namespace gpu {
class StreamTextureManager;

namespace gles2 {

class ContextGroup;
class QueryManager;

class MockGLES2Decoder : public GLES2Decoder {
 public:
  MockGLES2Decoder();
  virtual ~MockGLES2Decoder();

  MOCK_METHOD7(Initialize,
               bool(const scoped_refptr<gfx::GLSurface>& surface,
                    const scoped_refptr<gfx::GLContext>& context,
                    bool offscreen,
                    const gfx::Size& size,
                    const DisallowedFeatures& disallowed_features,
                    const char* allowed_extensions,
                    const std::vector<int32>& attribs));
  MOCK_METHOD1(Destroy, void(bool have_context));
  MOCK_METHOD1(SetSurface, void(const scoped_refptr<gfx::GLSurface>& surface));
  MOCK_METHOD2(SetParent, bool(GLES2Decoder* parent, uint32 parent_texture_id));
  MOCK_METHOD1(ResizeOffscreenFrameBuffer, bool(const gfx::Size& size));
  MOCK_METHOD0(MakeCurrent, bool());
  MOCK_METHOD0(ReleaseCurrent, void());
  MOCK_METHOD1(GetServiceIdForTesting, uint32(uint32 client_id));
  MOCK_METHOD0(GetGLES2Util, GLES2Util*());
  MOCK_METHOD0(GetGLSurface, gfx::GLSurface*());
  MOCK_METHOD0(GetGLContext, gfx::GLContext*());
  MOCK_METHOD0(GetContextGroup, ContextGroup*());
  MOCK_METHOD0(ProcessPendingQueries, bool());
  MOCK_METHOD0(GetQueryManager, gpu::gles2::QueryManager*());
  MOCK_METHOD0(GetVertexArrayManager, gpu::gles2::VertexArrayManager*());
  MOCK_METHOD1(SetResizeCallback, void(const base::Callback<void(gfx::Size)>&));
  MOCK_METHOD1(SetStreamTextureManager, void(StreamTextureManager*));
  MOCK_METHOD3(DoCommand, error::Error(unsigned int command,
                                       unsigned int arg_count,
                                       const void* cmd_data));
  MOCK_METHOD2(GetServiceTextureId, bool(uint32 client_texture_id,
                                         uint32* service_texture_id));
  MOCK_METHOD0(GetContextLostReason, error::ContextLostReason());
  MOCK_CONST_METHOD1(GetCommandName, const char*(unsigned int command_id));
  MOCK_METHOD9(ClearLevel, bool(
      unsigned service_id,
      unsigned bind_target,
      unsigned target,
      int level,
      unsigned format,
      unsigned type,
      int width,
      int height,
      bool is_texture_immutable));
  MOCK_METHOD0(GetGLError,  uint32());
  MOCK_METHOD1(SetMsgCallback, void(const MsgCallback& callback));
  MOCK_METHOD0(GetTextureUploadCount, uint32());
  MOCK_METHOD0(GetTotalTextureUploadTime, base::TimeDelta());
  MOCK_METHOD0(GetTotalProcessingCommandsTime, base::TimeDelta());
  MOCK_METHOD1(AddProcessingCommandsTime, void(base::TimeDelta));

  DISALLOW_COPY_AND_ASSIGN(MockGLES2Decoder);
};

}  // namespace gles2
}  // namespace gpu

#endif  // GPU_COMMAND_BUFFER_SERVICE_GLES2_CMD_DECODER_MOCK_H_


text:
This document aims to provide information about how to build Elektra's Website.

## Design and Structure

The website is developed as a single-page application (SPA) in [AngularJS (v1.5)](https://angularjs.org/).
All dependencies are either already contained in the application project or (preferred) resolved through
the dependency manager [npm](https://www.npmjs.com/) during installation (requires active internet connection).
Compiling (browserification, concatenation & minification), as well as other tasks like running a lightweight
webserver are handled by the nodeJS based task runner [grunt](http://gruntjs.com/) (installed by npm).

## Run and Configure

To install the website, make sure `website` is included in TOOLS. You can use [this guide](https://github.com/ElektraInitiative/libelektra/blob/master/doc/COMPILE.md) to add the required website tool.
`npm` is the only dependency.
Then use `make install` to install the website.
It will be installed in `@CMAKE_INSTALL_PREFIX@/share/elektra/tool_data/website/public`.
Default values for `CMAKE_INSTALL_PREFIX` can be found [here](https://cmake.org/cmake/help/latest/variable/CMAKE_INSTALL_PREFIX.html).

As next step, the website configuration needs to be copied and mounted:
`@CMAKE_INSTALL_PREFIX@/lib/elektra/tool_exec/mount-website-config`

The configuration will be mounted to `system:/sw/elektra/website/#0/current` in Elektra
(`@config_root@/@config_default_profile@`)
and contains some URLs for GitHub resources and translation,
as well as logger settings. Usually, no changes are required there, see
Configuration Options below for some useful options.

As next step, you can build the website:
`@CMAKE_INSTALL_PREFIX@/lib/elektra/tool_exec/build-website` (or `kdb build-@tool@`)

To run the application, basically two options are available:

- Use the built-in webserver of `grunt`, which can be configured in the
  [Gruntfile.js](Gruntfile.js) and run by `grunt server` (in the installation target directory `@CMAKE_INSTALL_PREFIX@/share/elektra/tool_data/website`)
  or `kdb run-@tool@` from anywhere.
  To stop the `@tool@`, run `kdb stop-@tool@`.
- Use an own webserver to distribute the application.
  In order to do so, only `grunt full` (or `kdb build-@tool@`, see above) needs to be run.
  After that, the content of the [public](public/) directory can be copied to any location
  that suits the needs. `npm` dependencies in the [node_modules](node_modules/) directory
  and the [resources](resources/) directory are only necessary for development,
  but can be ignored for deployment. The required dependencies were copied to the [public](public/)
  directory already.

In order to not receive any 404 errors by the webserver, it should serve the `index.html`
for all requests that do not have a static file as target.
The `index.html` will then try to serve the (dynamic) URL itself.

### Configuration Options

#### PID file

Using ${config_root}${config_default_profile}/daemon/lock (i.e., `daemon.lock` in JSON) you can specify which PID file should be used.
Default: /run/elektra-@tool@.pid

#### APIs (GitHub)

The configuration file allows to change GitHub settings in the `github` section.

#### Translations

The configuration file also allows to specify available translations in `translations.enabled`.
To add a translation, copy an existing translation file in
[public/assets/translations](public/assets/translations), translate it and add the name of
the new language to the list in `translations.enabled`.
After that run `grunt full` (or `kdb build-@tool@`) to re-compile the application.

If necessary, mappings for dialects as well as a default language can be specified as well.

#### Logger

It is possible to enable the frontend logger by changing `logger.enabled` in the configuration file.

### Directory Structure

The application project itself is mainly splitted into two directories: `resources` and `public`,
whereas only the latter can directly been accessed by clients if the built-in
`grunt server` is used to deploy the project.

The [resources](resources/) directory contains the JavaScript source files,
custom grunt tasks as well as the LESS files which are compiled into CSS files for the website.

The [public](public/) directory contains HTML template files, assets like fonts,
compiled JS and CSS files, as well as translation files and all dependencies resolved by `npm`,
which are copied by `grunt`. It does also contain copied documentation files for the website.

### Important facts

- Links are internal on the website if the target is part of it too,
  otherwise they are external (i.e. linked to repo on external site).
- The frontend supports Markdown syntax via a plugin ([marked](https://github.com/chjj/marked)).
- Styling can then be done easily through LESS/CSS.
- The website structure is dynamically adjustable.
  There is a set of types which can be used to define links, menus, content of sites, etc.
  A detailed discussion for the website structure happened in #1015.
- A full text search using Algolia is implemented https://issues.libelektra.org/2796

### Limitations

**AngularJS 2:**
At the time of development start, there was no stable AngularJS 2 release available yet,
only early previews. Because of that, the frontend was developed using AngularJS 1.5.
Later we tried an upgrade but failed of the extensive work which would be required.
Another idea would be to build a static webpage, so that at least the end user
is not confronted with the old version of AngularJS: https://issues.libelektra.org/3470

## Compiling and Installing

### Dependencies

The project has quite a few dependencies, of which most can be resolved automatically
by the used package manager.
The only dependency that has to be installed beforehand is the package manager
[npm](https://www.npmjs.com/) itself,
which comes bundled with [Node.js](https://nodejs.org/) (preferred installation).

### Compiling

The `@tool@` has full CMake integration, which does actually only two things:

- Install (copy) the project files to a target directory.
- Run `npm install` in this target directory, which does
- resolve all `npm` dependencies (into the directory [node_modules](node_modules/)).
- run `grunt full` to compile all application sources ([resources](resources/) dir)
  into working production files ([public](public/) dir) and
  copy required `npm` dependencies in the `public` folder.

### Installing

It is not necessary to install anything by hand, CMake does this job already.
If changes are made to the source files in [resources](resources/),
it is sufficient to run `grunt full` (or `kdb build-@tool@`) to build the application again.
During development, it can be handy to use `grunt watch` to run a watcher daemon that re-compiles
LESS or JS files whenever a change was made in the respective [resources](resources/) directory.

### resources/structure.json.in

This configuration file can be used to define the website structure.
The file consists at its root of an array, which will be transformed into the main menu of the website
(the dynamic part of the menu).
The array houses objects, of which every object represents an element on the website (e.g. a link).

In the following, the different element types will be explained in detail.
The headline always refers to the `type` field of the element.
The element type `link` for example would be an object like the following
with some extra attributes explained below:

```
{
    "type": "link",
    ... other attributes ...
}
```

It is possible to add additional attributes not used by the system without breaking anything.
For example use `dev-comment` to leave some development notes, e.g. decision information.

#### submenu

The `submenu` type can be used to create a menu point that has a (hoverable) submenu,
but does itself not link to any page. It can only be used in the top hierarchy of the structure file.

This field type supports following attributes:

- `name` (string) for the visible name of the menu point (i.e. button text)
- `ref` (string) for the dynamic URL part (i.e. a resource of the URL,
  e.g. `http://example.com/docs` for the subsequent example)
- `children` (array) holding other structure elements, but none of type `submenu`

Example:

```json
{
  "name": "Documentation",
  "type": "submenu",
  "ref": "docs",
  "children": []
}
```

#### parsereadme

The `parsereadme` element type is the most powerful of all types.
It takes a text file as input (often README.md) and creates with the help of some
regex patterns a section of the website which contains parsed links of the input file.

This field type support following attributes:

- `name` (string) for the visible name of the menu point (i.e. button text)
- `ref` (string) for the dynamic URL part (i.e. a resource of the URL,
  e.g. `http://example.com/plugins` for the subsequent example)
- `options` (object) with further options:
  - `path` (string) containing the path from the repository root to the text file to parse
  - `target_file` (array[string]) containing some filenames that should be
    targeted for parsed links that are no files (i.e. links to directories)
  - `parsing` (object) with further options:
    - `start_regex` (string, optional) defines the start point from where on
      the following regex types should be parsed
    - `entry_regex` (string) defines a regex that will create links to
      files within a website section
    - `section_regex` (string, optional) can additionally be used to
      parse group names which will make the section links look nicer
    - `stop_regex` (string, optional) defines the end point up to
      which the text file will be parsed
  - `name` (object) with further options:
    - `make_pretty` (boolean) whether the link names within the
      text file which will also be used on the website should be made pretty
      (e.g. first-capitalize, etc.);
      this option is discouraged for this structure element type

Example:

```json
{
  "name": "Plugins",
  "type": "parsereadme",
  "ref": "plugins",
  "options": {
    "path": "src/plugins/README.md",
    "target_file": ["README.md", "README", "readme.md", "readme"],
    "parsing": {
      "start_regex": "# Plugins",
      "stop_regex": "####### UNUSED",
      "section_regex": "### ([^#]+)",
      "entry_regex": "^\\- \\[(.+)\\]\\(([^\\)]+)\\)(.*)"
    },
    "name": {
      "make_pretty": false
    }
  }
}
```

#### listdirs

The `listdirs` element type can be used to enumerate all sub-directories of a specific directory.
It will try to find one of the target files (i.e. readme) within the sub-directories and
create a link to them. All this is done in a newly created website section.

This field type supports following attributes:

- `name` (string) for the visible name of the menu point (i.e. button text)
- `ref` (string) for the dynamic URL part (i.e. a resource of the URL,
  e.g. `http://example.com/tools` for the subsequent example)
- `options` (object) with further options:
  - `path` (string) containing the path from the repository root to the directory to enumerate
  - `target_file` (array[string]) containing some filenames that should be targeted within the sub-directories
    (e.g. find file `README.md` in directory `mydir` to use it as information file for the directory)

Example:

```json
{
  "name": "Tools",
  "type": "listdirs",
  "ref": "tools",
  "options": {
    "path": "src/tools",
    "target_file": ["README.md", "README", "readme.md", "readme"]
  }
}
```

#### listfiles

The `listfiles` element type is quite similar to the `listdirs` type,
but instead of sub-directories it enumerates files within a directory.
It does also create a new website section.

This field type supports following attributes:

- `name` (string) for the visible name of the menu point (i.e. button text)
- `ref` (string) for the dynamic URL part (i.e. a resource of the URL,
  e.g. `http://example.com/manpages` for the subsequent example)
- `options` (object) with further options:
  - `path` (string) containing the path from the repository root to the directory to enumerate
  - `blacklist` (array[string]) containing some filenames that should
    be excluded from the result (e.g. CMakeLists.txt)

Example:

```json
{
  "name": "Manpages",
  "type": "listfiles",
  "ref": "manpages",
  "options": {
    "path": "doc/help",
    "blacklist": ["CMakeLists.txt"]
  }
}
```

#### staticlist

The `staticlist` element type creates a new website section that is
entirely customizable within the structure configuration file.
This type can be used instead of the `parsereadme` type if a mix of many types is required.

This field type supports following attributes:

- `name` (string) for the visible name of the menu point (i.e. button text)
- `ref` (string) for the dynamic URL part (i.e. a resource of the URL,
  e.g. `http://example.com/getstarted` for the subsequent example)
- `children` (array) holding static structure elements like `staticref`, `staticfile` and `link`

Example:

```json
{
  "name": "Getting started",
  "type": "staticlist",
  "ref": "getstarted",
  "children": []
}
```

#### staticref

The `staticref` element type can be used in a `staticlist` to create a reference to another website part.

This field type support following attributes:

- `name` (string) for the visible name of the menu point (i.e. button text)
- `options` (object) with further options:
  - `path` (string) containing a reference, which can either be the `ref`
    attribute of another element or an even more specific reference

Example:

```json
{
  "name": "Tutorials",
  "type": "staticref",
  "options": {
    "path": "tutorials"
  }
}
```

#### staticfile

The `staticfile` element type can be used in a `staticlist` to create a menu point for a file.
The file is then a page in the section created by the `staticlist`.

This field type support following attributes:

- `name` (string) for the visible name of the menu point (i.e. button text)
- `options` (object) with further options:
  - `path` (string) containing the path to a file

Example:

```json
{
  "name": "Installation",
  "type": "staticfile",
  "options": {
    "path": "doc/INSTALL.md"
  }
}
```

#### link

The `link` element type can be used to create a simple link to whatever is desired.
It is recommended to use it only for external links.

This field type support following attributes:

- `name` (string) for the visible name of the menu point (i.e. button text)
- `ref` (string) for the dynamic URL part (_currently unused_)
- `options` (object) with further options:
  - `path` (string) containing the path of the link

Example:

```json
{
  "name": "Build Server",
  "type": "link",
  "ref": "buildserver",
  "options": {
    "path": "https://build.libelektra.org/"
  }
}
```

#### parsefolders

The `parsefolders` element type looks at list of folders and creates table of contents (TOC) file for the contents.
For every folder a section is appended to the TOC file.
The section will contain a list linking to all the files in the folder.

This field type support following attributes:

- `name` (string) for the visible name of the menu point (i.e. button text)
- `ref` (string) for the dynamic URL part (_currently unused_)
- `options` (object) with further options:
  - `path` (string) containing the path of the base folder
  - `base_toc` (string) filename of the base file for generating the TOC
  - `folders` (array of objects) list of folder to traverse
    - `path` (string) path of folder relative to base folder
    - `title` (string) title for the section of this folder
    - `title_level` (number) level of the title (adds this number of `#` before the title to create a Markdown title)

Example:

```json
{
  "name": "Decisions",
  "type": "parsefolders",
  "ref": "decisions",
  "options": {
    "path": "doc/decisions",
    "base_toc": "README.md",
    "folders": [
      {
        "path": "0_drafts",
        "title": "Drafts",
        "title_level": 2
      }
    ]
  }
}
```

## Development

When attempting to change the AngularJS application, it can be useful to first
have a look at all used dependencies, which are listed in
[resources/assets/js/application.js](resources/assets/js/application.js).
After that, the configuration files in
[resources/assets/js/config](resources/assets/js/config) should be checked.
Probably the most important configuration is the router in
[resources/assets/js/config/routes.config.js](resources/assets/js/config/routes.config.js).

### Life Cycle

An AngularJS application is bootstrapped by first instantiating constants (can be used for configuration).
After that, service providers are run, which allows for further configuration of services.
When the bootstrap process is finished and all services are instantiated based
on the settings made within the service providers, the router will load
the default route (main page) and bind the appropriate controller to it.
Controllers are destroyed as soon as a page is changed, but services are not.
So caching across pages can be done using services.
AngularJS also allows for dependency injection in basically every part of the
application (services, controllers, etc) by type-hinting the dependency name.

For detailed information, the website of [Angular](https://angularjs.org/) should be visited.

### Task Configuration

All `grunt` tasks can be configured using the [Gruntfile.js](Gruntfile.js) in the application root directory.

### Code Formatting

The task `grunt jshint` can be used to check the code formatting of JS source files.

### Noteworthy Information

#### HTML in i18n Keys

It is possible to use HTML in translation files (loca keys) if the place where
the loca key is used adds the directive `translate-compile`. The loca key itself
does also need to be placed in the `translate` directive instead of a dynamic
Angular binding (i.e. use `<span translate="LOCA_KEY"></span>` in favor of
`<span>{{ 'LOCA_KEY' | translate }}</span>`).

#### Links

For external links, the normal HTML `a`-tag has to be used (`<a href="..."></a>`).
If the external link has the same base URL as the frontend (e.g. frontend is at
`http://localhost/` and the link points to `http://localhost/news/feed.rss`),
the html tag `target` has to be added to the link with the desired value, e.g.
`_self` to open the link in the same window/tab or `_blank` to use a new one.
An example would be `<a href="http://localhost/news/feed.rss" target="_self">...</a>`.

For internal links (that are links that lead to another sub-page of the website)
two options are available. It is possible to use the normal `href` HTML attribute
or to use the special `ui-sref` attribute defined by the frontend router.
The `ui-sref` directive works on state names and not on links,
so if a sub-page like `<website-url>/docs/tutorials` exists, one cannot use
`<a ui-sref="/docs/tutorials">...</a>`; the state name for the tutorials page has to
be used, which is most likely `main.dyn.tutorials` if the tutorials section is based
on the `structure.json.in`. The link (with a simple loca key) would look like
`<a ui-sref="main.dyn.tutorials">...</a>` therefore.
The `ui-sref` variant requires the HTML to be specially compiled though, what makes
the usage of a normal `href` attribute easier in most scenarios.
The following link does exactly the same as the last example with `ui-sref`:
`<a href="/docs/tutorials">...</a>`.
An advantage of `ui-sref` over `href` is that it does also work with hidden parameters,
i.e. state parameters not visible in the URL. Such parameters are rarely used in
practice, though, as they are not SEO friendly at all.


text:
package fr.javatronic.damapping.processor.model;

import javax.annotation.Nonnull;

/**
 * DAImport - Represents an import statement in a Java source file.
 *
 * @author Sébastien Lesaint
 */
public interface DAImport extends DAElement {
  /**
   * The qualified name of the imported type, ie. a {@link DAName} object which name is {@code com.foo.Bar} for
   * {@code import com.foo.Bar}.
   *
   * @return a {@link DAName}
   */
  @Nonnull
  DAName getQualifiedName();

  /**
   * The package of the import type ie. {@code com.foo} in {@code import com.foo.Bar}.
   * <p>
   * Since it is illegal to import a Type from the unamed package, this method can not return an {@code null}.
   * </p>
   *
   * @return a {@link DAName}
   */
  @Nonnull
  DAName getPackageName();

  /**
   * The simple name of the imported type, ie. {@code Bar} in {@code import com.foo.Bar}.
   *
   * @return a {@link DAName}
   */
  @Nonnull
  DAName getSimpleName();
}


text:
<?php

namespace TubeLink\Tests\Service;

use TubeLink\Service\Youtube;
use TubeLink\Tube;

class YoutubeTest extends ServiceTestCase
{
    public function dataForTestParse()
    {
        return array(
            array('http://www.youtube.com/watch?v=gHYfY9lZaRE&feature=g-vrec', 'gHYfY9lZaRE'),
            array('http://youtube.com/watch?v=gHYfY9lZaRE&feature=g-vrec', 'gHYfY9lZaRE'),
            array('http://www.youtube.fr/watch?v=gHYfY9lZaRE', 'gHYfY9lZaRE'),
            array('http://www.youtube.com/watch?gl=FR&hl=fr&v=gHYfY9lZaRE#share', 'gHYfY9lZaRE'),
            array('http://www.youtube.com/all_comments?v=gHYfY9lZaRE', 'gHYfY9lZaRE'),
            array('http://youtu.be/gHYfY9lZaRE', 'gHYfY9lZaRE'),
            array('http://www.youtu.be/gHYfY9lZaRE', 'gHYfY9lZaRE'),
            array('http://www.youtu.be/gHYfY9lZaRE/?feature=g-vrec', 'gHYfY9lZaRE'),
            array('http://www.youtube.com/embed/gHYfY9lZaRE', 'gHYfY9lZaRE'),
            array('http://www.youtube.com/embed/P-8llsSbVDc?rel=0', 'P-8llsSbVDc'),
            array('http://www.youtube-nocookie.com/embed/P-8llsSbVDc?rel=0', 'P-8llsSbVDc'),
            array('http://www.youtube.com/v/uPgLxYUHRcg?fs=1&hl=fr_FR', 'uPgLxYUHRcg'),
            array('http://www.youtube-nocookie.com/v/Kw_yO2utN0c?fs=1&hl=fr_FR', 'Kw_yO2utN0c'),
            array('http://www.youtube.com/p/18DCC2CD9CCCCB91?hl=fr_FR&fs=1', '18DCC2CD9CCCCB91'),
        );
    }

    public function dataForTestParseFalse()
    {
        return array(
            array('http://www.youtube.com/watch?v=HYfY9lZaRE'), // Invalid ID
            array('http://www.youtu.be/HYfY9lZaRE'), // Invalid ID
        );
    }

    public function dataForTestGenerateEmbedUrl()
    {
        return array(
            array('gHYfY9lZaRE', 'http://www.youtube.com/embed/gHYfY9lZaRE'),
        );
    }

    public function dataForTestThumbnailUrl()
    {
        return array(
            array('fZ_JOBCLF-I', 'http://img.youtube.com/vi/fZ_JOBCLF-I/hqdefault.jpg', 'hqdefault'),
            array('fZ_JOBCLF-I', 'http://img.youtube.com/vi/fZ_JOBCLF-I/0.jpg', '0'),
        );
    }

    public function dataForTestThumbnailUrlFalse()
    {
        return array(
            array('fZ_JOBCLF-I', ''),
        );
    }

    protected function getService($options = array())
    {
        return new Youtube($options);
    }

    /**
     * @dataProvider dataForTestThumbnailUrl
     */
    public function testGetThumbnailUrl($id, $thumbnailUrl, $thumbnailSize = 'hqdefault')
    {
        $service = $this->getService(array('thumbnail' => $thumbnailSize));
        $video = new Tube($service);
        $video->id = $id;

        $this->assertEquals($thumbnailUrl, $video->thumbnail());
    }
}


text:
using System.Collections.Generic;

namespace nHydrate.ModelManagement
{
    public class DiskModel
    {
        public List<nHydrate.ModelManagement.Entity.configuration> Entities { get; internal set; } = new List<Entity.configuration>();
        public List<nHydrate.ModelManagement.Index.configuration> Indexes { get; internal set; } = new List<Index.configuration>();
        public List<nHydrate.ModelManagement.Relation.configuration> Relations { get; internal set; } = new List<Relation.configuration>();
        public List<nHydrate.ModelManagement.StaticData.configuration> StaticData { get; internal set; } = new List<StaticData.configuration>();
        public List<nHydrate.ModelManagement.View.configuration> Views { get; internal set; } = new List<View.configuration>();
        public ModelProperties ModelProperties { get; set; } = new ModelProperties();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest" xmlns:m2="http://schemas.microsoft.com/appx/2013/manifest" xmlns:build="http://schemas.microsoft.com/developer/appx/2012/build" IgnorableNamespaces="build">
  <!--
    THIS PACKAGE MANIFEST FILE IS GENERATED BY THE BUILD PROCESS.

    Changes to this file will be lost when it is regenerated. To correct errors in this file, edit the source .appxmanifest file.

    For more information on package manifest files, see http://go.microsoft.com/fwlink/?LinkID=241727
  -->
  <Identity Name="9826ece7-0f3c-4533-b2de-9e5b7e5e79e7" Version="1.0.0.1" Publisher="CN=Arcadio" ProcessorArchitecture="neutral" />
  <Properties>
    <DisplayName>PelucheMSP</DisplayName>
    <PublisherDisplayName>Arcadio</PublisherDisplayName>
    <Logo>images\storelogo.png</Logo>
  </Properties>
  <Prerequisites>
    <OSMinVersion>6.3.0</OSMinVersion>
    <OSMaxVersionTested>6.3.0</OSMaxVersionTested>
  </Prerequisites>
  <Resources>
    <Resource Language="EN-US" />
  </Resources>
  <Applications>
    <Application Id="App" StartPage="default.html">
      <m2:VisualElements DisplayName="PelucheMSP" Description="PelucheMSP" ForegroundText="light" BackgroundColor="#464646" Square150x150Logo="images\Logo.png" Square30x30Logo="images\SmallLogo.png">
        <m2:SplashScreen Image="images\splashscreen.png" />
      </m2:VisualElements>
    </Application>
  </Applications>
  <Capabilities>
    <Capability Name="internetClient" />
  </Capabilities>
  <Dependencies>
    <PackageDependency Name="Microsoft.WinJS.2.0" MinVersion="1.0.9600.17018" />
  </Dependencies>
  <build:Metadata>
    <build:Item Name="VisualStudio" Version="14.0" />
    <build:Item Name="VisualStudioEdition" Value="Microsoft Visual Studio Ultimate 2015 Preview" />
    <build:Item Name="OperatingSystem" Version="10.0.9926.0 (fbl_awesome1501.150119-1648)" />
    <build:Item Name="Microsoft.Build.AppxPackage.dll" Version="14.0.22310.1" />
    <build:Item Name="ProjectGUID" Value="9826ece7-0f3c-4533-b2de-9e5b7e5e79e7" />
    <build:Item Name="MakePri.exe" Version="6.3.9600.17298 (winblue.141024-1500)" />
  </build:Metadata>
</Package>


text:
class Verona(Place):
  self.occupants = []

class SceneOne(Scene):
  def Play(self):
    self.location = Verona()

    sampson = Person(name="Sampson", house="Capulet", armed=True)
    gregory = Person(name="Gregory", house="Capulet", armed=True)

    self.location.occupants.append([sampson, gregory])


text:
package tools.devnull.boteco;

/**
 * An interface to define a service for registering in the OSGi Registry
 */
public interface ServiceDefinition<T> {

  /**
   * Defines a service property
   *
   * @param key   the name of the property
   * @param value the value of the property
   * @return an instance of the service definition
   */
  ServiceDefinition<T> withProperty(String key, Object value);

  /**
   * Defines the service id as a service property
   *
   * @param value the id of the service
   * @return an instance of the service definition
   */
  ServiceDefinition<T> withId(Object value);

  /**
   * Defines the service class that the given object will be registered
   *
   * @param serviceClass the service class to register the given service
   */
  void as(Class<? super T> serviceClass);

}


text:
#ifndef CommonCryptoSPI_h
#define CommonCryptoSPI_h

#if OS(DARWIN)

#if USE(APPLE_INTERNAL_SDK)
#include <CommonCrypto/CommonRandomSPI.h>
#endif

typedef struct __CCRandom* CCRandomRef;

WTF_EXTERN_C_BEGIN

extern const CCRandomRef kCCRandomDefault;
int CCRandomCopyBytes(CCRandomRef rnd, void *bytes, size_t count);

WTF_EXTERN_C_END

#endif // OS(DARWIN)

#endif /* CommonCryptoSPI_h */


text:
var exp = {}
// --------------------------------------------------------------------------------------
const config = require('../config/config');
const deasync = require('deasync');
// --------------------------------------------------------------------------------------
// get basic user info
// return object with all important properties
// --------------------------------------------------------------------------------------
exp.get_user = function(req)
{
  var user = {};

  user.username = req.headers["remote_user"];
  user.identities = get_eduroam_identities(req.headers);
  user.groups = [];
  for(var group in config.role_groups) {
    var temp = parse_groups(req, user.username, req.headers[config.role_groups[group]]);

    for(role in temp)
      user.groups.push(temp[role]);
  }
  user.role = user.groups[user.groups.length - 1];      // default role is the highest available
  set_realms(req, user);
  set_display_role(user);

  return user;
}
// --------------------------------------------------------------------------------------
// returns list of users permission
// --------------------------------------------------------------------------------------
function parse_groups(req, username, group_list)
{
  var ret = [ "user" ];         // everyone is at least a user
  var done = false;
  var list = group_list.split(";");

  // search for realm admins locally in the database
  req.db.realm_admin_logins.find({ "admin_login_ids" : username }, function(err1, items) {
    if(err1) {
      var err2 = new Error();      // just to detect where the original error happened
      console.error(err2);
      console.error(err1);
      next([err2, err1]);
      return;
    }

    if(items.length > 0)    // username has realm admin privilege
      ret.push("realm_admin");
    done = true;
  });

  deasync.loopWhile(function() {
    return !done;
  });

  // admins
  for(var group in config.admin_groups) {
    for(var item in list) {
      if(list[item] == config.admin_groups[group]) {
        if(ret.indexOf("realm_admin") == -1)
          ret.push("realm_admin", "admin");   // global admin is also a realm admin

        else
          ret.push("admin");   // realm admin included from previous loop

        break;
      }
    }
  }

  return ret;
}
// --------------------------------------------------------------------------------------
// get eduroam identity
// may be different from username and one user may have more identities
// --------------------------------------------------------------------------------------
function get_eduroam_identities(headers)
{
  var ret = [];

  if(headers["eduroamuid"] != "(null)") {    // special eduroam identity attribute
    var identities = headers["eduroamuid"].split(';');
    for(var id in identities) {
      ret.push(identities[id]);
    }
  }
  else   // "hack" using remote_user/eppn for users, which do not supply eduroamuid attribute
    ret.push(headers["remote_user"]);

  return ret;
}
// --------------------------------------------------------------------------------------
// set array of administered realms if the user is realm admin
// --------------------------------------------------------------------------------------
function set_realms(req, user)
{
  if(user.role != "realm_admin")
    return;     // applies only for realm admin

  user.administered_realms = get_administered_realms(req, user.username);
  user.notify_address = get_notify_address(req, user.username);
}
// --------------------------------------------------------------------------------------
// get array of administered realms for given username
// --------------------------------------------------------------------------------------
function get_administered_realms(req, username)
{
  var done = false;
  var ret = [];

  req.db.realm_admin_logins.find({ "admin_login_ids" : username }, { _id : 0, administered_realms : 1 }, function(err1, items) {
    if(err1) {
      var err2 = new Error();      // just to detect where the original error happened
      console.error(err2);
      console.error(err1);
      next([err2, err1]);
      return;
    }

    if(items.length > 0)    // array of administered realms
      ret = items[0].administered_realms;
    else                    // "hack" using remote_user/eppn for now
      ret.push(username.replace(/.*@/, ""));

    done = true;
  });

  deasync.loopWhile(function() {
    return !done;
  });

  return ret;
}
// --------------------------------------------------------------------------------------
// get notify address for given username
// --------------------------------------------------------------------------------------
function get_notify_address(req, username)
{
  var done = false;
  var ret;

  req.db.realm_admin_logins.find({ "admin_login_ids" : username }, { _id : 0, admin_notify_address : 1 }, function(err1, items) {
    if(err1) {
      var err2 = new Error();      // just to detect where the original error happened
      console.error(err2);
      console.error(err1);
      next([err2, err1]);
      return;
    }

    if(items.length > 0)
      ret = items[0].admin_notify_address;
    done = true;
  });

  deasync.loopWhile(function() {
    return !done;
  });

  return ret;
}
// --------------------------------------------------------------------------------------
// set display role
// --------------------------------------------------------------------------------------
function set_display_role(user)
{
  user.display_role = user.role;

  if(user.display_role == "user")
    user.display_role = "uživatel";     // only to display correct language variant in frontend

  if(user.display_role == "realm_admin")
    user.display_role = "realm admin";     // no undescore
}
// --------------------------------------------------------------------------------------
// set user role
// --------------------------------------------------------------------------------------
exp.set_user_role = function(req)
{
  var user = exp.get_user(req);

  switch(req.params.role) {
    case "user":
      user.role = "user";       // anyone with higher privs can be a user
      break;

    case "realm_admin":
      if(user.groups.length > 1)
        user.role = "realm_admin";       // only realm_admin or admin can become realm_admin
      break;

    case "admin":
      if(user.groups.length > 2)
        user.role = "admin";       // only admin can become admin
      break;
  }

  set_realms(req, user);
  set_display_role(user);

  return user;
}
// --------------------------------------------------------------------------------------
// set items per page for user
// --------------------------------------------------------------------------------------
exp.set_paging = function(req)
{
  var user = exp.get_user(req);
  user.items_by_page = parseInt(req.params.paging, 10);
  return user;
}
// --------------------------------------------------------------------------------------
module.exports = exp;


text:
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/gorilla/mux"
	"github.com/lovoo/goka"
	"github.com/lovoo/goka/codec"
)

var (
	brokers             = []string{"127.0.0.1:9092"}
	topic   goka.Stream = "user-click"
	group   goka.Group  = "mini-group"

	tmc *goka.TopicManagerConfig
)

// A user is the object that is stored in the processor's group table
type user struct {
	// number of clicks the user has performed.
	Clicks int
}

// This codec allows marshalling (encode) and unmarshalling (decode) the user to and from the
// group table.
type userCodec struct{}

func init() {
	tmc = goka.NewTopicManagerConfig()
	tmc.Table.Replication = 1
	tmc.Stream.Replication = 1
}

// Encodes a user into []byte
func (jc *userCodec) Encode(value interface{}) ([]byte, error) {
	if _, isUser := value.(*user); !isUser {
		return nil, fmt.Errorf("Codec requires value *user, got %T", value)
	}
	return json.Marshal(value)
}

// Decodes a user from []byte to it's go representation.
func (jc *userCodec) Decode(data []byte) (interface{}, error) {
	var (
		c   user
		err error
	)
	err = json.Unmarshal(data, &c)
	if err != nil {
		return nil, fmt.Errorf("Error unmarshaling user: %v", err)
	}
	return &c, nil
}

func runEmitter() {
	emitter, err := goka.NewEmitter(brokers, topic,
		new(codec.String))
	if err != nil {
		panic(err)
	}
	defer emitter.Finish()

	t := time.NewTicker(100 * time.Millisecond)
	defer t.Stop()

	var i int
	for range t.C {
		key := fmt.Sprintf("user-%d", i%10)
		value := fmt.Sprintf("%s", time.Now())
		emitter.EmitSync(key, value)
		i++
	}
}

func process(ctx goka.Context, msg interface{}) {
	var u *user
	if val := ctx.Value(); val != nil {
		u = val.(*user)
	} else {
		u = new(user)
	}

	u.Clicks++
	ctx.SetValue(u)
	fmt.Printf("[proc] key: %s clicks: %d, msg: %v\n", ctx.Key(), u.Clicks, msg)
}

func runProcessor(initialized chan struct{}) {
	g := goka.DefineGroup(group,
		goka.Input(topic, new(codec.String), process),
		goka.Persist(new(userCodec)),
	)
	p, err := goka.NewProcessor(brokers,
		g,
		goka.WithTopicManagerBuilder(goka.TopicManagerBuilderWithTopicManagerConfig(tmc)),
		goka.WithConsumerGroupBuilder(goka.DefaultConsumerGroupBuilder),
	)
	if err != nil {
		panic(err)
	}

	close(initialized)

	p.Run(context.Background())
}

func runView(initialized chan struct{}) {
	<-initialized

	view, err := goka.NewView(brokers,
		goka.GroupTable(group),
		new(userCodec),
	)
	if err != nil {
		panic(err)
	}

	root := mux.NewRouter()
	root.HandleFunc("/{key}", func(w http.ResponseWriter, r *http.Request) {
		value, _ := view.Get(mux.Vars(r)["key"])
		data, _ := json.Marshal(value)
		w.Write(data)
	})
	fmt.Println("View opened at http://localhost:9095/")
	go http.ListenAndServe(":9095", root)

	view.Run(context.Background())
}

func main() {
	tm, err := goka.NewTopicManager(brokers, goka.DefaultConfig(), tmc)
	if err != nil {
		log.Fatalf("Error creating topic manager: %v", err)
	}
	defer tm.Close()
	err = tm.EnsureStreamExists(string(topic), 8)
	if err != nil {
		log.Printf("Error creating kafka topic %s: %v", topic, err)
	}

	// When this example is run the first time, wait for creation of all internal topics (this is done
	// by goka.NewProcessor)
	initialized := make(chan struct{})

	go runEmitter()
	go runProcessor(initialized)
	runView(initialized)
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('LL1_Academy', '0009_auto_20170518_0803'),
    ]

    operations = [
        migrations.AlterField(
            model_name='userhistory',
            name='score',
            field=models.IntegerField(default=-1),
        ),
    ]


text:
package net.sf.jasperreports.charts.fill;

import java.awt.Color;

import net.sf.jasperreports.charts.JRAreaPlot;
import net.sf.jasperreports.engine.JRExpression;
import net.sf.jasperreports.engine.JRFont;
import net.sf.jasperreports.engine.fill.JRFillChartPlot;
import net.sf.jasperreports.engine.fill.JRFillObjectFactory;
import net.sf.jasperreports.engine.util.JRStyleResolver;

/**
 * @author Flavius Sana (flavius_sana@users.sourceforge.net)
 * @version $Id: JRFillAreaPlot.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class JRFillAreaPlot extends JRFillChartPlot implements JRAreaPlot
{

	/**
	 *
	 */
	protected JRFont categoryAxisLabelFont;
	protected Color categoryAxisLabelColor;
	protected JRFont categoryAxisTickLabelFont;
	protected Color categoryAxisTickLabelColor;
	protected Color categoryAxisLineColor;

	protected JRFont valueAxisLabelFont;
	protected Color valueAxisLabelColor;
	protected JRFont valueAxisTickLabelFont;
	protected Color valueAxisTickLabelColor;
	protected Color valueAxisLineColor;

	/**
	 *
	 */
	public JRFillAreaPlot( JRAreaPlot areaPlot, JRFillObjectFactory factory )
	{
		super( areaPlot, factory );

		//FIXME should the font use the fill chart?
		categoryAxisLabelFont = factory.getFont(areaPlot.getChart(), areaPlot.getCategoryAxisLabelFont());
		categoryAxisLabelColor = areaPlot.getOwnCategoryAxisLabelColor();
		categoryAxisTickLabelFont = factory.getFont(areaPlot.getChart(), areaPlot.getCategoryAxisTickLabelFont());
		categoryAxisTickLabelColor = areaPlot.getOwnCategoryAxisTickLabelColor();
		categoryAxisLineColor = areaPlot.getOwnCategoryAxisLineColor();

		valueAxisLabelFont = factory.getFont(areaPlot.getChart(), areaPlot.getValueAxisLabelFont());
		valueAxisLabelColor = areaPlot.getOwnValueAxisLabelColor();
		valueAxisTickLabelFont = factory.getFont(areaPlot.getChart(), areaPlot.getValueAxisTickLabelFont());
		valueAxisTickLabelColor = areaPlot.getOwnValueAxisTickLabelColor();
		valueAxisLineColor = areaPlot.getOwnValueAxisLineColor();
	}

	/**
	 *
	 */
	public JRExpression getCategoryAxisLabelExpression()
	{
		return ((JRAreaPlot)parent).getCategoryAxisLabelExpression();
	}

	/**
	 *
	 */
	public JRFont getCategoryAxisLabelFont()
	{
		return categoryAxisLabelFont;
	}

	/**
	 *
	 */
	public Color getCategoryAxisLabelColor()
	{
		return JRStyleResolver.getCategoryAxisLabelColor(this, this);
	}

	/**
	 *
	 */
	public Color getOwnCategoryAxisLabelColor()
	{
		return categoryAxisLabelColor;
	}

	/**
	 *
	 */
	public void setCategoryAxisLabelColor(Color color)
	{
	}

	/**
	 *
	 */
	public JRFont getCategoryAxisTickLabelFont()
	{
		return categoryAxisTickLabelFont;
	}

	/**
	 *
	 */
	public Color getCategoryAxisTickLabelColor()
	{
		return JRStyleResolver.getCategoryAxisTickLabelColor(this, this);
	}

	/**
	 *
	 */
	public Color getOwnCategoryAxisTickLabelColor()
	{
		return categoryAxisTickLabelColor;
	}

	/**
	 *
	 */
	public void setCategoryAxisTickLabelColor(Color color)
	{
	}

	/**
	 *
	 */
	public String getCategoryAxisTickLabelMask()
	{
		return ((JRAreaPlot)parent).getCategoryAxisTickLabelMask();
	}

	/**
	 *
	 */
	public Boolean getCategoryAxisVerticalTickLabels()
	{
		return ((JRAreaPlot)parent).getCategoryAxisVerticalTickLabels();
	}

	/**
	 *
	 */
	public Double getCategoryAxisTickLabelRotation()
	{
		return ((JRAreaPlot)parent).getCategoryAxisTickLabelRotation();
	}

	/**
	 *
	 */
	public void setCategoryAxisTickLabelRotation(Double labelRotation)
	{
	}

	/**
	 *
	 */
	public Color getCategoryAxisLineColor()
	{
		return JRStyleResolver.getCategoryAxisLineColor(this, this);
	}

	/**
	 *
	 */
	public Color getOwnCategoryAxisLineColor()
	{
		return categoryAxisLineColor;
	}

	/**
	 *
	 */
	public void setCategoryAxisLineColor(Color color)
	{
	}

	/**
	 *
	 */
	public JRExpression getValueAxisLabelExpression()
	{
		return ((JRAreaPlot)parent).getValueAxisLabelExpression();
	}

	/**
	 *
	 */
	public JRExpression getDomainAxisMinValueExpression()
	{
		return ((JRAreaPlot)parent).getDomainAxisMinValueExpression();
	}

	/**
	 *
	 */
	public JRExpression getDomainAxisMaxValueExpression()
	{
		return ((JRAreaPlot)parent).getDomainAxisMaxValueExpression();
	}

	/**
	 *
	 */
	public JRExpression getRangeAxisMinValueExpression()
	{
		return ((JRAreaPlot)parent).getRangeAxisMinValueExpression();
	}

	/**
	 *
	 */
	public JRExpression getRangeAxisMaxValueExpression()
	{
		return ((JRAreaPlot)parent).getRangeAxisMaxValueExpression();
	}

	/**
	 *
	 */
	public JRFont getValueAxisLabelFont()
	{
		return valueAxisLabelFont;
	}

	/**
	 *
	 */
	public Color getValueAxisLabelColor()
	{
		return JRStyleResolver.getValueAxisLabelColor(this, this);
	}

	/**
	 *
	 */
	public Color getOwnValueAxisLabelColor()
	{
		return valueAxisLabelColor;
	}

	/**
	 *
	 */
	public void setValueAxisLabelColor(Color color)
	{
	}

	/**
	 *
	 */
	public JRFont getValueAxisTickLabelFont()
	{
		return valueAxisTickLabelFont;
	}

	/**
	 *
	 */
	public Color getValueAxisTickLabelColor()
	{
		return JRStyleResolver.getValueAxisTickLabelColor(this, this);
	}

	/**
	 *
	 */
	public Color getOwnValueAxisTickLabelColor()
	{
		return valueAxisTickLabelColor;
	}

	/**
	 *
	 */
	public void setValueAxisTickLabelColor(Color color)
	{
	}

	/**
	 *
	 */
	public String getValueAxisTickLabelMask()
	{
		return ((JRAreaPlot)parent).getValueAxisTickLabelMask();
	}

	/**
	 *
	 */
	public Boolean getValueAxisVerticalTickLabels()
	{
		return ((JRAreaPlot)parent).getValueAxisVerticalTickLabels();
	}

	/**
	 *
	 */
	public Color getValueAxisLineColor()
	{
		return JRStyleResolver.getValueAxisLineColor(this, this);
	}

	/**
	 *
	 */
	public Color getOwnValueAxisLineColor()
	{
		return valueAxisLineColor;
	}

	/**
	 *
	 */
	public void setValueAxisLineColor(Color color)
	{
	}
}


text:
Rails.application.routes.draw do
  match '/test_error' => "errors#test"
end


text:
#include "AggregationResult.h"

namespace griddb {

	AggregationResult::AggregationResult(GSAggregationResult* aggResult) : Resource(aggResult), mAggResult(aggResult) {
	}

	AggregationResult::~AggregationResult() {
		close();
	}

	/**
	 *Obtains the result of aggregating numeric-type values in LONG type (Long).
	 */
	long AggregationResult::get_long() {
		long value;

		GSBool ret = gsGetAggregationValue(mAggResult, &value, GS_TYPE_LONG);
		if(ret == GS_FALSE) {
			throw GSException("Value with type long cannot be retrieved from Aggregation result");
		}

		return value;
	}

	/**
	 *Obtains the result of aggregating numeric-type values in DOUBLE type (Double).
	 */
	double AggregationResult::get_double() {
		double value;

		GSBool ret = gsGetAggregationValue(mAggResult, &value, GS_TYPE_DOUBLE);
		if(ret == GS_FALSE) {
			throw GSException("Value with type double cannot be retrieved from Aggregation result");
		}

		return value;
	}

	/**
	 *Obtains the result of aggregating numeric-type values in GSTIMESTAMP type (GSTimestamp).
	 */
	GSTimestamp AggregationResult::get_timestamp() {
		GSTimestamp value;

		GSBool ret = gsGetAggregationValue(mAggResult, &value, GS_TYPE_TIMESTAMP);
		if(ret == GS_FALSE) {
			throw GSException("Value with type Timestamp cannot be retrieved from Aggregation result");
		}

		return value;
	}

	void AggregationResult::close() {
		if(mAggResult != NULL) {
			gsCloseAggregationResult(&mAggResult);
		}
		mAggResult = NULL;
	}

} /* namespace griddb */


text:
function isOddOrEven(string) {
     if (typeof (string) !== 'string') {
          return undefined;
     }

     if (string.length % 2 === 0) {
          return "even";
     }

     return "odd";
}

module.exports = isOddOrEven;


text:
layout: post
title: "Flex Data Services for AJAX"
category: "Blog"
---
{% include JB/setup %}

I this link on Ben Forta's blog about a new project called [Ajax Data Services](http://labs.adobe.com/wiki/index.php/Ajax_Data_Services ) on Adobe Labs.

This Library lets you embed an invisible SWF file in your web page, and then use Flex Data Services to push data to your HTML content. It is extremely difficult to push to AJAX clients without a technology like this for developers.


text:
set -e

usage(){
    echo gzip the provided .sql file, and
    echo then upload it to the MMW S3 bucket.
    echo
    echo Appends a timestamp to file name before uploading.
    echo
    echo ARGS:
    echo -e "\t [-p MMW_STG_AWS_PROFILE]: Optional, the name of your mmw-stg profile."
    echo -e "\t\t If not provided, will default to AWS_PROFILE environment"
    echo -e "\t\t variable."
    echo -e "\t PATH_TO_FILE: Path to the file to upload"
    echo -e "\t [DST_FILE_NAME]: Optional, if the uploaded file"
    echo -e "\t\t needs a different name than input file"
    echo
    echo "Usage: upload_sql_data.sh [-p MMW_STG_AWS_PROFILE] PATH_TO_FILE [DST_FILE_NAME]"
    exit 1
}

if [[ $# -eq 0 ]] ; then
    usage
fi

# Load optional flagged arguments
while getopts ":p:" opt; do
    case $opt in
        p)
            AWS_PROFILE="$OPTARG" ;;
        \?)
            usage
esac
done
shift $(( OPTIND-1 ))

# Require AWS_PROFILE to be set
if [ -z ${AWS_PROFILE+x} ]; then
    echo AWS_PROFILE environment variable must be set to your mmw-stg profile
    echo or the mmw-stg profile must be passed in as option -p
    exit;
fi

FILE_PATH=$1
# Require FILE_PATH to be a .sql file
if [[ -z $FILE_PATH || $FILE_PATH != *\.sql ]]; then
    echo You must provide a .sql file
    echo
    usage
fi

echo gzipping...
gzip $FILE_PATH
GZIPPED_FILE_PATH=$FILE_PATH.gz

echo checking integrity of gzip
GZIP_FAILURE=$(gzip -t $GZIPPED_FILE_PATH)
case "$GZIP_FAILURE" in
    *[!$whitespace]*)
        echo gzip failed: $GZIP_FAILURE
        exit 1
esac

# Get base file name
# eg if FILE_PATH is ./somewhere/nhdflowline.sql
# FILE_PATH will be nhdflowline
FILE_NAME=$(echo $FILE_PATH | \
            sed 's/.*\///' | \
            sed 's/\.sql.*//')

DST_NAME=${2-$FILE_NAME}
DESIRED_FILE_NAME=${DST_NAME}_$(date +%s).sql.gz

echo Creating MD5 checksum
CHECKSUM=$(openssl md5 -binary $GZIPPED_FILE_PATH | base64)

echo Uploading $DESIRED_FILE_NAME to s3
aws s3 cp --profile ${AWS_PROFILE} \
       $GZIPPED_FILE_PATH \
       s3://data.mmw.azavea.com/$DESIRED_FILE_NAME \
       --acl public-read \
       --metadata md5=$CHECKSUM


text:
import { has } from "./index";
export = has;


text:
using Augustus.CRM.Queries;
using Augustus.Domain.Objects;
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using Augustus.CRM;
using Augustus.Domain.Interfaces;
using Augustus.Web.Portal.ViewModels;

namespace Augustus.Web.Portal.Controllers
{
    public class AccountController : BaseWriteController<AccountWriteViewModel, Account>
    {
        private const string bindAttributes = "Name";

        protected override IQuery<Account> GetQuery(CrmContext context)
        {
            return new AccountQuery(context);
        }

        protected override void RefreshCreateViewModel(CrmContext context, Guid? parentId, ref AccountWriteViewModel model)
        {
            model.Title = "Create Account";
            model.Breadcrumb = new Breadcrumb();
            model.FormButtons = new FormButtons(GetParentUrl(parentId));
            model.AccountDropDown = new DropDownViewModel<Account>
            {
                SelectedId = model.Account.ParentAccountId,
                Items = new OrganizationQuery(context).GetNewAccounts(),
                AllowNull = true,
                RemoveSelfId = model.Account.Id
            };
        }

        protected override void RefreshEditViewModel(CrmContext context, Guid id, ref AccountWriteViewModel model)
        {
            model.Title = "Edit Account";
            model.FormButtons = new FormButtons(id, GetDefaultUrl(id));
            model.Breadcrumb = new Breadcrumb { Account = new AccountQuery(context).GetItem(id) };
            model.AccountDropDown = new DropDownViewModel<Account>
            {
                SelectedId = model.Account.ParentAccountId,
                Items = new OrganizationQuery(context).GetNewAccounts(),
                AllowNull = true,
                RemoveSelfId = model.Account.Id
            };
        }

        protected override string GetParentUrl(Guid? parentId)
        {
            return Url.Action("ActiveAccounts", "Organization");
        }

        protected override string GetDefaultUrl(Guid id)
        {
            return Url.Action("Invoices", new { Id = id });
        }

        //GET: /Account/Invoices/{id}
        public async Task<ActionResult> Invoices(Guid id)
        {
            Response.AppendHeader("guid", id.ToString());

            using (var context = await GetCrmContext())
            {
                var query = new AccountQuery(context);

                var model = query.GetItem(id);
                var viewModel = new AccountReadViewModel
                {
                    Title = model.Name,
                    Breadcrumb = new Breadcrumb(),
                    Account = model,
                    EditButton = ButtonViewModel.Create(
                        ButtonViewModel.Edit, "Account",
                        Url.Action("Edit", "Account", new { id = model.Id }))
                };

                return View(viewModel);
            }
        }

        // GET: /Account/Opportunities/{id}
        public async Task<ActionResult> Opportunities(Guid id)
        {
            Response.AppendHeader("guid", id.ToString());

            using (var context = await GetCrmContext())
            {
                var query = GetQuery(context);
                var model = query.GetItem(id);

                var viewModel = new AccountReadViewModel
                {
                    Title = model.Name,
                    Breadcrumb = new Breadcrumb(),
                    DomainModel = model,
                    CreateButton = ButtonViewModel.Create(
                        ButtonViewModel.New, "Opportunity",
                        Url.Action("Create", "Opportunity", new { id = model.Id })
                        ),
                    EditButton = ButtonViewModel.Create(
                        ButtonViewModel.Edit, "Account",
                        Url.Action("Edit", "Account", new { id = model.Id }))
                };

                return View(viewModel);
            }
        }
    }
}