text:
//
//  MainViewController.m
//  insitu
//
//  Created by Hector Goycoolea on 3/26/14.
//  Copyright (c) 2014 Hector Goycoolea. All rights reserved.
//
#import "MainViewController.h"
#include "SatelliteHelper.h"

@interface MainViewController ()
/// propertie de las imagenes de cada mercante
@property (strong,nonatomic) NSMutableArray* avatarList;
/// id de cada uno de los mercantes
@property (strong,nonatomic) NSMutableArray* idsList;
/// imagen del home de cada
@property (strong,nonatomic) NSMutableArray* homeList;

@property (strong,nonatomic) NSMutableArray *vistas;

@property (strong, nonatomic) IBOutlet UIImageView *barra_top;
@property (strong, nonatomic) IBOutlet UIImageView *barra_down;
@end

@implementation MainViewController

@synthesize locationManager;
@synthesize refreshControl;
@synthesize jsonObjects;
@synthesize pageControl;
@synthesize ui_slides;
@synthesize barra_down, barra_top;
/*
 *
 */
- (void)viewDidLoad
{
    [super viewDidLoad];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task, preferably in chunks.
        NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(InitializeCLControler) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    });

    [self downloadMercantesMembresiasPagadas];
    // Call changePage each time value of pageControl changes
    [self.pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];

    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tappedRightButton:)];
    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.view addGestureRecognizer:swipeLeft];

    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tappedLeftButton:)];
    [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.view addGestureRecognizer:swipeRight];

    UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tappedUpButton:)];
    [swipeUp setDirection:UISwipeGestureRecognizerDirectionUp];
    [self.view addGestureRecognizer:swipeUp];

    UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tappedDownButton:)];
    [swipeDown setDirection:UISwipeGestureRecognizerDirectionDown];
    [self.view addGestureRecognizer:swipeDown];

}

- (IBAction)infoForMechant:(id)sender{

}

- (IBAction)tappedUpButton:(id)sender
{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.7f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    transition.type = kCATransitionFade;

    [barra_top.layer addAnimation:transition forKey:nil];
    [barra_down.layer addAnimation:transition forKey:nil];

    barra_top.hidden = YES;
    barra_down.hidden = YES;
}

- (IBAction)tappedDownButton:(id)sender
{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.7f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    transition.type = kCATransitionFade;

    [barra_top.layer addAnimation:transition forKey:nil];
    [barra_down.layer addAnimation:transition forKey:nil];

    barra_top.hidden = NO;
    barra_down.hidden = NO;
}

- (IBAction)tappedRightButton:(id)sender
{
    int pageToGo = [self.pageControl currentPage] + 1;
    if(pageToGo>=0){

        CATransition *transition = [CATransition animation];
        transition.duration = 1.0f;
        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
        transition.type = kCATransitionFade;

        [self.ui_slides.layer addAnimation:transition forKey:nil];

        self.ui_slides.image =[self.vistas objectAtIndex:pageToGo];
        self.pageControl.currentPage = pageToGo;

        /// NSUserDefaults
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        /// card holder number
        [prefs setObject:[self.idsList objectAtIndex:pageToGo] forKey:@"id_merchant_selected"];
        /// we syncrho the preferences
        [prefs synchronize];

    }
}

- (IBAction)tappedLeftButton:(id)sender
{
    int pageToGo = [self.pageControl currentPage] - 1;
    if(pageToGo>=0){
        CATransition *transition = [CATransition animation];
        transition.duration = 1.0f;
        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
        transition.type = kCATransitionFade;

        [self.ui_slides.layer addAnimation:transition forKey:nil];

        self.ui_slides.image =[self.vistas objectAtIndex:pageToGo];
        self.pageControl.currentPage = pageToGo;

        /// NSUserDefaults
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        /// card holder number
        [prefs setObject:[self.idsList objectAtIndex:pageToGo] forKey:@"id_merchant_selected"];
        /// we syncrho the preferences
        [prefs synchronize];
    }
}

- (IBAction) changePage:(id)sender {
    self.ui_slides.image =[self.vistas objectAtIndex:[self.pageControl currentPage]];
}

- (void)downloadMercantesMembresiasPagadas {
    // make up some test data
    self.avatarList = [NSMutableArray arrayWithCapacity:1];
    self.idsList = [NSMutableArray arrayWithCapacity:1];
    self.homeList = [NSMutableArray arrayWithCapacity:1];
    // Set up the views array with 3 UIImageViews
    self.vistas = [NSMutableArray arrayWithCapacity:1];
    /// we initialize the helper
    SatelliteHelper *helper = [[SatelliteHelper alloc] init];
    /// this will show me the response
    NSString *response = [helper readMercantesPorMembresias:@"1,2,3"];
    /// let's configure the data
    NSData* data=[response dataUsingEncoding: [NSString defaultCStringEncoding] ];
    /// error for the json objects
    NSError *error = nil;
    /// now we get an array of the all json file
    jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    int count = 0;
    /// let's loop foreach on the statement
    for(NSDictionary *keys in jsonObjects){
        NSString *_id = [keys objectForKey:@"ID"];
        NSString *avatar = [keys objectForKey:@"UrlImageLogo"];
        NSString *img_home = [keys objectForKey:@"UrlImageHome"];

        /// let's make a circle of the avatar for the company
        UIImage *imagesHome = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img_home]]];
        if(imagesHome!=nil){
            /// we add the promotion
            [self.avatarList addObject:avatar];
            [self.idsList addObject:_id];
            [self.homeList addObject:img_home];
            [self.vistas addObject:imagesHome];
            count++;
        }
    }
    /// first image load
    self.ui_slides.image =[self.vistas objectAtIndex:0];
    /// we set the pages with the images that we have
    self.pageControl.numberOfPages = count;
    self.pageControl.currentPage = 0;
    /// NSUserDefaults
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    /// card holder number
    [prefs setObject:[self.idsList objectAtIndex:0] forKey:@"id_merchant_selected"];
    /// we syncrho the preferences
    [prefs synchronize];

    /// response to the log
    NSLog(@"%@",response);
}
/*
 *
 */
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Flipside View
/*
 *
 */
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/**/
- (void)categoryViewControllerDidFinish:(CategoryControllerViewTableViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/*
 *
 */
- (void)menuViewControllerDidFinish:(MenuViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/*
 *
 */
- (void)wallViewControllerDidFinish:(WallViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
///
- (void)merchantInfoViewControllerDidFinish:(MerchantInfoViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
///
- (void)mapsViewControllerDidFinish:(MapsViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
///
- (void)searchViewControllerDidFinish:(SearchViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/*
 *
 */
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showAlternate"]) {
        [[segue destinationViewController] setDelegate:self];
    }
}
/*
 * InitializeCLControler
 *
 * Method that initializes the Core Location Controller
 */
-(void) InitializeCLControler
{
    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    locationManager.delegate = self;
    [locationManager startUpdatingLocation];
}
/*
 *
 */
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	if([locationManager.delegate conformsToProtocol:@protocol(CLLocationManagerDelegate)]) {  // Check if the class assigning itself as the delegate conforms to our protocol.  If not, the message will go nowhere.  Not good.
		[self locationUpdate:newLocation];
	}
}
/*
 *
 */
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
	if([locationManager.delegate conformsToProtocol:@protocol(CLLocationManagerDelegate)]) {  // Check if the class assigning itself as the delegate conforms to our protocol.  If not, the message will go nowhere.  Not good.
		//[self locationError:error];
	}
}
/*
 *
 */
- (void)locationUpdate:(CLLocation *)location {
    /// we initialize the helper
    SatelliteHelper *helper = [[SatelliteHelper alloc] init];
    // we set the errro to manager
    self.locationManager.distanceFilter = 50.0f;
    /// we set the acuracy
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    /// we delegate them to self
    self.locationManager.delegate = self;
    /// first we get the location Manager location
    CLLocation *ulocation = [locationManager location];
    /// we now get the coordinates
    CLLocationCoordinate2D userCoordinate = ulocation.coordinate;
    /// we now get users speed
    NSString *speed = [NSString stringWithFormat:@"%f", [location speed]];
    /// x coordinate
    NSString *lat = [[NSString alloc]initWithFormat:@"%f", userCoordinate.latitude];
    /// y coordinate
    NSString *lon = [[NSString alloc ]initWithFormat:@"%f", userCoordinate.longitude ];
    /// altitude
    NSString *alt = [NSString stringWithFormat:@"%f", [location altitude]];
    /// client
    NSString *client = @"1";
    /// this will show me the response
    NSString *response = [helper acknowledgeRutas:lat Longitude:lon Speed:speed Altitude:alt Client:client];
    /// we present answers to the debugers only if dif from nil
    if(response!=nil){
    /// response to the log
    NSLog(@"%@",response);
    }
}
@end


text:
@implementation OCUnitIOSLogicTestRunner

- (NSTask *)otestTaskWithTestBundle:(NSString *)testBundlePath
{
  NSString *launchPath = [NSString stringWithFormat:@"%@/Developer/%@",
                          _buildSettings[Xcode_SDKROOT],
                          _framework[kTestingFrameworkIOSTestrunnerName]];
  NSArray *args = [[self testArguments] arrayByAddingObject:testBundlePath];
  NSMutableDictionary *env = [NSMutableDictionary dictionary];

  // In Xcode 6 `sim` doesn't set `CFFIXED_USER_HOME` if simulator is not launched
  // but this environment is used, for example, by NSHomeDirectory().
  // To avoid similar situations in future let's copy all simulator environments
  if (ToolchainIsXcode6OrBetter()) {
    SimDevice *device = [(SimulatorInfoXcode6 *)self.simulatorInfo simulatedDevice];
    NSDictionary *simulatorEnvironment = [device environment];
    if (simulatorEnvironment) {
      [env addEntriesFromDictionary:simulatorEnvironment];
    }
    NSString *fixedUserHome = simulatorEnvironment[@"CFFIXED_USER_HOME"];
    if (!fixedUserHome && [device dataPath]) {
      env[@"CFFIXED_USER_HOME"] = [device dataPath];
    }
  }

  // adding custom xctool environment variables
  [env addEntriesFromDictionary:@{
    @"DYLD_INSERT_LIBRARIES" : [XCToolLibPath() stringByAppendingPathComponent:@"otest-shim-ios.dylib"],
    @"DYLD_FRAMEWORK_PATH" : _buildSettings[Xcode_BUILT_PRODUCTS_DIR],
    @"DYLD_FALLBACK_FRAMEWORK_PATH" : IOSTestFrameworkDirectories(),
    @"DYLD_LIBRARY_PATH" : _buildSettings[Xcode_BUILT_PRODUCTS_DIR],
    @"NSUnbufferedIO" : @"YES",
  }];

  // and merging with process environments and `_environment` variable contents
  env = [self otestEnvironmentWithOverrides:env];

  return [CreateTaskForSimulatorExecutable([self cpuType],
                                           [SimulatorInfo baseVersionForSDKShortVersion:[self.simulatorInfo simulatedSdkVersion]],
                                           launchPath,
                                           args,
                                           env) autorelease];
}

- (void)runTestsAndFeedOutputTo:(void (^)(NSString *))outputLineBlock
                   startupError:(NSString **)startupError
                    otherErrors:(NSString **)otherErrors
{
  NSString *sdkName = _buildSettings[Xcode_SDK_NAME];
  NSAssert([sdkName hasPrefix:@"iphonesimulator"], @"Unexpected SDK name: %@", sdkName);

  [self updateSimulatorInfo];

  NSString *testBundlePath = [self testBundlePath];
  BOOL bundleExists = [[NSFileManager defaultManager] fileExistsAtPath:testBundlePath];

  if (IsRunningUnderTest()) {
    // If we're running under test, pretend the bundle exists even if it doesn't.
    bundleExists = YES;
  }

  if (bundleExists) {
    NSString *output = nil;
    @autoreleasepool {
      NSPipe *outputPipe = [NSPipe pipe];

      NSTask *task = [self otestTaskWithTestBundle:testBundlePath];

      // Don't let STDERR pass through.  This silences the warning message that
      // comes from the 'sim' launcher when the iOS Simulator isn't running:
      // "Simulator does not seem to be running, or may be running an old SDK."
      [task setStandardError:outputPipe];

      LaunchTaskAndFeedOuputLinesToBlock(task,
                                         @"running otest/xctest on test bundle",
                                         outputLineBlock);

      NSData *outputData = [[outputPipe fileHandleForReading] readDataToEndOfFile];
      output = [[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding];
    }
    *otherErrors = [output autorelease];
  } else {
    *startupError = [NSString stringWithFormat:@"Test bundle not found at: %@", testBundlePath];
  }
}

@end

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe Spree::Address do
  let(:address) {build(:address)}

  it { is_expected.to validate_presence_of(:number) }
  it { is_expected.to validate_presence_of(:district) }

  it 'should validate length of district' do
    address.district = string_with_length(151)

    expect(address).to_not be_valid
  end

  it 'should validate number negative' do
    address.number = -1

    expect(address).to_not be_valid
  end

  context '#save' do
    subject { address }

    before { address.save! }

    it { is_expected.to be_persisted }
  end

  def string_with_length(length)
    (1..length).map { (65 + rand(26)).chr }.join
  end
end


text:
package com.amazonaws.services.sns.model;

import java.io.Serializable;

/**
 *

 * Response for ListTopics action.
 *

 */
public class ListTopicsResult implements Serializable, Cloneable {

    /**
     * A list of topic ARNs.
     */
    private com.amazonaws.internal.ListWithAutoConstructFlag<Topic> topics;

    /**
     * Token to pass along to the next ListTopics request. This
     * element is returned if there are additional topics to retrieve.
     */
    private String nextToken;

    /**
     * A list of topic ARNs.
     *
     * @return A list of topic ARNs.
     */
    public java.util.List<Topic> getTopics() {
        if (topics == null) {
              topics = new com.amazonaws.internal.ListWithAutoConstructFlag<Topic>();
              topics.setAutoConstruct(true);
        }
        return topics;
    }

    /**
     * A list of topic ARNs.
     *
     * @param topics A list of topic ARNs.
     */
    public void setTopics(java.util.Collection<Topic> topics) {
        if (topics == null) {
            this.topics = null;
            return;
        }
        com.amazonaws.internal.ListWithAutoConstructFlag<Topic> topicsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<Topic>(topics.size());
        topicsCopy.addAll(topics);
        this.topics = topicsCopy;
    }

    /**
     * A list of topic ARNs.
     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setTopics(java.util.Collection)} or {@link
     * #withTopics(java.util.Collection)} if you want to override the
     * existing values.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param topics A list of topic ARNs.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ListTopicsResult withTopics(Topic... topics) {
        if (getTopics() == null) setTopics(new java.util.ArrayList<Topic>(topics.length));
        for (Topic value : topics) {
            getTopics().add(value);
        }
        return this;
    }

    /**
     * A list of topic ARNs.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param topics A list of topic ARNs.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ListTopicsResult withTopics(java.util.Collection<Topic> topics) {
        if (topics == null) {
            this.topics = null;
        } else {
            com.amazonaws.internal.ListWithAutoConstructFlag<Topic> topicsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<Topic>(topics.size());
            topicsCopy.addAll(topics);
            this.topics = topicsCopy;
        }

        return this;
    }

    /**
     * Token to pass along to the next ListTopics request. This
     * element is returned if there are additional topics to retrieve.
     *
     * @return Token to pass along to the next ListTopics request. This
     *         element is returned if there are additional topics to retrieve.
     */
    public String getNextToken() {
        return nextToken;
    }

    /**
     * Token to pass along to the next ListTopics request. This
     * element is returned if there are additional topics to retrieve.
     *
     * @param nextToken Token to pass along to the next ListTopics request. This
     *         element is returned if there are additional topics to retrieve.
     */
    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     * Token to pass along to the next ListTopics request. This
     * element is returned if there are additional topics to retrieve.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param nextToken Token to pass along to the next ListTopics request. This
     *         element is returned if there are additional topics to retrieve.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ListTopicsResult withNextToken(String nextToken) {
        this.nextToken = nextToken;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getTopics() != null) sb.append("Topics: " + getTopics() + ",");
        if (getNextToken() != null) sb.append("NextToken: " + getNextToken() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getTopics() == null) ? 0 : getTopics().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof ListTopicsResult == false) return false;
        ListTopicsResult other = (ListTopicsResult)obj;

        if (other.getTopics() == null ^ this.getTopics() == null) return false;
        if (other.getTopics() != null && other.getTopics().equals(this.getTopics()) == false) return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null) return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false;
        return true;
    }

    @Override
    public ListTopicsResult clone() {
        try {
            return (ListTopicsResult) super.clone();

        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                    + "even though we're Cloneable!",
                    e);
        }

    }

}


text: Chef::Log.info "CURSE YOU...Perry the Platypus!!!!"


text:
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System.IO;
using Perspex.Media;

namespace Perspex.Platform
{
    /// <summary>
    /// Defines the main platform-specific interface for the rendering subsystem.
    /// </summary>
    public interface IPlatformRenderInterface
    {
        /// <summary>
        /// Creates a formatted text implementation.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="fontFamilyName">The font family.</param>
        /// <param name="fontSize">The font size.</param>
        /// <param name="fontStyle">The font style.</param>
        /// <param name="textAlignment">The text alignment.</param>
        /// <param name="fontWeight">The font weight.</param>
        /// <returns>An <see cref="IFormattedTextImpl"/>.</returns>
        IFormattedTextImpl CreateFormattedText(
            string text,
            string fontFamilyName,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight);

        /// <summary>
        /// Creates a stream geometry implementation.
        /// </summary>
        /// <returns>An <see cref="IStreamGeometryImpl"/>.</returns>
        IStreamGeometryImpl CreateStreamGeometry();

        /// <summary>
        /// Creates a renderer.
        /// </summary>
        /// <param name="handle">The platform handle for the renderer.</param>
        /// <param name="width">The initial width of the render.</param>
        /// <param name="height">The initial height of the render.</param>
        /// <returns>An <see cref="IRenderTarget"/>.</returns>
        IRenderTarget CreateRenderer(IPlatformHandle handle);

        /// <summary>
        /// Creates a render target bitmap implementation.
        /// </summary>
        /// <param name="width">The width of the bitmap.</param>
        /// <param name="height">The height of the bitmap.</param>
        /// <returns>An <see cref="IRenderTargetBitmapImpl"/>.</returns>
        IRenderTargetBitmapImpl CreateRenderTargetBitmap(int width, int height);

        /// <summary>
        /// Loads a bitmap implementation from a file..
        /// </summary>
        /// <param name="fileName">The filename of the bitmap.</param>
        /// <returns>An <see cref="IBitmapImpl"/>.</returns>
        IBitmapImpl LoadBitmap(string fileName);

        /// <summary>
        /// Loads a bitmap implementation from a file..
        /// </summary>
        /// <param name="stream">The stream to read the bitmap from.</param>
        /// <returns>An <see cref="IBitmapImpl"/>.</returns>
        IBitmapImpl LoadBitmap(Stream stream);
    }
}


text:
using System.Web.Mvc;
using System.Web.Routing;
using GalleryMVC_With_Auth.Resources;

namespace GalleryMVC_With_Auth
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("Default", "{controller}/{action}/{id}",
                new {controller = Defines.HomeControllerName, action = Defines.IndexView, id = UrlParameter.Optional}
                );
        }
    }
}


text:
/*
 * Author: Minho Kim (ISKU)
 * Date: 2017.12.23
 * E-mail: minho1a@hanmail.net
 *
 * https://github.com/ISKU/Algorithm
 * https://www.acmicpc.net/problem/15272
 */

import java.util.*;

public class Main {
	public static void main(String... args) {
		String s = new Scanner(System.in).next();
		System.out.print(s.contains("ss") ? "hiss" : "no hiss");
	}
}


text:
<?php

namespace OanhNN\AdminLte\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProfileRequest extends FormRequest
{

}


text:
<?php
namespace PlaygroundFlow\Service;

use PlaygroundFlow\Service\OpenGraphObject;
use Laminas\ServiceManager\Factory\FactoryInterface;
use Interop\Container\ContainerInterface;

class OpenGraphObjectFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $service = new OpenGraphObject($container);

        return $service;
    }
}


text:
require "strscan"

class ComfortableMexicanSofa::Content::ParamsParser

  class Error < StandardError; end

  STRING_LITERAL  = %r{'[^']*'|"[^"]*"}
  IDENTIFIER      = %r{[a-z0-9][\w\-/.]*}i
  HASH_KEY        = %r{#{IDENTIFIER}:}
  COMMA           = %r{,}
  HASH_OPEN       = %r{\{}
  HASH_CLOSE      = %r{\}}
  ARRAY_OPEN      = %r{\[}
  ARRAY_CLOSE     = %r{\]}

  # @param <String> string
  def initialize(string = "")
    @string = string
  end

  # Takes CMS content tag parameters and converts them into array of strings,
  # hashes and arrays.
  #
  # @return [Array<String, {String => String}>]
  # @raise [Error] if the given `text` is malformed.
  #
  # @example
  #   new("a, b, c").parse
  #   #=> ["a", "b", "c"]
  #
  #   new("a, b: c, d: e").parse
  #   #=> ["a", {"b" => "c", "d" => "e"}]
  #
  #   new("a, b: {c: [d, e]}").parse
  #   #=> ["a", {"b" => {"c" => ["d", "e"]}}]
  #
  def params
    @tokens = tokenize(@string)
    parse_params
  end

private

  # Contructs root-level list of arguments sent via content tag
  def parse_params
    params = []
    while (token = @tokens.shift)
      params << parse_value(token)
    end
    params
  end

  # Gets token value. Will trigger parsing of hash and array structures
  def parse_value(token)
    case token&.first
    when :string
      token[1]
    when :hash_key
      @tokens.unshift(token)
      parse_hash
    when :hash_open
      parse_hash
    when :array_open
      parse_array
    else
      raise Error, "Invalid params: #{@string}"
    end
  end

  # Hash constructor method. Will handle nested hashes as well
  def parse_hash
    opens = 1
    hash = {}

    while (token = @tokens.shift)
      case token&.first
      when :hash_key
        hash[token[1]] = parse_value(@tokens.shift)
      when :hash_close
        opens -= 1
      when :hash_open
        opens += 1
      else
        raise Error, "Invalid params: #{@string}"
      end

      return hash if opens.zero?
    end

    # We're can't really detect unclosed hashes as we can construct them without
    # opening brakets. For example, `a: b, c: d` is same as `{a: b, c: d}` and
    # `{a: b, c: d` is also ends up to be a valid hash. It will error out if
    # unclosed hash is followed by some other unexpected token. Like: `{a: b, c`
    hash
  end

  # Array construction method. Will handle nested arrays
  def parse_array
    opens = 1
    array = []
    while (token = @tokens.shift)
      case token&.first
      when :array_close
        opens -= 1
      else
        array << parse_value(token)
      end

      return array if opens.zero?
    end

    raise Error, "Unclosed array param: #{@string}"
  end

  # Tokenizing input string into a list of touples
  # Also args_string is stripped of "smart" quotes coming from wysiwyg
  #
  # @param [String] args_string
  # @return [Array<String>] tokens
  def tokenize(args_string)
    args_string = args_string.tr("""''", %q(""''))
    ss = StringScanner.new(args_string)
    tokens = []
    loop do
      ss.skip(%r{\s*})
      break if ss.eos?

      # commas are just separators like spaces
      next if ss.scan(COMMA)

      tokens <<
        if    (t = ss.scan(STRING_LITERAL)) then [:string, t[1...-1]]
        elsif (t = ss.scan(HASH_KEY))       then [:hash_key, t[0...-1]]
        elsif (t = ss.scan(IDENTIFIER))     then [:string, t]
        elsif (t = ss.scan(HASH_OPEN))      then [:hash_open, t]
        elsif (t = ss.scan(HASH_CLOSE))     then [:hash_close, t]
        elsif (t = ss.scan(ARRAY_OPEN))     then [:array_open, t]
        elsif (t = ss.scan(ARRAY_CLOSE))    then [:array_close, t]
        else
          raise Error, "Unexpected char: #{ss.getch}"
        end
    end

    tokens
  end

end


text: module.export = require('./lib/JDateTime.js');


text:
"""
    The core addon is responsible for verifying core settings that are not
    checked by other addons.
"""
from mitmproxy import exceptions
from mitmproxy import platform
from mitmproxy.net import server_spec
from mitmproxy.utils import human

class CoreOptionValidation:
    def configure(self, opts, updated):
        if opts.add_upstream_certs_to_client_chain and not opts.upstream_cert:
            raise exceptions.OptionsError(
                "The no-upstream-cert and add-upstream-certs-to-client-chain "
                "options are mutually exclusive. If no-upstream-cert is enabled "
                "then the upstream certificate is not retrieved before generating "
                "the client certificate chain."
            )
        if "body_size_limit" in updated and opts.body_size_limit:
            try:
                opts._processed["body_size_limit"] = human.parse_size(
                    opts.body_size_limit
                )
            except ValueError as e:
                raise exceptions.OptionsError(
                    "Invalid body size limit specification: %s" %
                    opts.body_size_limit
                )
        if "mode" in updated:
            mode = opts.mode
            if mode.startswith("reverse:") or mode.startswith("upstream:"):
                try:
                    server_spec.parse_with_mode(mode)
                except ValueError as e:
                    raise exceptions.OptionsError(str(e)) from e
            elif mode == "transparent":
                if not platform.original_addr:
                    raise exceptions.OptionsError(
                        "Transparent mode not supported on this platform."
                    )
            elif mode not in ["regular", "socks5"]:
                raise exceptions.OptionsError(
                    "Invalid mode specification: %s" % mode
                )


text:
Imports System
Imports System.Runtime.InteropServices

Namespace Examples
    Friend Class Program
        <STAThread>
        Shared Sub Main(ByVal args() As String)
            Dim application As SolidEdgeFramework.Application = Nothing
            Dim document As SolidEdgeFramework.SolidEdgeDocument = Nothing
            Dim variables As SolidEdgeFramework.Variables = Nothing
            Dim variable As SolidEdgeFramework.variable = Nothing

            Try
                ' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
                OleMessageFilter.Register()

                ' Attempt to connect to a running instance of Solid Edge.
                application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)

                document = CType(application.ActiveDocument, SolidEdgeFramework.SolidEdgeDocument)

                variables = CType(document.Variables, SolidEdgeFramework.Variables)

                variable = CType(variables.Add("Variable1", "100.0", SolidEdgeConstants.UnitTypeConstants.igUnitDistance), SolidEdgeFramework.variable)

                ' Get the Variable with Translate method.
                variable = CType(variables.Translate("Variable1"), SolidEdgeFramework.variable)
            Catch ex As System.Exception
                Console.WriteLine(ex)
            Finally
                OleMessageFilter.Unregister()
            End Try
        End Sub
    End Class
End Namespace


text:
package pulsarreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/pulsarreceiver"

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"go.opentelemetry.io/collector/pdata/plog"
	"go.opentelemetry.io/collector/pdata/pmetric"
	"go.opentelemetry.io/collector/pdata/ptrace"
)

// copy from kafka receiver
func TestNewPdataTracesUnmarshaler(t *testing.T) {
	um := newPdataTracesUnmarshaler(&ptrace.ProtoUnmarshaler{}, "test")
	assert.Equal(t, "test", um.Encoding())
}

func TestNewPdataMetricsUnmarshaler(t *testing.T) {
	um := newPdataMetricsUnmarshaler(&pmetric.ProtoUnmarshaler{}, "test")
	assert.Equal(t, "test", um.Encoding())
}

func TestNewPdataLogsUnmarshaler(t *testing.T) {
	um := newPdataLogsUnmarshaler(&plog.ProtoUnmarshaler{}, "test")
	assert.Equal(t, "test", um.Encoding())
}


text:
Bug #49985 (pdo_pgsql prepare() re-use previous aborted transaction)
--SKIPIF--
<?php
if (!extension_loaded('pdo') || !extension_loaded('pdo_pgsql')) die('skip not loaded');
require dirname(__FILE__) . '/config.inc';
require dirname(__FILE__) . '/../../../ext/pdo/tests/pdo_test.inc';
PDOTest::skip();
?>
--FILE--
<?php
require dirname(__FILE__) . '/../../../ext/pdo/tests/pdo_test.inc';
$db = PDOTest::test_factory(dirname(__FILE__) . '/common.phpt');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->exec("CREATE TABLE test (a int PRIMARY KEY)");

for ($i = 0; $i < 3; $i++) {
    try {
        $db->beginTransaction();
        $stmt = $db->prepare("INSERT INTO test (a) VALUES (?)");
        var_dump($stmt->execute(array(1)));
        $db->commit();
    } catch (Exception $e) {
        echo trim(current(explode("\n", $e->getMessage())))."\n";
        $db->rollback();
    }
}

?>
--EXPECTF--
bool(true)
SQLSTATE[23505]: %stest_pkey%s
SQLSTATE[23505]: %stest_pkey%s


text:
'use strict';

module.exports = {
  bmp:  require('./parse_stream/bmp'),
  gif:  require('./parse_stream/gif'),
  ico:  require('./parse_stream/ico'),
  jpeg: require('./parse_stream/jpeg'),
  png:  require('./parse_stream/png'),
  psd:  require('./parse_stream/psd'),
  svg:  require('./parse_stream/svg'),
  tiff: require('./parse_stream/tiff'),
  webp: require('./parse_stream/webp')
};


text:
using System.Configuration;

namespace NLogger.Configuration
{
    /// <summary>
    /// Generic logger appender configuration element
    /// </summary>
    public class NLoggerAppender : RootAppender
    {
        /// <summary>
        /// Appender name
        /// </summary>
        [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
        public string Name
        {
            get { return (string) this["name"]; }
            set { this["name"] = value; }
        }

        /// <summary>
        /// Appender type
        /// </summary>
        [ConfigurationProperty("type", IsRequired = true)]
        public string Type
        {
            get { return (string) this["type"]; }
            set { this["type"] = value; }
        }

        /// <summary>
        /// Appender parameters
        /// </summary>
        [ConfigurationProperty("parameters", IsRequired = false)]
        public string Parameters
        {
            get { return (string) this["parameters"]; }
            set { this["parameters"] = value; }
        }

        /// <summary>
        /// Appender file options
        /// </summary>
        [ConfigurationProperty("file", IsRequired = false)]
        public NLoggerFile File
        {
            get { return (NLoggerFile) this["file"]; }
            set { this["file"] = value; }
        }

        /// <summary>
        /// Maximum time allowed between writes even if queue is not long enough
        /// </summary>
        [ConfigurationProperty("timesincelastwrite")]
        public string TimeSinceLastWrite
        {
            get { return (string) this["timesincelastwrite"]; }
            set { this["timesincelastwrite"] = value; }
        }

        /// <summary>
        /// Maximum allowed queue size before a write occurs
        /// </summary>
        [ConfigurationProperty("maxqueuesize")]
        public int MaxQueueSize
        {
            get { return (int) this["maxqueuesize"]; }
            set { this["maxqueuesize"] = value; }
        }

        /// <summary>
        /// Time between queue checks
        /// </summary>
        [ConfigurationProperty("timebetweenchecks")]
        public int TimeBetweenChecks
        {
            get { return (int) this["timebetweenchecks"]; }
            set { this["timebetweenchecks"] = value; }
        }
    }
}


text:
// NOLINT(namespace-envoy)

// This file is part of the QUICHE platform implementation, and is not to be
// consumed or referenced directly by other Envoy code. It serves purely as a
// porting layer for QUICHE.

#include <set>

#include "source/common/common/assert.h"
#include "source/common/http/utility.h"

#include "absl/flags/flag.h"
#include "absl/strings/ascii.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "quiche_platform_impl/quiche_flags_impl.h"

namespace {

// Envoy uses different default values for some QUICHE flags. The following methods
// ensure that the absl::Flag objects are created with the correct values for
// these flags. This ensures that the absl::FlagSaver finds the correct values
// and avoid a race condition between the dynamic initialization of these flags
// and the FlagSaver in tests.
template <typename T> constexpr T maybeOverride(absl::string_view /*name*/, T val) { return val; }

template <> constexpr bool maybeOverride<bool>(absl::string_view name, bool val) {
  if (name == "quic_reloadable_flag_quic_disable_version_draft_29") {
    // Envoy only supports RFC-v1 in the long term, so disable IETF draft 29 implementation by
    // default.
    return true;
  }
  if (name == "quic_reloadable_flag_quic_default_to_bbr") {
    // This flag enables BBR, otherwise QUIC will use Cubic which is less performant.
    return true;
  }
  if (name == "quic_header_size_limit_includes_overhead") {
    // Do not include 32-byte per-entry overhead while counting header size.
    return false;
  }

  return val;
}

template <> constexpr int32_t maybeOverride<int32_t>(absl::string_view name, int32_t val) {
  if (name == "quic_buffered_data_threshold") {
    // Set send buffer twice of max flow control window to ensure that stream send
    // buffer always takes all the data.
    // The max amount of data buffered is the per-stream high watermark + the max
    // flow control window of upstream. The per-stream high watermark should be
    // smaller than max flow control window to make sure upper stream can be flow
    // control blocked early enough not to send more than the threshold allows.
    // TODO(#8826) Ideally we should use the negotiated value from upstream which is not accessible
    // for now. 512MB is way to large, but the actual bytes buffered should be bound by the
    // negotiated upstream flow control window.
    return 2 * ::Envoy::Http2::Utility::OptionsLimits::DEFAULT_INITIAL_STREAM_WINDOW_SIZE; // 512MB
  }
  return val;
}

} // namespace

// Flag definitions
#define QUIC_FLAG(flag, value) ABSL_FLAG(bool, envoy_##flag, maybeOverride(#flag, value), "");
#include "quiche/quic/core/quic_flags_list.h"
QUIC_FLAG(quic_reloadable_flag_spdy_testonly_default_false, false)  // NOLINT
QUIC_FLAG(quic_reloadable_flag_spdy_testonly_default_true, true)    // NOLINT
QUIC_FLAG(quic_restart_flag_spdy_testonly_default_false, false)     // NOLINT
QUIC_FLAG(quic_restart_flag_spdy_testonly_default_true, true)       // NOLINT
QUIC_FLAG(quic_reloadable_flag_http2_testonly_default_false, false) // NOLINT
QUIC_FLAG(quic_reloadable_flag_http2_testonly_default_true, true)   // NOLINT
QUIC_FLAG(quic_restart_flag_http2_testonly_default_false, false)    // NOLINT
QUIC_FLAG(quic_restart_flag_http2_testonly_default_true, true)      // NOLINT
#undef QUIC_FLAG

#define DEFINE_PROTOCOL_FLAG_IMPL(type, flag, value, help)                                         \
  ABSL_FLAG(type, envoy_##flag, maybeOverride(#flag, value), help);

#define DEFINE_PROTOCOL_FLAG_SINGLE_VALUE(type, flag, value, doc)                                  \
  DEFINE_PROTOCOL_FLAG_IMPL(type, flag, value, doc)

#define DEFINE_PROTOCOL_FLAG_TWO_VALUES(type, flag, internal_value, external_value, doc)           \
  DEFINE_PROTOCOL_FLAG_IMPL(type, flag, external_value, doc)

// Select the right macro based on the number of arguments.
#define GET_6TH_ARG(arg1, arg2, arg3, arg4, arg5, arg6, ...) arg6

#define PROTOCOL_FLAG_MACRO_CHOOSER(...)                                                           \
  GET_6TH_ARG(__VA_ARGS__, DEFINE_PROTOCOL_FLAG_TWO_VALUES, DEFINE_PROTOCOL_FLAG_SINGLE_VALUE)

#define QUIC_PROTOCOL_FLAG(...) PROTOCOL_FLAG_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__)
#include "quiche/quic/core/quic_protocol_flags_list.h"
#undef QUIC_PROTOCOL_FLAG

#define QUICHE_PROTOCOL_FLAG(...) PROTOCOL_FLAG_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__)
#include "quiche/common/quiche_protocol_flags_list.h"
#undef QUICHE_PROTOCOL_FLAG

#undef PROTOCOL_FLAG_MACRO_CHOOSER
#undef GET_6TH_ARG
#undef DEFINE_PROTOCOL_FLAG_TWO_VALUES
#undef DEFINE_PROTOCOL_FLAG_SINGLE_VALUE

namespace quiche {

namespace {

absl::flat_hash_map<absl::string_view, ReloadableFlag*> makeReloadableFlagMap() {
  absl::flat_hash_map<absl::string_view, ReloadableFlag*> flags;

  ASSERT(absl::GetFlag(FLAGS_envoy_quic_restart_flag_quic_testonly_default_true) == true);
#define QUIC_FLAG(flag, ...) flags.emplace("FLAGS_envoy_" #flag, &FLAGS_envoy_##flag);
#include "quiche/quic/core/quic_flags_list.h"
  QUIC_FLAG(quic_reloadable_flag_spdy_testonly_default_false, false)
  QUIC_FLAG(quic_reloadable_flag_spdy_testonly_default_true, true)
  QUIC_FLAG(quic_restart_flag_spdy_testonly_default_false, false)
  QUIC_FLAG(quic_restart_flag_spdy_testonly_default_true, true)
  QUIC_FLAG(quic_reloadable_flag_http2_testonly_default_false, false)
  QUIC_FLAG(quic_reloadable_flag_http2_testonly_default_true, true)
  QUIC_FLAG(quic_restart_flag_http2_testonly_default_false, false)
  QUIC_FLAG(quic_restart_flag_http2_testonly_default_true, true)
#undef QUIC_FLAG
  return flags;
}

} // namespace

FlagRegistry::FlagRegistry() : reloadable_flags_(makeReloadableFlagMap()) {}

// static
FlagRegistry& FlagRegistry::getInstance() {
  static auto* instance = new FlagRegistry();
  return *instance;
}

void FlagRegistry::updateReloadableFlags(
    const absl::flat_hash_map<std::string, bool>& quiche_flags_override) {
  for (auto& [flag_name, flag] : reloadable_flags_) {
    const auto it = quiche_flags_override.find(flag_name);
    if (it != quiche_flags_override.end()) {
      absl::SetFlag(flag, it->second);
    }
  }
}

} // namespace quiche


text:
"""
Description     : Simple Python implementation of the Apriori Algorithm

Usage:
    $python apriori.py -f DATASET.csv -s minSupport  -c minConfidence

    $python apriori.py -f DATASET.csv -s 0.15 -c 0.6
"""

import sys

from itertools import chain, combinations
from collections import defaultdict
from optparse import OptionParser

def subsets(arr):
    """ Returns non empty subsets of arr"""
    return chain(*[combinations(arr, i + 1) for i, a in enumerate(arr)])

def returnItemsWithMinSupport(itemSet, transactionList, minSupport, freqSet):
    """calculates the support for items in the itemSet and returns a subset
   of the itemSet each of whose elements satisfies the minimum support"""
    _itemSet = set()
    _itemSetRemoved = set()
    localSet = defaultdict(int)

    for item in itemSet:
        for transaction in transactionList:
            if item.issubset(transaction):
                freqSet[item] += 1
                localSet[item] += 1

    for item, count in localSet.items():
        support = float(count)/len(transactionList)
        if support >= minSupport:
            _itemSet.add(item)
        else:
            _itemSetRemoved.add(item)

    return _itemSet, _itemSetRemoved

# def joinSet(itemSet, removedSet, length):
def joinSet(itemSet, length):
    """Join a set with itself and returns the n-element itemsets"""
    # filteredSet = set()
    # newremovedSet = set()
    # flagAddItem = True
    # composed_set = [i.union(j) for i in itemSet for j in itemSet if len(i.union(j)) == length]
    return set([i.union(j) for i in itemSet for j in itemSet if len(i.union(j)) == length])
    # for item in composed_set:
    #     if removedSet != set([]):
    #         for itemR in removedSet:
    #             if itemR.issubset(item):
    #                 flagAddItem = False
    #                 break
    #     if flagAddItem == True:
    #         filteredSet.add(item)
    #     else:
    #         newremovedSet.add(item)
    # return filteredSet, newremovedSet

def getItemSetTransactionList(data_iterator):
    transactionList = list()
    itemSet = set()
    for record in data_iterator:
        transaction = frozenset(record)
        transactionList.append(transaction)
        for item in transaction:
            itemSet.add(frozenset([item]))              # Generate 1-itemSets
    return itemSet, transactionList

def runApriori(data_iter, minSupport, minConfidence):
    """
    run the apriori algorithm. data_iter is a record iterator
    Return both:
     - items (tuple, support)
     - rules ((pretuple, posttuple), confidence)
    """
    itemSet, transactionList = getItemSetTransactionList(data_iter)

    freqSet = defaultdict(int)
    largeSet = dict()
    # Global dictionary which stores (key=n-itemSets,value=support)
    # which satisfy minSupport

    assocRules = dict()
    # Dictionary which stores Association Rules

    oneCSet, removedSet = returnItemsWithMinSupport(itemSet,
                                        transactionList,
                                        minSupport,
                                        freqSet)

    currentLSet = oneCSet
    k = 2
    while(currentLSet != set([])):
        largeSet[k-1] = currentLSet
        #currentLSet, removedSet = joinSet(currentLSet, removedSet,  k)
        currentLSet, removedSet = joinSet(currentLSet, k)
        currentCSet = returnItemsWithMinSupport(currentLSet,
                                                transactionList,
                                                minSupport,
                                                freqSet)
        currentLSet = currentCSet
        k = k + 1

    def getSupport(item):
            """local function which Returns the support of an item"""
            return float(freqSet[item])/len(transactionList)

    toRetItems = []
    for key, value in largeSet.items():
        toRetItems.extend([(tuple(item), getSupport(item))
                           for item in value])

    toRetRules = []
    for key, value in largeSet.items():
        for item in value:
            _subsets = map(frozenset, [x for x in subsets(item)])
            for element in _subsets:
                remain = item.difference(element)
                if len(remain) > 0:
                    confidence = getSupport(item)/getSupport(element)
                    if confidence >= minConfidence:
                        toRetRules.append(((tuple(element), tuple(remain)),
                                           confidence))
    return toRetItems, toRetRules

def printResults(items, rules):
    """prints the generated itemsets sorted by support and the confidence rules sorted by confidence"""
    for item, support in sorted(items, key=lambda tp: tp[1]):
        print("item: %s , %.3f" % (str(item), support))
    print("\n------------------------ RULES:")
    for rule, confidence in sorted(rules, key=lambda tp: tp[1]):
        pre, post = rule
        print("Rule: %s ==> %s , %.3f" % (str(pre), str(post), confidence))

def dataFromFile(fname):
    """Function which reads from the file and yields a generator"""
    file_iter = open(fname, 'rU')
    for line in file_iter:
        line = line.strip().rstrip(',')                         # Remove trailing comma
        record = frozenset(line.split(','))
        yield record

if __name__ == "__main__":

    optparser = OptionParser()
    optparser.add_option('-f', '--inputFile',
                         dest='input',
                         help='filename containing csv',
                         default=None)
    optparser.add_option('-s', '--minSupport',
                         dest='minS',
                         help='minimum support value',
                         default=0.15,
                         type='float')
    optparser.add_option('-c', '--minConfidence',
                         dest='minC',
                         help='minimum confidence value',
                         default=0.6,
                         type='float')

    (options, args) = optparser.parse_args()

    inFile = None
    if options.input is None:
            inFile = sys.stdin
    elif options.input is not None:
            inFile = dataFromFile(options.input)
    else:
            print('No dataset filename specified, system with exit')
            sys.exit('System will exit')

    minSupport = options.minS
    minConfidence = options.minC

    items, rules = runApriori(inFile, minSupport, minConfidence)

    printResults(items, rules)


text:
from __future__ import unicode_literals
import os
import unittest

from prometheus_client import Gauge, Counter, Summary, Histogram, Metric
from prometheus_client import CollectorRegistry, generate_latest, ProcessCollector

class TestCounter(unittest.TestCase):
    def setUp(self):
        self.registry = CollectorRegistry()
        self.counter = Counter('c', 'help', registry=self.registry)

    def test_increment(self):
        self.assertEqual(0, self.registry.get_sample_value('c'))
        self.counter.inc()
        self.assertEqual(1, self.registry.get_sample_value('c'))
        self.counter.inc(7)
        self.assertEqual(8, self.registry.get_sample_value('c'))

    def test_negative_increment_raises(self):
        self.assertRaises(ValueError, self.counter.inc, -1)

    def test_function_decorator(self):
        @self.counter.count_exceptions(ValueError)
        def f(r):
            if r:
                raise ValueError
            else:
                raise TypeError

        try:
            f(False)
        except TypeError:
            pass
        self.assertEqual(0, self.registry.get_sample_value('c'))

        try:
            f(True)
        except ValueError:
            raised = True
        self.assertEqual(1, self.registry.get_sample_value('c'))

    def test_block_decorator(self):
        with self.counter.count_exceptions():
            pass
        self.assertEqual(0, self.registry.get_sample_value('c'))

        raised = False
        try:
            with self.counter.count_exceptions():
                raise ValueError
        except:
            raised = True
        self.assertTrue(raised)
        self.assertEqual(1, self.registry.get_sample_value('c'))

class TestGauge(unittest.TestCase):
    def setUp(self):
        self.registry = CollectorRegistry()
        self.gauge = Gauge('g', 'help', registry=self.registry)

    def test_gauge(self):
        self.assertEqual(0, self.registry.get_sample_value('g'))
        self.gauge.inc()
        self.assertEqual(1, self.registry.get_sample_value('g'))
        self.gauge.dec(3)
        self.assertEqual(-2, self.registry.get_sample_value('g'))
        self.gauge.set(9)
        self.assertEqual(9, self.registry.get_sample_value('g'))

    def test_function_decorator(self):
        self.assertEqual(0, self.registry.get_sample_value('g'))

        @self.gauge.track_inprogress()
        def f():
            self.assertEqual(1, self.registry.get_sample_value('g'))

        f()
        self.assertEqual(0, self.registry.get_sample_value('g'))

    def test_block_decorator(self):
        self.assertEqual(0, self.registry.get_sample_value('g'))
        with self.gauge.track_inprogress():
            self.assertEqual(1, self.registry.get_sample_value('g'))
        self.assertEqual(0, self.registry.get_sample_value('g'))

    def test_gauge_function(self):
        x = {}
        self.gauge.set_function(lambda: len(x))
        self.assertEqual(0, self.registry.get_sample_value('g'))
        self.gauge.inc()
        self.assertEqual(0, self.registry.get_sample_value('g'))
        x['a'] = None
        self.assertEqual(1, self.registry.get_sample_value('g'))

class TestSummary(unittest.TestCase):
    def setUp(self):
        self.registry = CollectorRegistry()
        self.summary = Summary('s', 'help', registry=self.registry)

    def test_summary(self):
        self.assertEqual(0, self.registry.get_sample_value('s_count'))
        self.assertEqual(0, self.registry.get_sample_value('s_sum'))
        self.summary.observe(10)
        self.assertEqual(1, self.registry.get_sample_value('s_count'))
        self.assertEqual(10, self.registry.get_sample_value('s_sum'))

    def test_function_decorator(self):
        self.assertEqual(0, self.registry.get_sample_value('s_count'))

        @self.summary.time()
        def f():
            pass

        f()
        self.assertEqual(1, self.registry.get_sample_value('s_count'))

    def test_block_decorator(self):
        self.assertEqual(0, self.registry.get_sample_value('s_count'))
        with self.summary.time():
            pass
        self.assertEqual(1, self.registry.get_sample_value('s_count'))

class TestHistogram(unittest.TestCase):
    def setUp(self):
        self.registry = CollectorRegistry()
        self.histogram = Histogram('h', 'help', registry=self.registry)
        self.labels = Histogram('hl', 'help', ['l'], registry=self.registry)

    def test_histogram(self):
        self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '1.0'}))
        self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '2.5'}))
        self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '5.0'}))
        self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '+Inf'}))
        self.assertEqual(0, self.registry.get_sample_value('h_count'))
        self.assertEqual(0, self.registry.get_sample_value('h_sum'))

        self.histogram.observe(2)
        self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '1.0'}))
        self.assertEqual(1, self.registry.get_sample_value('h_bucket', {'le': '2.5'}))
        self.assertEqual(1, self.registry.get_sample_value('h_bucket', {'le': '5.0'}))
        self.assertEqual(1, self.registry.get_sample_value('h_bucket', {'le': '+Inf'}))
        self.assertEqual(1, self.registry.get_sample_value('h_count'))
        self.assertEqual(2, self.registry.get_sample_value('h_sum'))

        self.histogram.observe(2.5)
        self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '1.0'}))
        self.assertEqual(2, self.registry.get_sample_value('h_bucket', {'le': '2.5'}))
        self.assertEqual(2, self.registry.get_sample_value('h_bucket', {'le': '5.0'}))
        self.assertEqual(2, self.registry.get_sample_value('h_bucket', {'le': '+Inf'}))
        self.assertEqual(2, self.registry.get_sample_value('h_count'))
        self.assertEqual(4.5, self.registry.get_sample_value('h_sum'))

        self.histogram.observe(float("inf"))
        self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '1.0'}))
        self.assertEqual(2, self.registry.get_sample_value('h_bucket', {'le': '2.5'}))
        self.assertEqual(2, self.registry.get_sample_value('h_bucket', {'le': '5.0'}))
        self.assertEqual(3, self.registry.get_sample_value('h_bucket', {'le': '+Inf'}))
        self.assertEqual(3, self.registry.get_sample_value('h_count'))
        self.assertEqual(float("inf"), self.registry.get_sample_value('h_sum'))

    def test_setting_buckets(self):
        h = Histogram('h', 'help', registry=None, buckets=[0, 1, 2])
        self.assertEqual([0.0, 1.0, 2.0, float("inf")], h._upper_bounds)

        h = Histogram('h', 'help', registry=None, buckets=[0, 1, 2, float("inf")])
        self.assertEqual([0.0, 1.0, 2.0, float("inf")], h._upper_bounds)

        self.assertRaises(ValueError, Histogram, 'h', 'help', registry=None, buckets=[])
        self.assertRaises(ValueError, Histogram, 'h', 'help', registry=None, buckets=[float("inf")])
        self.assertRaises(ValueError, Histogram, 'h', 'help', registry=None, buckets=[3, 1])

    def test_labels(self):
        self.labels.labels('a').observe(2)
        self.assertEqual(0, self.registry.get_sample_value('hl_bucket', {'le': '1.0', 'l': 'a'}))
        self.assertEqual(1, self.registry.get_sample_value('hl_bucket', {'le': '2.5', 'l': 'a'}))
        self.assertEqual(1, self.registry.get_sample_value('hl_bucket', {'le': '5.0', 'l': 'a'}))
        self.assertEqual(1, self.registry.get_sample_value('hl_bucket', {'le': '+Inf', 'l': 'a'}))
        self.assertEqual(1, self.registry.get_sample_value('hl_count', {'l': 'a'}))
        self.assertEqual(2, self.registry.get_sample_value('hl_sum', {'l': 'a'}))

    def test_function_decorator(self):
        self.assertEqual(0, self.registry.get_sample_value('h_count'))
        self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '+Inf'}))

        @self.histogram.time()
        def f():
            pass

        f()
        self.assertEqual(1, self.registry.get_sample_value('h_count'))
        self.assertEqual(1, self.registry.get_sample_value('h_bucket', {'le': '+Inf'}))

    def test_block_decorator(self):
        self.assertEqual(0, self.registry.get_sample_value('h_count'))
        self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '+Inf'}))
        with self.histogram.time():
            pass
        self.assertEqual(1, self.registry.get_sample_value('h_count'))
        self.assertEqual(1, self.registry.get_sample_value('h_bucket', {'le': '+Inf'}))

class TestMetricWrapper(unittest.TestCase):
    def setUp(self):
        self.registry = CollectorRegistry()
        self.counter = Counter('c', 'help', labelnames=['l'], registry=self.registry)
        self.two_labels = Counter('two', 'help', labelnames=['a', 'b'], registry=self.registry)

    def test_child(self):
        self.counter.labels('x').inc()
        self.assertEqual(1, self.registry.get_sample_value('c', {'l': 'x'}))
        self.two_labels.labels('x', 'y').inc(2)
        self.assertEqual(2, self.registry.get_sample_value('two', {'a': 'x', 'b': 'y'}))

    def test_remove(self):
        self.counter.labels('x').inc()
        self.counter.labels('y').inc(2)
        self.assertEqual(1, self.registry.get_sample_value('c', {'l': 'x'}))
        self.assertEqual(2, self.registry.get_sample_value('c', {'l': 'y'}))
        self.counter.remove('x')
        self.assertEqual(None, self.registry.get_sample_value('c', {'l': 'x'}))
        self.assertEqual(2, self.registry.get_sample_value('c', {'l': 'y'}))

    def test_incorrect_label_count_raises(self):
        self.assertRaises(ValueError, self.counter.labels)
        self.assertRaises(ValueError, self.counter.labels, 'a', 'b')
        self.assertRaises(ValueError, self.counter.remove)
        self.assertRaises(ValueError, self.counter.remove, 'a', 'b')

    def test_labels_coerced_to_string(self):
        self.counter.labels(None).inc()
        self.counter.labels({'l': None}).inc()
        self.assertEqual(2, self.registry.get_sample_value('c', {'l': 'None'}))

        self.counter.remove(None)
        self.assertEqual(None, self.registry.get_sample_value('c', {'l': 'None'}))

    def test_non_string_labels_raises(self):
        class Test(object):
            __str__ = None
        self.assertRaises(TypeError, self.counter.labels, Test())
        self.assertRaises(TypeError, self.counter.labels, {'l': Test()})

    def test_namespace_subsystem_concatenated(self):
        c = Counter('c', 'help', namespace='a', subsystem='b', registry=self.registry)
        c.inc()
        self.assertEqual(1, self.registry.get_sample_value('a_b_c'))

    def test_labels_by_dict(self):
        self.counter.labels({'l': 'x'}).inc()
        self.assertEqual(1, self.registry.get_sample_value('c', {'l': 'x'}))
        self.assertRaises(ValueError, self.counter.labels, {'l': 'x', 'm': 'y'})
        self.assertRaises(ValueError, self.counter.labels, {'m': 'y'})
        self.assertRaises(ValueError, self.counter.labels, {})
        self.two_labels.labels({'a': 'x', 'b': 'y'}).inc()
        self.assertEqual(1, self.registry.get_sample_value('two', {'a': 'x', 'b': 'y'}))
        self.assertRaises(ValueError, self.two_labels.labels, {'a': 'x', 'b': 'y', 'c': 'z'})
        self.assertRaises(ValueError, self.two_labels.labels, {'a': 'x', 'c': 'z'})
        self.assertRaises(ValueError, self.two_labels.labels, {'b': 'y', 'c': 'z'})
        self.assertRaises(ValueError, self.two_labels.labels, {'c': 'z'})
        self.assertRaises(ValueError, self.two_labels.labels, {})

    def test_invalid_names_raise(self):
        self.assertRaises(ValueError, Counter, '', 'help')
        self.assertRaises(ValueError, Counter, '^', 'help')
        self.assertRaises(ValueError, Counter, '', 'help', namespace='&')
        self.assertRaises(ValueError, Counter, '', 'help', subsystem='(')
        self.assertRaises(ValueError, Counter, 'c', '', labelnames=['^'])
        self.assertRaises(ValueError, Counter, 'c', '', labelnames=['__reserved'])
        self.assertRaises(ValueError, Summary, 'c', '', labelnames=['quantile'])

class TestGenerateText(unittest.TestCase):
    def setUp(self):
        self.registry = CollectorRegistry()

    def test_counter(self):
        c = Counter('cc', 'A counter', registry=self.registry)
        c.inc()
        self.assertEqual(b'# HELP cc A counter\n# TYPE cc counter\ncc 1.0\n', generate_latest(self.registry))

    def test_gauge(self):
        g = Gauge('gg', 'A gauge', registry=self.registry)
        g.set(17)
        self.assertEqual(b'# HELP gg A gauge\n# TYPE gg gauge\ngg 17.0\n', generate_latest(self.registry))

    def test_summary(self):
        s = Summary('ss', 'A summary', ['a', 'b'], registry=self.registry)
        s.labels('c', 'd').observe(17)
        self.assertEqual(b'# HELP ss A summary\n# TYPE ss summary\nss_count{a="c",b="d"} 1.0\nss_sum{a="c",b="d"} 17.0\n', generate_latest(self.registry))

    def test_unicode(self):
        c = Counter('cc', '\u4500', ['l'], registry=self.registry)
        c.labels('\u4500').inc()
        self.assertEqual(b'# HELP cc \xe4\x94\x80\n# TYPE cc counter\ncc{l="\xe4\x94\x80"} 1.0\n', generate_latest(self.registry))

    def test_escaping(self):
        c = Counter('cc', 'A\ncount\\er', ['a'], registry=self.registry)
        c.labels('\\x\n"').inc(1)
        self.assertEqual(b'# HELP cc A\\ncount\\\\er\n# TYPE cc counter\ncc{a="\\\\x\\n\\""} 1.0\n', generate_latest(self.registry))

    def test_nonnumber(self):
        class MyNumber():
            def __repr__(self):
              return "MyNumber(123)"
            def __float__(self):
              return 123.0
        class MyCollector():
            def collect(self):
                metric = Metric("nonnumber", "Non number", 'untyped')
                metric.add_sample("nonnumber", {}, MyNumber())
                yield metric
        self.registry.register(MyCollector())
        self.assertEqual(b'# HELP nonnumber Non number\n# TYPE nonnumber untyped\nnonnumber 123.0\n', generate_latest(self.registry))

class TestProcessCollector(unittest.TestCase):
    def setUp(self):
        self.registry = CollectorRegistry()
        self.test_proc = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'proc')

    def test_working(self):
        collector = ProcessCollector(proc=self.test_proc, pid=lambda: 26231, registry=self.registry)
        collector._ticks = 100

        self.assertEqual(17.21, self.registry.get_sample_value('process_cpu_seconds_total'))
        self.assertEqual(56274944.0, self.registry.get_sample_value('process_virtual_memory_bytes'))
        self.assertEqual(8114176, self.registry.get_sample_value('process_resident_memory_bytes'))
        self.assertEqual(1418184099.75, self.registry.get_sample_value('process_start_time_seconds'))
        self.assertEqual(2048.0, self.registry.get_sample_value('process_max_fds'))
        self.assertEqual(5.0, self.registry.get_sample_value('process_open_fds'))
        self.assertEqual(None, self.registry.get_sample_value('process_fake_namespace'))

    def test_namespace(self):
        collector = ProcessCollector(proc=self.test_proc, pid=lambda: 26231, registry=self.registry, namespace='n')
        collector._ticks = 100

        self.assertEqual(17.21, self.registry.get_sample_value('n_process_cpu_seconds_total'))
        self.assertEqual(56274944.0, self.registry.get_sample_value('n_process_virtual_memory_bytes'))
        self.assertEqual(8114176, self.registry.get_sample_value('n_process_resident_memory_bytes'))
        self.assertEqual(1418184099.75, self.registry.get_sample_value('n_process_start_time_seconds'))
        self.assertEqual(2048.0, self.registry.get_sample_value('n_process_max_fds'))
        self.assertEqual(5.0, self.registry.get_sample_value('n_process_open_fds'))
        self.assertEqual(None, self.registry.get_sample_value('process_cpu_seconds_total'))

    def test_working_584(self):
        collector = ProcessCollector(proc=self.test_proc, pid=lambda: "584\n", registry=self.registry)
        collector._ticks = 100

        self.assertEqual(0.0, self.registry.get_sample_value('process_cpu_seconds_total'))
        self.assertEqual(10395648.0, self.registry.get_sample_value('process_virtual_memory_bytes'))
        self.assertEqual(634880, self.registry.get_sample_value('process_resident_memory_bytes'))
        self.assertEqual(1418291667.75, self.registry.get_sample_value('process_start_time_seconds'))
        self.assertEqual(None, self.registry.get_sample_value('process_max_fds'))
        self.assertEqual(None, self.registry.get_sample_value('process_open_fds'))

    def test_working_fake_pid(self):
        collector = ProcessCollector(proc=self.test_proc, pid=lambda: 123, registry=self.registry)
        collector._ticks = 100

        self.assertEqual(None, self.registry.get_sample_value('process_cpu_seconds_total'))
        self.assertEqual(None, self.registry.get_sample_value('process_virtual_memory_bytes'))
        self.assertEqual(None, self.registry.get_sample_value('process_resident_memory_bytes'))
        self.assertEqual(None, self.registry.get_sample_value('process_start_time_seconds'))
        self.assertEqual(None, self.registry.get_sample_value('process_max_fds'))
        self.assertEqual(None, self.registry.get_sample_value('process_open_fds'))
        self.assertEqual(None, self.registry.get_sample_value('process_fake_namespace'))

if __name__ == '__main__':
    unittest.main()


text:
package webplang.web;

import static org.springframework.web.bind.annotation.RequestMethod.*;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Controller of the home section
 */
@Controller
@RequestMapping("/home")
public class HomeController {

  @RequestMapping(method = GET)
  public String page(Model model) {
    return "home";
  }

}


text:
var AppDispatcher = require("../dispatcher/AppDispatcher");
var MetaDataConfigurationActionTypes = require("../constants/MetaDataConfigurationActionTypes");
var MetaDataConfigurationStore = require("../stores/MetaDataConfigurationStore");
var AppEventEmitter = require("../EventEmitter");
var NodeEventEmitter = require("events").EventEmitter;
var APIResponseMixin = require("../mixins/APIResponseMixin");
var update = require("react-addons-update");

class MetaDataConfigurationActions extends NodeEventEmitter {

  reorder(newOrder, baseUrl) {
    var oldOrder = _.map(MetaDataConfigurationStore.fields, function (data) {
      return { name: data.name, order: data.order };
    });

    baseUrl += "/reorder";

    AppDispatcher.dispatch({
      actionType: MetaDataConfigurationActionTypes.MDC_REORDER_FIELDS,
      newFieldOrder: newOrder,
    });

    $.ajax({
      url: baseUrl,
      dataType: "json",
      method: "PUT",
      data: {
        fields: newOrder,
      },
      success: (function() {
        this.emit("ChangeReorderFinished", true);
      }).bind(this),
      error: (function(xhr) {
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_REORDER_FIELDS,
          newFieldOrder: oldOrder,
        });
        this.emit("ChangeReorderFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", "Reorder Failed.  Please try again if the problem persists please contact WSE unit.");
      }).bind(this),
    });
  }

  changeActive(fieldName, activeValue, pushToUrl){
    // Clone values in order to revert the store if the change fails
    var previousValue = MetaDataConfigurationStore.fields[fieldName].active;
    var fieldValues = update(MetaDataConfigurationStore.fields[fieldName], {});

    // Optimistically change the store
    fieldValues.active = activeValue;
    AppDispatcher.dispatch({
      actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_FIELD,
      name: fieldName,
      values: fieldValues,
    });

    pushToUrl += "/" + fieldName;
    $.ajax({
      url: pushToUrl,
      dataType: "json",
      method: "PUT",
      data: {
        fields: fieldValues,
      },
      success: (function() {
        // Store was already changed, nothing to do here
        this.emit("ChangeActiveFinished", true);
        AppEventEmitter.emit("MessageCenterDisplay", "info", "Collection updated");
      }).bind(this),
      error: (function(xhr) {
        // Request to change failed, revert the store to previous values
        fieldValues.active = previousValue;
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_FIELD,
          name: fieldName,
          values: fieldValues,
        });
        // Communicate the error to the user
        this.emit("ChangeActiveFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", APIResponseMixin.apiErrorToString(xhr));
      }).bind(this)
    });
  }

  changeField(fieldName, fieldValues, pushToUrl) {
    // Clone values in order to revert the store if the change fails
    var previousValues = update(MetaDataConfigurationStore.fields[fieldName], {});

    pushToUrl += "/" + fieldName;

    $.ajax({
      url: pushToUrl,
      dataType: "json",
      method: "PUT",
      data: {
        fields: fieldValues,
      },
      success: (function(result) {
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_FIELD,
          name: result.field.name,
          values: result.field,
        });
        this.emit("ChangeFieldFinished", true, result.field);
        AppEventEmitter.emit("MessageCenterDisplay", "info", "Collection updated");
      }).bind(this),
      error: (function(xhr) {
        // Request to change failed, revert the store to previous values on if it is updated
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_FIELD,
          name: fieldName,
          values: previousValues,
        });
        // Communicate the error to the user
        this.emit("ChangeFieldFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", "Save failed. Please select a type and unique label and try again.");
      }).bind(this)
    });
  }

  createField(fieldName, fieldValues, pushToUrl) {
    var requiredValues = _.pick(fieldValues, "defaultFormField", "label", "multiple", "optionalFormField", "required", "type");
    var postValues = _.omit(requiredValues, function(value) { return _.isNull(value); });

    $.ajax({
      url: pushToUrl,
      dataType: "json",
      method: "POST",
      data: {
        fields: postValues,
      },
      success: (function(result) {
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_FIELD,
          name: result.field.name,
          values: result.field,
        });
        this.emit("CreateFieldFinished", true, result.field);
        AppEventEmitter.emit("MessageCenterDisplay", "info", "Collection updated");
      }).bind(this),
      error: (function(xhr) {
        // Communicate the error to the user
        this.emit("CreateFieldFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", "Create failed. Please select a unique label and try again.");
      }).bind(this)
    });
  }

  changeFacet(facetName, facetValues, pushToUrl) {
    // Clone values in order to revert the store if the change fails
    var match = MetaDataConfigurationStore.facets.find(function(facet) {
      return facet.name === facetName;
    });
    if (!match) {
      return;
    }
    var previousValues = update(match, {});

    $.ajax({
      url: `${pushToUrl}/${facetName}`,
      dataType: "json",
      method: "PUT",
      data: facetValues,
      success: (function(result) {
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_FACET,
          name: result.facet.name,
          values: result.facet,
        });
        this.emit("ChangeFacetFinished", true, result);
        AppEventEmitter.emit("MessageCenterDisplay", "info", "Collection updated");
      }).bind(this),
      error: (function(xhr) {
        // Request to change failed, revert the store to previous values on if it is updated
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_FACET,
          name: facetName,
          values: previousValues,
        });
        // Communicate the error to the user
        this.emit("ChangeFacetFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", "Save failed. Please refresh and try again.");
      }).bind(this)
    });
  }

  createFacet(facetName, facetValues, pushToUrl) {
    var requiredValues = _.pick(facetValues, "name", "field_name", "label", "limit", "order");
    var postValues = _.omit(requiredValues, function(value) { return _.isNull(value); });

    $.ajax({
      url: pushToUrl,
      dataType: "json",
      method: "POST",
      data: postValues,
      success: (function(result) {
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_FACET,
          name: result.facet.name,
          values: result.facet,
        })
        this.emit("CreateFacetFinished", true, result);
        AppEventEmitter.emit("MessageCenterDisplay", "info", "Collection updated");
      }).bind(this),
      error: (function(xhr) {
        // Communicate the error to the user
        this.emit("CreateFacetFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", "Create failed. Please select a unique field and try again.");
      }).bind(this)
    });
  }

  removeFacet(facetName, pushToUrl) {
    // Clone values in order to revert the store if the remove fails
    var match = MetaDataConfigurationStore.facets.find(function(facet) {
      return facet.name === facetName;
    });
    var previousValues = update(match, {});

    // Optimistically change the store
    AppDispatcher.dispatch({
      actionType: MetaDataConfigurationActionTypes.MDC_REMOVE_FACET,
      name: facetName,
    });

    $.ajax({
      url: `${pushToUrl}/${facetName}`,
      dataType: "json",
      method: "DELETE",
      success: (function() {
        // Store was already changed, nothing to do here
        this.emit("RemoveFacetFinished", true);
        AppEventEmitter.emit("MessageCenterDisplay", "info", "Collection updated");
      }).bind(this),
      error: (function(xhr) {
        // Request to change failed, revert the store to previous values
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_FACET,
          name: facetName,
          values: previousValues,
        });
        // Communicate the error to the user
        this.emit("RemoveFacetFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", APIResponseMixin.apiErrorToString(xhr));
      }).bind(this)
    });
  }

  reorderFacets(newOrder, baseUrl) {
    var oldOrder = _.map(MetaDataConfigurationStore.facets, function (data) {
      return { name: data.name, order: data.order };
    });

    AppDispatcher.dispatch({
      actionType: MetaDataConfigurationActionTypes.MDC_REORDER_FACETS,
      newFacetOrder: newOrder,
    });

    $.ajax({
      url: `${baseUrl}/reorder`,
      dataType: "json",
      method: "PUT",
      data: {
        facets: newOrder,
      },
      success: (function() {
        this.emit("FacetReorderFinished", true);
      }).bind(this),
      error: (function(xhr) {
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_REORDER_FACETS,
          newFacetOrder: oldOrder,
        });
        this.emit("FacetReorderFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", "Reorder Failed.  Please try again. If the problem persists, please contact WSE unit.");
      }).bind(this),
    });
  }

  changeSort(sortName, sortValues, pushToUrl) {
    // Clone values in order to revert the store if the change fails
    var match = MetaDataConfigurationStore.sorts.find(function(sort) {
      return sort.name === sortName;
    });
    if (!match) {
      return;
    }
    var previousValues = update(match, {});

    $.ajax({
      url: `${pushToUrl}/${sortName}`,
      dataType: "json",
      method: "PUT",
      data: sortValues,
      success: (function(result) {
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_SORT,
          name: result.sort.name,
          values: result.sort,
        });
        this.emit("ChangeSortFinished", true, result);
        AppEventEmitter.emit("MessageCenterDisplay", "info", "Collection updated");
      }).bind(this),
      error: (function(xhr) {
        // Request to change failed, revert the store to previous values on if it is updated
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_SORT,
          name: sortName,
          values: previousValues,
        });
        // Communicate the error to the user
        this.emit("ChangeSortFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", "Save failed. Please refresh and try again.");
      }).bind(this)
    });
  }

  createSort(sortName, sortValues, pushToUrl) {
    var requiredValues = _.pick(sortValues, "name", "field_name", "label", "direction", "order");
    var postValues = _.omit(requiredValues, function(value) { return _.isNull(value); });

    $.ajax({
      url: pushToUrl,
      dataType: "json",
      method: "POST",
      data: postValues,
      success: (function(result) {
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_SORT,
          name: result.sort.name,
          values: result.sort,
        })
        this.emit("CreateSortFinished", true, result);
        AppEventEmitter.emit("MessageCenterDisplay", "info", "Collection updated");
      }).bind(this),
      error: (function(xhr) {
        // Communicate the error to the user
        this.emit("CreateSortFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", "Create failed. Please select a unique field + direction combination.");
      }).bind(this)
    });
  }

  removeSort(sortName, pushToUrl) {
    // Clone values in order to revert the store if the remove fails
    var match = MetaDataConfigurationStore.sorts.find(function(sort) {
      return sort.name === sortName;
    });
    var previousValues = update(match, {});

    // Optimistically change the store
    AppDispatcher.dispatch({
      actionType: MetaDataConfigurationActionTypes.MDC_REMOVE_SORT,
      name: sortName,
    });

    $.ajax({
      url: `${pushToUrl}/${sortName}`,
      dataType: "json",
      method: "DELETE",
      success: (function() {
        // Store was already changed, nothing to do here
        this.emit("RemoveSortFinished", true);
        AppEventEmitter.emit("MessageCenterDisplay", "info", "Collection updated");
      }).bind(this),
      error: (function(xhr) {
        // Request to change failed, revert the store to previous values
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_CHANGE_SORT,
          name: sortName,
          values: previousValues,
        });
        // Communicate the error to the user
        this.emit("RemoveSortFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", APIResponseMixin.apiErrorToString(xhr));
      }).bind(this)
    });
  }

  reorderSorts(newOrder, baseUrl) {
    var oldOrder = _.map(MetaDataConfigurationStore.sorts, function (data) {
      return { name: data.name, order: data.order };
    });

    AppDispatcher.dispatch({
      actionType: MetaDataConfigurationActionTypes.MDC_REORDER_SORTS,
      newSortOrder: newOrder,
    });

    $.ajax({
      url: `${baseUrl}/reorder`,
      dataType: "json",
      method: "PUT",
      data: {
        sorts: newOrder,
      },
      success: (function() {
        this.emit("SortReorderFinished", true);
      }).bind(this),
      error: (function(xhr) {
        AppDispatcher.dispatch({
          actionType: MetaDataConfigurationActionTypes.MDC_REORDER_SORTS,
          newSortOrder: oldOrder,
        });
        this.emit("SortReorderFinished", false, xhr);
        AppEventEmitter.emit("MessageCenterDisplay", "error", "Reorder Failed.  Please try again. If the problem persists, please contact WSE unit.");
      }).bind(this),
    });
  }
}

module.exports = new MetaDataConfigurationActions();


text:
<?php

declare(strict_types=1);

namespace Valkyrja\Annotation\Constants;

/**
 * Constant Alias.
 *
 * @author Melech Mizrachi
 */
final class Alias
{
    public const REQUEST_METHOD = 'RequestMethod';
    public const STATUS_CODE    = 'StatusCode';
}


text:
package es.itecban.deployment.model.deployment.target;

import org.eclipse.emf.common.util.EMap;

import org.eclipse.emf.ecore.EObject;

import org.eclipse.emf.ecore.util.FeatureMap;

/**
 *
 * A representation of the model object 'Document Root'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getMixed Mixed}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getXMLNSPrefixMap XMLNS Prefix Map}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getXSISchemaLocation XSI Schema Location}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getBridge Bridge}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getContainer Container}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getContainerType Container Type}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getDomain Domain}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getInterconnect Interconnect}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getNode Node}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getRuntimeResource Runtime Resource}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getRuntimeUnit Runtime Unit}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getStatus Status}

 *
{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getSupportedPackage Supported Package}

 *

 *

 *
 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot()
 * @model extendedMetaData="name='' kind='mixed'"
 * @generated
 */
public interface DocumentRoot extends EObject {
	/**
	 * Returns the value of the 'Mixed' attribute list.
	 * The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}.
	 *
	 *

	 * If the meaning of the 'Mixed' attribute list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Mixed' attribute list.
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_Mixed()
	 * @model unique="false" dataType="org.eclipse.emf.ecore.EFeatureMapEntry" many="true"
	 *        extendedMetaData="kind='elementWildcard' name=':mixed'"
	 * @generated
	 */
	FeatureMap getMixed();

	/**
	 * Returns the value of the 'XMLNS Prefix Map' map.
	 * The key is of type {@link java.lang.String},
	 * and the value is of type {@link java.lang.String},
	 *
	 *

	 * If the meaning of the 'XMLNS Prefix Map' map isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'XMLNS Prefix Map' map.
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_XMLNSPrefixMap()
	 * @model mapType="org.eclipse.emf.ecore.EStringToStringMapEntry<org.eclipse.emf.ecore.EString, org.eclipse.emf.ecore.EString>" transient="true"
	 *        extendedMetaData="kind='attribute' name='xmlns:prefix'"
	 * @generated
	 */
	EMap<String, String> getXMLNSPrefixMap();

	/**
	 * Returns the value of the 'XSI Schema Location' map.
	 * The key is of type {@link java.lang.String},
	 * and the value is of type {@link java.lang.String},
	 *
	 *

	 * If the meaning of the 'XSI Schema Location' map isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'XSI Schema Location' map.
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_XSISchemaLocation()
	 * @model mapType="org.eclipse.emf.ecore.EStringToStringMapEntry<org.eclipse.emf.ecore.EString, org.eclipse.emf.ecore.EString>" transient="true"
	 *        extendedMetaData="kind='attribute' name='xsi:schemaLocation'"
	 * @generated
	 */
	EMap<String, String> getXSISchemaLocation();

	/**
	 * Returns the value of the 'Bridge' containment reference.
	 *
	 *

	 * If the meaning of the 'Bridge' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Bridge' containment reference.
	 * @see #setBridge(BridgeType)
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_Bridge()
	 * @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='bridge' namespace='##targetNamespace'"
	 * @generated
	 */
	BridgeType getBridge();

	/**
	 * Sets the value of the '{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getBridge Bridge}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Bridge' containment reference.
	 * @see #getBridge()
	 * @generated
	 */
	void setBridge(BridgeType value);

	/**
	 * Returns the value of the 'Container' containment reference.
	 *
	 *

	 * If the meaning of the 'Container' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Container' containment reference.
	 * @see #setContainer(ContainerType)
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_Container()
	 * @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='container' namespace='##targetNamespace'"
	 * @generated
	 */
	ContainerType getContainer();

	/**
	 * Sets the value of the '{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getContainer Container}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Container' containment reference.
	 * @see #getContainer()
	 * @generated
	 */
	void setContainer(ContainerType value);

	/**
	 * Returns the value of the 'Container Type' containment reference.
	 *
	 *

	 * If the meaning of the 'Container Type' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Container Type' containment reference.
	 * @see #setContainerType(ContainerTypeType)
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_ContainerType()
	 * @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='containerType' namespace='##targetNamespace'"
	 * @generated
	 */
	ContainerTypeType getContainerType();

	/**
	 * Sets the value of the '{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getContainerType Container Type}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Container Type' containment reference.
	 * @see #getContainerType()
	 * @generated
	 */
	void setContainerType(ContainerTypeType value);

	/**
	 * Returns the value of the 'Domain' containment reference.
	 *
	 *

	 * If the meaning of the 'Domain' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Domain' containment reference.
	 * @see #setDomain(DeploymentTargetType)
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_Domain()
	 * @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='domain' namespace='##targetNamespace'"
	 * @generated
	 */
	DeploymentTargetType getDomain();

	/**
	 * Sets the value of the '{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getDomain Domain}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Domain' containment reference.
	 * @see #getDomain()
	 * @generated
	 */
	void setDomain(DeploymentTargetType value);

	/**
	 * Returns the value of the 'Interconnect' containment reference.
	 *
	 *

	 * If the meaning of the 'Interconnect' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Interconnect' containment reference.
	 * @see #setInterconnect(InterconnectType)
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_Interconnect()
	 * @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='interconnect' namespace='##targetNamespace'"
	 * @generated
	 */
	InterconnectType getInterconnect();

	/**
	 * Sets the value of the '{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getInterconnect Interconnect}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Interconnect' containment reference.
	 * @see #getInterconnect()
	 * @generated
	 */
	void setInterconnect(InterconnectType value);

	/**
	 * Returns the value of the 'Node' containment reference.
	 *
	 *

	 * If the meaning of the 'Node' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Node' containment reference.
	 * @see #setNode(NodeType)
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_Node()
	 * @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='node' namespace='##targetNamespace'"
	 * @generated
	 */
	NodeType getNode();

	/**
	 * Sets the value of the '{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getNode Node}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Node' containment reference.
	 * @see #getNode()
	 * @generated
	 */
	void setNode(NodeType value);

	/**
	 * Returns the value of the 'Runtime Resource' containment reference.
	 *
	 *

	 * If the meaning of the 'Runtime Resource' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Runtime Resource' containment reference.
	 * @see #setRuntimeResource(RuntimeResourceType)
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_RuntimeResource()
	 * @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='runtimeResource' namespace='##targetNamespace'"
	 * @generated
	 */
	RuntimeResourceType getRuntimeResource();

	/**
	 * Sets the value of the '{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getRuntimeResource Runtime Resource}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Runtime Resource' containment reference.
	 * @see #getRuntimeResource()
	 * @generated
	 */
	void setRuntimeResource(RuntimeResourceType value);

	/**
	 * Returns the value of the 'Runtime Unit' containment reference.
	 *
	 *

	 * If the meaning of the 'Runtime Unit' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Runtime Unit' containment reference.
	 * @see #setRuntimeUnit(RuntimeUnitType)
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_RuntimeUnit()
	 * @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='runtimeUnit' namespace='##targetNamespace'"
	 * @generated
	 */
	RuntimeUnitType getRuntimeUnit();

	/**
	 * Sets the value of the '{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getRuntimeUnit Runtime Unit}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Runtime Unit' containment reference.
	 * @see #getRuntimeUnit()
	 * @generated
	 */
	void setRuntimeUnit(RuntimeUnitType value);

	/**
	 * Returns the value of the 'Status' attribute.
	 * The literals are from the enumeration {@link es.itecban.deployment.model.deployment.target.StatusType}.
	 *
	 *

	 * If the meaning of the 'Status' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Status' attribute.
	 * @see es.itecban.deployment.model.deployment.target.StatusType
	 * @see #setStatus(StatusType)
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_Status()
	 * @model unique="false" upper="-2" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='status' namespace='##targetNamespace'"
	 * @generated
	 */
	StatusType getStatus();

	/**
	 * Sets the value of the '{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getStatus Status}' attribute.
	 *
	 *
	 * @param value the new value of the 'Status' attribute.
	 * @see es.itecban.deployment.model.deployment.target.StatusType
	 * @see #getStatus()
	 * @generated
	 */
	void setStatus(StatusType value);

	/**
	 * Returns the value of the 'Supported Package' containment reference.
	 *
	 *

	 * If the meaning of the 'Supported Package' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Supported Package' containment reference.
	 * @see #setSupportedPackage(SupportedPackageType)
	 * @see es.itecban.deployment.model.deployment.target.TargetPackage#getDocumentRoot_SupportedPackage()
	 * @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='supportedPackage' namespace='##targetNamespace'"
	 * @generated
	 */
	SupportedPackageType getSupportedPackage();

	/**
	 * Sets the value of the '{@link es.itecban.deployment.model.deployment.target.DocumentRoot#getSupportedPackage Supported Package}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Supported Package' containment reference.
	 * @see #getSupportedPackage()
	 * @generated
	 */
	void setSupportedPackage(SupportedPackageType value);

} // DocumentRoot


text: ![](../img/finalpres/apicommunication.png)


text:
package org.apache.falcon.replication;

import org.apache.commons.cli.CommandLine;
import org.apache.falcon.entity.Storage;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.tools.DistCpOptions;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * Test class for FeedReplicator.
 */
public class FeedReplicatorTest {

    @Test
    public void testArguments() throws Exception {
        /*
         * <arg>-update</arg>
         * <arg>-blocking</arg><arg>true</arg>
         * <arg>-maxMaps</arg><arg>3</arg>
         * <arg>-mapBandwidth</arg><arg>4</arg>
         * <arg>-sourcePaths</arg><arg>${distcpSourcePaths}</arg>
         * <arg>-targetPath</arg><arg>${distcpTargetPaths}</arg>
         */
        final String[] args = {
            "true",
            "-maxMaps", "3",
            "-mapBandwidth", "4",
            "-sourcePaths", "hdfs://localhost:8020/tmp/",
            "-targetPath", "hdfs://localhost1:8020/tmp/",
            "-falconFeedStorageType", Storage.TYPE.FILESYSTEM.name(),
        };

        FeedReplicator replicator = new FeedReplicator();
        CommandLine cmd = replicator.getCommand(args);
        DistCpOptions options = replicator.getDistCpOptions(cmd);

        List<Path> srcPaths = new ArrayList<Path>();
        srcPaths.add(new Path("hdfs://localhost:8020/tmp/"));
        Assert.assertEquals(options.getMaxMaps(), 3);
        Assert.assertEquals(options.getMapBandwidth(), 4);
        Assert.assertEquals(options.getSourcePaths(), srcPaths);
        Assert.assertEquals(options.getTargetPath(), new Path("hdfs://localhost1:8020/tmp/"));
    }
}