text:
package com.coleman.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.text.TextUtils;

import com.coleman.log.Log;

/**
 * A general parser should have the ability to parse the following format:
 * [number][.] [hello world][.!] [你好世界!]
 *
 * @author coleman
 */
public class GeneralParser {
    private static final String TAG = GeneralParser.class.getName();

    private static Log Log = Config.getLog();

    /**
     * Assets is pre-installed files.
     *
     * @param fileName
     * @throws IOException
     */
    public static ArrayList<String> parseFile(Context context, String fileName, boolean fromAsset,
            IProgressNotifier notifier) throws IOException {
        InputStream is = null;

        // init notifier vars
        int max = 30;// progress here can go for 30%
        int cur = 0;// current progress 0%
        int total_size = 1;// total stream size
        int load_size = 1;// already load stream size

        // get the file's input stream
        if (fromAsset) {
            is = context.getAssets().open(fileName);
        } else {
            is = new FileInputStream(fileName);
        }
        total_size = is.available();

        // process the stream line by line
        int v;
        byte bytes[] = new byte[1024];
        ByteArrayOutputStream baf = new ByteArrayOutputStream();
        while ((v = is.read(bytes)) != -1) {
            baf.write(bytes, 0, v);
            load_size = baf.size();
            cur = load_size * (max - 10) / (total_size + 1);
            notifier.notify(cur);
        }
        is.close();
        String str = new String(baf.toByteArray());

        ArrayList<String> list = null;
        if (isQuickList(str)) {
            list = getQuickWorldList(str);
        } else {
            list = getWorldList(str);
        }
        notifier.notify(cur + 10);

        return list;
    }

    private static boolean isQuickList(CharSequence sb) {
        final Pattern pattern = Pattern.compile("[a-zA-Z \\.\\-/]+");
        Matcher m = pattern.matcher(sb);
        return m.matches();
    }

    private static ArrayList<String> getQuickWorldList(String sb) {
        String strs[] = sb.split("/");
        ArrayList<String> list = new ArrayList<String>();
        for (String string : strs) {
            if (!TextUtils.isEmpty(string)) {
                list.add(string);
            }
        }
        Log.i(TAG, "===coleman-debug-parse words count: " + list.size());
        return list;
    }

    private static ArrayList<String> getWorldList(CharSequence sb) {
        final Pattern WORD = Pattern.compile("[a-zA-Z]+-{0,1}[a-zA-Z]+\\b");
        final Pattern WORD_TYPE = Pattern.compile("^(prep|n|v(t|i|)|ad(j|v|)|[a-zA-Z])$");
        ArrayList<String> list = new ArrayList<String>();
        Matcher m = WORD.matcher(sb);
        String tempStr;
        while (m.find()) {
            if (!WORD_TYPE.matcher(m.group()).find()) {
                tempStr = m.group();
                if (!list.contains(tempStr)) {
                    list.add(tempStr);
                }
            } else {
                // Log.i(TAG, "skip word: " + m.group());
            }
        }
        Log.i(TAG, "===coleman-debug-parse words count: " + list.size());
        return list;
    }

    /**
     * Assets is pre-installed files.
     *
     * @param fileName
     * @throws IOException
     */
    public static HashMap<String, String> parseFile(InputStream is) throws IOException {

        // process the stream line by line
        int v;
        byte bytes[] = new byte[1024];
        ByteArrayOutputStream baf = new ByteArrayOutputStream();
        while ((v = is.read(bytes)) != -1) {
            baf.write(bytes, 0, v);
        }
        is.close();
        baf.close();
        String str = new String(baf.toByteArray());
        HashMap<String, String> list = getProperties(str);

        return list;
    }

    private static HashMap<String, String> getProperties(String sb) {
        HashMap<String, String> list = new HashMap<String, String>();
        String items[] = sb.split("\\s");
        for (String string : items) {
            if (string != null && !string.trim().equals("")) {
                list.put(string.substring(0, string.indexOf("=")).trim(),
                        string.substring(string.indexOf("=") + 1).trim());
            }
        }
        return list;
    }

    public static interface IProgressNotifier {
        void notify(int p);
    }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Kanbantastic::Column do
  use_vcr_cassette "cassette2"

  before do
    @config = Kanbantastic::Config.new(API_KEY, WORKSPACE, PROJECT_ID)
  end

  describe "all" do
    it "should return an array of columns" do
      columns = Kanbantastic::Column.all(@config)
      columns.class.should == Array
      columns.should_not be_blank
      columns.first.name.should_not be_nil
      columns.first.position.should_not be_nil
      columns.first.id.should_not be_nil
    end
  end

  describe "find" do
    it "should return the column" do
      column1 = Kanbantastic::Column.all(@config)[0]
      column1.should_not be_nil
      column2 = Kanbantastic::Column.find(@config, column1.id)
      column2.should == column1
    end
  end

  describe "first?" do
    before do
      @columns = Kanbantastic::Column.all(@config)
    end

    it "should return true if its first column" do
      column = @columns.select{|c| c.position == 1}[0]
      column.should_not be_nil
      column.should be_first
    end

    it "should return false if its not the first column" do
      column = @columns.select{|c| c.position == 2}[0]
      column.should_not be_nil
      column.should_not be_first
    end
  end

  describe "second?" do
    before do
      @columns = Kanbantastic::Column.all(@config)
    end

    it "should return true if its second column" do
      column = @columns.select{|c| c.position == 2}[0]
      column.should_not be_nil
      column.should be_second
    end

    it "should return false if its not the second column" do
      column = @columns.select{|c| c.position == 1}[0]
      column.should_not be_nil
      column.should_not be_second
    end
  end

  describe "last?" do
    before do
      @columns = Kanbantastic::Column.all(@config)
    end

    it "should return true if its last column" do
      column = @columns.last
      column.position.should == @columns.length
      column.should be_last
    end

    it "should return false if its not the last column" do
      column = @columns.select{|c| c.position == 1}[0]
      column.should_not be_nil
      column.should_not be_last
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
const char *AdEventNames[] = {
    "Ad Break Ready", "All Ads Completed", "Clicked", "Complete", "First Quartile", "Loaded",
    "Midpoint", "Pause", "Resume", "Skipped", "Started", "Tapped", "Third Quartile",
};

typedef enum { PlayButton, PauseButton } PlayButtonType;

@interface VideoViewController ()

// Tracking for play/pause
@property(nonatomic) BOOL isAdPlayback;

// Play/Pause buttons.
@property(nonatomic, strong) UIImage *playBtnBG;
@property(nonatomic, strong) UIImage *pauseBtnBG;

// Storage points for resizing between fullscreen and non-fullscreen
@property(nonatomic, assign) CGRect fullscreenVideoFrame;
@property(nonatomic, assign) CGRect portraitVideoViewFrame;
@property(nonatomic, assign) CGRect portraitVideoFrame;
@property(nonatomic, assign) CGRect fullscreenControlsFrame;
@property(nonatomic, assign) CGRect portraitControlsViewFrame;
@property(nonatomic, assign) CGRect portraitControlsFrame;
@property(nonatomic, assign) BOOL isFullscreen;

// Gesture recognizer for tap on video
@property(nonatomic, strong) UITapGestureRecognizer *videoTapRecognizer;

// IMA SDK handles
@property(nonatomic, strong) IMAAdsLoader *adsLoader;
@property(nonatomic, strong) IMAAdDisplayContainer *adDisplayContainer;
@property(nonatomic, strong) IMAAdsRenderingSettings *adsRenderingSettings;
@property(nonatomic, strong) IMAAVPlayerContentPlayhead *contentPlayhead;
@property(nonatomic, strong) IMAAdsManager *adsManager;
@property(nonatomic, strong) IMACompanionAdSlot *companionSlot;

// Content player handles
@property(nonatomic, strong) AVPlayer *contentPlayer;
@property(nonatomic, strong) AVPlayerLayer *contentPlayerLayer;
@property(nonatomic, strong) id playHeadObserver;

@end

@implementation VideoViewController

#pragma mark Set-up methods

// Set up the new view controller.
- (void)viewDidLoad {
  [super viewDidLoad];
  [self.topLabel setText:self.video.title];
  // Set the play button image.
  self.playBtnBG = [UIImage imageNamed:@"play.png"];
  // Set the pause button image.
  self.pauseBtnBG = [UIImage imageNamed:@"pause.png"];
  self.isAdPlayback = NO;
  self.isFullscreen = NO;

  // Fix iPhone issue of log text starting in the middle of the UITextView
  self.automaticallyAdjustsScrollViewInsets = NO;

  // Set up CGRects for resizing the video and controls on rotate.
  CGPoint videoViewOrigin = self.videoView.frame.origin;
  CGRect videoViewBounds = self.videoView.bounds;
  self.portraitVideoViewFrame = CGRectMake(videoViewOrigin.x, videoViewOrigin.y,
                                           videoViewBounds.size.width, videoViewBounds.size.height);
  self.portraitVideoFrame =
      CGRectMake(0, 0, videoViewBounds.size.width, videoViewBounds.size.height);

  CGPoint videoControlsOrigin = self.videoControls.frame.origin;
  CGRect videoControlsBounds = self.videoControls.bounds;
  self.portraitControlsViewFrame =
      CGRectMake(videoControlsOrigin.x, videoControlsOrigin.y, videoControlsBounds.size.width,
                 videoControlsBounds.size.height);
  self.portraitControlsFrame =
      CGRectMake(0, 0, videoControlsBounds.size.width, videoControlsBounds.size.height);

  // Set videoView on top of everything else (for fullscreen support).
  [self.view bringSubviewToFront:self.videoView];
  [self.view bringSubviewToFront:self.videoControls];

  // Check orientation, set to fullscreen if we're in landscape
  if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft ||
      [[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) {
    [self viewDidEnterLandscape];
  }

  // Set up content player and IMA classes, then request ads. If the user selected "Custom",
  // get the ad tag from the pop-up dialog.
  [self setUpContentPlayer];
  [self setUpAdsLoader];
  if ([self.video.tag isEqual:@"custom"]) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Tag"
                                                    message:@"Enter your test tag below"
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert show];
  } else {
    [self requestAdsWithTag:self.video.tag];
  }
}

- (void)viewWillDisappear:(BOOL)animated {
  [self.contentPlayer pause];
  if (self.adsManager) {
    [self.adsManager destroy];
    self.adsManager = nil;
  }
  if (self.adsLoader) {
    self.adsLoader = nil;
  }
  self.contentPlayer = nil;
  [super viewWillDisappear:animated];
}

// If pop-up dialog was shown, request ads with provided tag on dialog close.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  [self requestAdsWithTag:[[alertView textFieldAtIndex:0] text]];
}

// Initialize the content player and load content.
- (void)setUpContentPlayer {
  // Load AVPlayer with path to our content.
  NSURL *contentURL = [NSURL URLWithString:self.video.video];
  self.contentPlayer = [AVPlayer playerWithURL:contentURL];

  // Playhead observers for progress bar.
  __weak VideoViewController *controller = self;
  self.playHeadObserver = [controller.contentPlayer
      addPeriodicTimeObserverForInterval:CMTimeMake(1, 30)
                                   queue:NULL
                              usingBlock:^(CMTime time) {
                                  CMTime duration = [controller
                                      getPlayerItemDuration:self.contentPlayer.currentItem];
                                  [controller updatePlayHeadWithTime:time duration:duration];
                              }];
  [self.contentPlayer addObserver:self forKeyPath:@"rate" options:0 context:@"contentPlayerRate"];
  [self.contentPlayer addObserver:self
                       forKeyPath:@"currentItem.duration"
                          options:0
                          context:@"playerDuration"];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(contentDidFinishPlaying)
                                               name:AVPlayerItemDidPlayToEndTimeNotification
                                             object:[self.contentPlayer currentItem]];

  // Set up fullscreen tap listener to show controls
  self.videoTapRecognizer =
      [[UITapGestureRecognizer alloc] initWithTarget:self
                                              action:@selector(showFullscreenControls:)];
  [self.videoView addGestureRecognizer:self.videoTapRecognizer];

  // Create a player layer for the player.
  self.contentPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.contentPlayer];

  // Size, position, and display the AVPlayer.
  self.contentPlayerLayer.frame = self.videoView.layer.bounds;
  [self.videoView.layer addSublayer:self.contentPlayerLayer];
}

// Handler for keypath listener that is added for content playhead observer.
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
  if (context == @"contentPlayerRate" && self.contentPlayer == object) {
    [self updatePlayHeadState:(self.contentPlayer.rate != 0)];
  } else if (context == @"playerDuration" && self.contentPlayer == object) {
    [self
        updatePlayHeadDurationWithTime:[self getPlayerItemDuration:self.contentPlayer.currentItem]];
  }
}

#pragma mark UI handlers

// Handle clicks on play/pause button.
- (IBAction)onPlayPauseClicked:(id)sender {
  if (self.isAdPlayback == NO) {
    if (self.contentPlayer.rate == 0) {
      [self.contentPlayer play];
    } else {
      [self.contentPlayer pause];
    }
  } else {
    if (self.playHeadButton.tag == PlayButton) {
      [self.adsManager resume];
      [self setPlayButtonType:PauseButton];
    } else {
      [self.adsManager pause];
      [self setPlayButtonType:PlayButton];
    }
  }
}

// Updates play button for provided playback state.
- (void)updatePlayHeadState:(BOOL)isPlaying {
  [self setPlayButtonType:isPlaying ? PauseButton : PlayButton];
}

// Sets play button type.
- (void)setPlayButtonType:(PlayButtonType)buttonType {
  self.playHeadButton.tag = buttonType;
  [self.playHeadButton setImage:buttonType == PauseButton ? self.pauseBtnBG : self.playBtnBG
                       forState:UIControlStateNormal];
}

// Called when the user seeks.
- (IBAction)playHeadValueChanged:(id)sender {
  if (![sender isKindOfClass:[UISlider class]]) {
    return;
  }
  if (self.isAdPlayback == NO) {
    UISlider *slider = (UISlider *)sender;
    // If the playhead value changed by the user, skip to that point of the
    // content is skippable.
    [self.contentPlayer seekToTime:CMTimeMake(slider.value, 1)];
  }
}

// Used to track progress of ads for progress bar.
- (void)adDidProgressToTime:(NSTimeInterval)mediaTime totalTime:(NSTimeInterval)totalTime {
  CMTime time = CMTimeMakeWithSeconds(mediaTime, 1000);
  CMTime duration = CMTimeMakeWithSeconds(totalTime, 1000);
  [self updatePlayHeadWithTime:time duration:duration];
  self.progressBar.maximumValue = totalTime;
}

// Get the duration value from the player item.
- (CMTime)getPlayerItemDuration:(AVPlayerItem *)item {
  CMTime itemDuration = kCMTimeInvalid;
  if ([item respondsToSelector:@selector(duration)]) {
    itemDuration = item.duration;
  } else {
    if (item.asset && [item.asset respondsToSelector:@selector(duration)]) {
      // Sometimes the test app hangs here for ios 4.2.
      itemDuration = item.asset.duration;
    }
  }
  return itemDuration;
}

// Updates progress bar for provided time and duration.
- (void)updatePlayHeadWithTime:(CMTime)time duration:(CMTime)duration {
  if (CMTIME_IS_INVALID(time)) {
    return;
  }
  Float64 currentTime = CMTimeGetSeconds(time);
  if (isnan(currentTime)) {
    return;
  }
  self.progressBar.value = currentTime;
  self.playHeadTimeText.text =
      [NSString stringWithFormat:@"%d:%02d", (int)currentTime / 60, (int)currentTime % 60];
  [self updatePlayHeadDurationWithTime:duration];
}

// Update the current playhead duration.
- (void)updatePlayHeadDurationWithTime:(CMTime)duration {
  if (CMTIME_IS_INVALID(duration)) {
    return;
  }
  Float64 durationValue = CMTimeGetSeconds(duration);
  if (isnan(durationValue)) {
    return;
  }
  self.progressBar.maximumValue = durationValue;
  self.durationTimeText.text =
      [NSString stringWithFormat:@"%d:%02d", (int)durationValue / 60, (int)durationValue % 60];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  switch (interfaceOrientation) {
    case UIInterfaceOrientationLandscapeLeft:
    case UIInterfaceOrientationLandscapeRight:
      [self viewDidEnterPortrait];
      break;
    case UIInterfaceOrientationPortrait:
    case UIInterfaceOrientationPortraitUpsideDown:
      [self viewDidEnterLandscape];
      break;
    case UIInterfaceOrientationUnknown:
      break;
  }
}

- (void)viewDidEnterLandscape {
  self.isFullscreen = YES;
  CGRect screenRect = [[UIScreen mainScreen] bounds];
  if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
    self.fullscreenVideoFrame = CGRectMake(0, 0, screenRect.size.height, screenRect.size.width);
    self.fullscreenControlsFrame =
        CGRectMake(0, (screenRect.size.width - self.videoControls.frame.size.height),
                   screenRect.size.height, self.videoControls.frame.size.height);
  } else {
    self.fullscreenVideoFrame = CGRectMake(0, 0, screenRect.size.width, screenRect.size.height);
    self.fullscreenControlsFrame =
        CGRectMake(0, (screenRect.size.height - self.videoControls.frame.size.height),
                   screenRect.size.width, self.videoControls.frame.size.height);
  }
  [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
  [[self navigationController] setNavigationBarHidden:YES];
  self.videoView.frame = self.fullscreenVideoFrame;
  self.contentPlayerLayer.frame = self.fullscreenVideoFrame;
  self.videoControls.frame = self.fullscreenControlsFrame;
  self.videoControls.hidden = YES;
}

- (void)viewDidEnterPortrait {
  self.isFullscreen = NO;
  [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
  [[self navigationController] setNavigationBarHidden:NO];
  self.videoView.frame = self.portraitVideoViewFrame;
  self.contentPlayerLayer.frame = self.portraitVideoFrame;
  self.videoControls.frame = self.portraitControlsViewFrame;
}

- (IBAction)videoControlsTouchStarted:(id)sender {
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(hideFullscreenControls)
                                             object:self];
}

- (IBAction)videoControlsTouchEnded:(id)sender {
  [self startHideControlsTimer];
}

- (void)showFullscreenControls:(UITapGestureRecognizer *)recognizer {
  if (self.isFullscreen) {
    self.videoControls.hidden = NO;
    self.videoControls.alpha = 0.9;
    [self startHideControlsTimer];
  }
}

- (void)startHideControlsTimer {
  [self performSelector:@selector(hideFullscreenControls) withObject:self afterDelay:3];
}

- (void)hideFullscreenControls {
  [UIView animateWithDuration:0.5 animations:^{ self.videoControls.alpha = 0.0; }];
}

#pragma mark IMA SDK methods

// Initialize ad display container.
- (void)setUpAdDisplayContainer {
  // Create our AdDisplayContainer. Initialize it with our videoView as the container. This
  // will result in ads being displayed over our content video.
  if (self.companionView != nil) {
    self.adDisplayContainer =
        [[IMAAdDisplayContainer alloc] initWithAdContainer:self.videoView
                                            companionSlots:@[ self.companionSlot ]];
  } else {
    self.adDisplayContainer =
        [[IMAAdDisplayContainer alloc] initWithAdContainer:self.videoView companionSlots:nil];
  }
}

// Register companion slots.
- (void)setUpCompanions {
  self.companionSlot =
      [[IMACompanionAdSlot alloc] initWithView:self.companionView
                                         width:self.companionView.frame.size.width
                                        height:self.companionView.frame.size.height];
}

// Create AdsRenderingSettings.
- (void)createAdsRenderingSettings {
  self.adsRenderingSettings = [[IMAAdsRenderingSettings alloc] init];
  self.adsRenderingSettings.webOpenerPresentingController = self;
}

// Create playhead for content tracking.
- (void)createContentPlayhead {
  self.contentPlayhead = [[IMAAVPlayerContentPlayhead alloc] initWithAVPlayer:self.contentPlayer];
}

// Initialize AdsLoader.
- (void)setUpAdsLoader {
  if (self.adsManager) {
    [self.adsManager destroy];
  }
  if (self.adsLoader) {
    self.adsLoader = nil;
  }
  IMASettings *settings = [[IMASettings alloc] init];
  settings.language = self.video.language;
  self.adsLoader = [[IMAAdsLoader alloc] initWithSettings:settings];
  self.adsLoader.delegate = self;
  if (self.companionView != nil) {
    [self setUpCompanions];
  }
}

// Request ads for provided tag.
- (void)requestAdsWithTag:(NSString *)adTagUrl {
  [self logMessage:@"Requesting ads"];
  [self setUpAdDisplayContainer];
  // Create an ad request with our ad tag, display container, and optional user context.
  IMAAdsRequest *request = [[IMAAdsRequest alloc] initWithAdTagUrl:adTagUrl
                                                adDisplayContainer:self.adDisplayContainer
                                                       userContext:nil];
  [self.adsLoader requestAdsWithRequest:request];
}

// Notify IMA SDK when content is done for post-rolls.
- (void)contentDidFinishPlaying {
  [self.adsLoader contentComplete];
}

#pragma mark AdsLoader Delegates

- (void)adsLoader:(IMAAdsLoader *)loader adsLoadedWithData:(IMAAdsLoadedData *)adsLoadedData {
  // Grab the instance of the IMAAdsManager and set ourselves as the delegate.
  self.adsManager = adsLoadedData.adsManager;
  self.adsManager.delegate = self;
  // Create ads rendering settings to tell the SDK to use the in-app browser.
  [self createAdsRenderingSettings];
  // Create a content playhead so the SDK can track our content for VMAP and ad rules.
  [self createContentPlayhead];
  // Initialize the ads manager.
  [self.adsManager initializeWithContentPlayhead:self.contentPlayhead
                            adsRenderingSettings:self.adsRenderingSettings];
}

- (void)adsLoader:(IMAAdsLoader *)loader failedWithErrorData:(IMAAdLoadingErrorData *)adErrorData {
  // Something went wrong loading ads. Log the error and play the content.
  [self logMessage:@"Error loading ads: %@", adErrorData.adError.message];
  self.isAdPlayback = NO;
  [self setPlayButtonType:PauseButton];
  [self.contentPlayer play];
}

#pragma mark AdsManager Delegates

- (void)adsManager:(IMAAdsManager *)adsManager didReceiveAdEvent:(IMAAdEvent *)event {
  [self logMessage:@"AdsManager event (%s).", AdEventNames[event.type]];
  // When the SDK notified us that ads have been loaded, play them.
  switch (event.type) {
    case kIMAAdEvent_LOADED:
      [adsManager start];
      break;
    case kIMAAdEvent_PAUSE:
      [self setPlayButtonType:PlayButton];
      break;
    case kIMAAdEvent_RESUME:
      [self setPlayButtonType:PauseButton];
      break;
    case kIMAAdEvent_TAPPED:
      [self showFullscreenControls:nil];
      break;
    default:
      break;
  }
}

- (void)adsManager:(IMAAdsManager *)adsManager didReceiveAdError:(IMAAdError *)error {
  // Something went wrong with the ads manager after ads were loaded. Log the error and play the
  // content.
  [self logMessage:@"AdsManager error: %@", error.message];
  self.isAdPlayback = NO;
  [self setPlayButtonType:PauseButton];
  [self.contentPlayer play];
}

- (void)adsManagerDidRequestContentPause:(IMAAdsManager *)adsManager {
  // The SDK is going to play ads, so pause the content.
  self.isAdPlayback = YES;
  [self setPlayButtonType:PauseButton];
  [self.contentPlayer pause];
}

- (void)adsManagerDidRequestContentResume:(IMAAdsManager *)adsManager {
  // The SDK is done playing ads (at least for now), so resume the content.
  self.isAdPlayback = NO;
  [self setPlayButtonType:PauseButton];
  [self.contentPlayer play];
}

#pragma mark Utility methods

- (void)logMessage:(NSString *)log, ... {
  va_list args;
  va_start(args, log);
  NSString *s =
      [[NSString alloc] initWithFormat:[NSString stringWithFormat:@"%@\n", log] arguments:args];
  self.consoleView.text = [self.consoleView.text stringByAppendingString:s];
  NSLog(@"%@", s);
  va_end(args);
  if (self.consoleView.text.length > 0) {
    NSRange bottom = NSMakeRange(self.consoleView.text.length - 1, 1);
    [self.consoleView scrollRangeToVisible:bottom];
  }
}

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

@end


text:
package schedule.mock.fragments.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;

import schedule.mock.R;

public class OKDialogFragment extends BaseDialogFragment {
	private static final String EXTRAS_TITLE = "extras.title";
	private static final String EXTRAS_CONTENT = "extras.content";

	public static void showInstance(FragmentActivity _context, String _title, String _content) {
		Bundle args = new Bundle();
		args.putString(EXTRAS_TITLE, _title);
		args.putString(EXTRAS_CONTENT, _content);
		DialogFragment fragment = (DialogFragment) instantiate(_context, OKDialogFragment.class.getName(), args);
		show(_context, fragment, null);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setCancelable(true);
	}

	@Override
	public Dialog onCreateDialog(Bundle _savedInstanceState) {
		Bundle args = getArguments();
		String title = args.getString(EXTRAS_TITLE);
		String content = args.getString(EXTRAS_CONTENT);

		return new AlertDialog.Builder(getActivity()).setTitle(title).setMessage(content)
				.setPositiveButton(R.string.general_ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						onOk();
					}
				}).create();
	}

	public void onOk() {
		dismiss();
	}

}


text:
package com.google.api.ads.dfp.jaxws.v201405;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             This represents an entry in a map with a key of type ConversionEvent
 *             and value of type TrackingUrls.
 *
 *
 *
Java class for ConversionEvent_TrackingUrlsMapEntry complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ConversionEvent_TrackingUrlsMapEntry">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="key" type="{https://www.google.com/apis/ads/publisher/v201405}ConversionEvent" minOccurs="0"/>
 *         <element name="value" type="{https://www.google.com/apis/ads/publisher/v201405}TrackingUrls" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ConversionEvent_TrackingUrlsMapEntry", propOrder = {
    "key",
    "value"
})
public class ConversionEventTrackingUrlsMapEntry {

    protected ConversionEvent key;
    protected TrackingUrls value;

    /**
     * Gets the value of the key property.
     *
     * @return
     *     possible object is
     *     {@link ConversionEvent }
     *
     */
    public ConversionEvent getKey() {
        return key;
    }

    /**
     * Sets the value of the key property.
     *
     * @param value
     *     allowed object is
     *     {@link ConversionEvent }
     *
     */
    public void setKey(ConversionEvent value) {
        this.key = value;
    }

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link TrackingUrls }
     *
     */
    public TrackingUrls getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link TrackingUrls }
     *
     */
    public void setValue(TrackingUrls value) {
        this.value = value;
    }

}


text:
package org.trianacode.taskgraph.service;

import org.trianacode.enactment.logging.stampede.StampedeLog;
import org.trianacode.taskgraph.*;
import org.trianacode.taskgraph.clipin.HistoryClipIn;

import java.util.HashMap;
import java.util.UUID;

/**
 * The scheduler is responsible for waking-up all the input tasks in a taskgraph when the taskgraph is run.
 *
 * @author Ian Wang
 * @version $Revision: 4048 $
 */
public class Scheduler implements SchedulerInterface {

    private ExecutionState tgState = ExecutionState.RESET;

    /**
     * The taskgraph which this scheduler runs.
     */
    private TaskGraph taskgraph;

    /**
     * The history clipin
     */
    private HistoryClipIn history;

//    private UUID runUUID;
//    private UUID parentUUID = null;

    //    public RuntimeFileLog runtimeFileLog;
//    private HashMap<Task, Integer> taskMap; // = new HashMap<Task, Integer>();
//    private HashMap<Task, Integer> stateChanges;
    public StampedeLog stampedeLog;
    private HashMap<String, String> executionProperties;
//    private int sched_id_count;
//    private ExecutionListener executionLogger = new ExecutionLogger(stampedeLog);
//    private long startTime;

    //    private ExecutionStateLogger logger = new ExecutionStateLogger();

    /**
     * Construct a scheduler for the given taskgraph and registers it with all the tasks in the taskgraph
     *
     * @param taskgraph
     */
    public Scheduler(TaskGraph taskgraph) {
        this.taskgraph = taskgraph;
    }

    /**
     * @return the taskgraph state
     */
    public ExecutionState getExecutionState() {
        return tgState;
    }

    /**
     * Runs the main taskgraph
     */
    public void runTaskGraph() throws SchedulerException {
        runTaskGraph((HistoryClipIn) null);
    }

    /**
     * Runs the taskgraph by waking up all the input tasks. Attaches the specified object as a history clip-in
     */
    public void runTaskGraph(HistoryClipIn history) throws SchedulerException {
        this.history = history;

        if (tgState == ExecutionState.ERROR) {
            throw (new SchedulerException("Run Error: Taskgraph is in an error state (try reseting)"));
        } else if (isSuspendedTasks(taskgraph)) {
            throw (new SchedulerException("Run Error: Taskgraph contains suspended tasks"));
        } else if (tgState == ExecutionState.PAUSED) {
            resumeTaskGraph(taskgraph);
        } else {
            runTaskGraph(taskgraph);
        }
    }

    /**
     * Pauses the taskgraph
     */
    public void pauseTaskGraph() {
        pauseTaskGraph(taskgraph);
    }

    /**
     * Continue after a pause.
     */
    public void resumeTaskGraph() {
        resumeTaskGraph(taskgraph);
    }

    /**
     * Halt the taskgraph and reset all units to their start values.
     */
    public void resetTaskGraph() {
        resetTaskGraph(taskgraph);
    }

    /**
     * Flushes all data from the task graph cables
     */
    public void flushTaskGraph() {
        pauseTaskGraph();

        Cable[] cables = TaskGraphUtils.getConnectedCables(TaskGraphUtils.getAllTasksRecursive(taskgraph, true));

        for (int i = 0; i < cables.length; i++) {
            if (cables[i] instanceof InputCable) {
                ((InputCable) cables[i]).suspend();
            } else if (cables[i] instanceof OutputCable) {
                ((OutputCable) cables[i]).suspend();
            }
        }

        // todo flush the units

        for (int i = 0; i < cables.length; i++) {
            if (cables[i] instanceof InputCable) {
                ((InputCable) cables[i]).resume();
            } else if (cables[i] instanceof OutputCable) {
                ((OutputCable) cables[i]).resume();
            }
        }
    }

    /**
     * Runs the specified task (within a running taskgraph)
     */
    public void runTask(Task task) throws SchedulerException {
        if (tgState == ExecutionState.RUNNING) {
            wakeTask(task);
        } else {
            throw (new SchedulerException("Cannot run task " + task.getToolName() + ": Execution state = " + tgState));
        }
    }

    /**
     * @return true if any tasks within the taskgraph are suspended
     */
    private boolean isSuspendedTasks(TaskGraph taskgraph) {
        Task[] tasks = TaskGraphUtils.getAllTasksRecursive(taskgraph, true);
        boolean suspended = false;

        for (int count = 0; (count < tasks.length) && (!suspended); count++) {
            if ((tasks[count] instanceof RunnableInstance)) {
                suspended = suspended || (((RunnableInstance) tasks[count]).getExecutionState()
                        == ExecutionState.SUSPENDED);
            }
        }

        return suspended;
    }

    /**
     * Called to notify an error has occured in the taskgraph
     *
     * @param cause the cause of the error
     */
    public void notifyError(RunnableInstance cause, String message) {
        stopTaskGraph(taskgraph);
        if (stampedeLog.isSubWorkflow()) {
            try {
                Thread.sleep(3000);
                stampedeLog.complete();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void addExecutionListener(ExecutionListener listener) {
        taskgraph.addExecutionListener(listener);
    }

    @Override
    public void removeExecutionListener(ExecutionListener listener) {
        taskgraph.removeExecutionListener(listener);
    }

//    @Override
//    public void setParentUUID(UUID uuid) {
//        this.parentUUID = uuid;
//    }
//
//    public UUID getRunUUID() {
//        return runUUID;
//    }

    @Override
    public void setExecutionProperties(HashMap<String, String> executionProperties) {
        this.executionProperties = executionProperties;
    }

    /**
     * Attaches history to input tasks
     */
    private void attachHistoryClipIn(Task task) {
        if ((history != null) && (task.getDataInputNodeCount() == 0)) {
            if (task instanceof ClipableTaskInterface) {
                ((ClipableTaskInterface) task).queueClipIn(HistoryClipIn.HISTORY_CLIPIN_NAME, history.clone());
            } else {
                throw (new RuntimeException("Scheduler Error: Cannot attach history clip-in to " + task.getToolName()));
            }
        }
    }

    /**
     * Send all tasks in the task graph a wake up call (except the control task)
     */
    private void runTaskGraph(TaskGraph tgraph) {

//        startTime = new Date().getTime() / 1000;
//        runUUID = UUID.randomUUID();
//        if(parentUUID == null){
//            parentUUID = runUUID;
//        }

        //A new unique identifier for this specific execution
        UUID runUUID = UUID.randomUUID();

        //if there is no stampede logger yet, add one. Otherwise change the current one to this uuid
        if (stampedeLog == null) {
            stampedeLog = new StampedeLog(taskgraph, runUUID);
        } else {
            stampedeLog.reset(runUUID);
//            stampedeLog.setRunUUID(runUUID);
        }

        if (executionProperties != null) {
            stampedeLog.initExecutionProperties(executionProperties);
        }

        stampedeLog.logPlanEvent(taskgraph);
        //if there is no parent ID, then this taskgraph is a root graph, and so should be planned/ mapped.
        //otherwise, assume the parent taskgraph has already been planned/ mapped.
//        if (parentUUID != null) {
//            stampedeLog.logSubWf(parentUUID, runUUID, jobID, jobInstID);
//        }

//        stampedeLog.reset();

//        runtimeFileLog = new RuntimeFileLog(
//                tgraph.getProperties().getProperty(TrianaProperties.LOG_LOCATION), runUUID);
//        taskMap = new HashMap<Task, Integer>();
//        stateChanges = new HashMap<Task, Integer>();
//        sched_id_count = 0;

//        StampedeEvent planEvent = new StampedeEvent(LogDetail.PLAN)
//                .add(LogDetail.ROOT_WF, parentUUID.toString())
//                .add(LogDetail.PLANNER_VERSION, (String) tgraph.getParameter(TrianaProperties.VERSION))
//                .add(LogDetail.SUBMIT_DIR, System.getProperty("user.dir"))
//                .add(LogDetail.USERNAME, System.getProperty("user.name"))
//                .add(LogDetail.EXECUTION_FILE_NAME, "exec:" + tgraph.getToolName())
//                .add(LogDetail.SUBMIT_HOSTNAME, getHostname())
//                .add(LogDetail.WF_VERSION, "1")
//                .add(LogDetail.DESCRIPTION_FILE, tgraph.getToolName())
//                .add(LogDetail.ARGS, "\"\"");
//        addBaseEventDetails(planEvent);
//        logStampedeEvent(planEvent);

//        logGraph(tgraph);

        if ((tgState != ExecutionState.ERROR) && (tgState != ExecutionState.RESETTING)) {
            tgState = ExecutionState.RUNNING;

//            stampedeLog.recordSchedForRootTaskGraph(tgraph);

            wakeTask(tgraph);

            stampedeLog.logInvocationStart(tgraph);
            stampedeLog.logJobInstStart(tgraph);
        }
    }

    /**
     * Pauses all tasks
     */
    private void pauseTaskGraph(TaskGraph tgraph) {
        if (tgState.equals(ExecutionState.RUNNING)) {
            tgState = ExecutionState.PAUSED;
            Task[] tasks = TaskGraphUtils.getAllTasksRecursive(tgraph, true);

            for (int count = 0; count < tasks.length; count++) {
                if ((tasks[count] instanceof RunnableInstance)) {
                    ((RunnableInstance) tasks[count]).pause();
                }
            }
        }
    }

    /**
     * Sends a wake-up call to all tasks except tasks with zero input nodes (and tasks that are running continuously).
     * This resumes paused tasks
     */
    private void resumeTaskGraph(TaskGraph tgraph) {
        if (tgState.equals(ExecutionState.PAUSED)) {
            tgState = ExecutionState.RUNNING;
            Task[] tasks = TaskGraphUtils.getAllTasksRecursive(tgraph, true);

            for (int count = 0; count < tasks.length; count++) {
                if (tasks[count] instanceof RunnableInstance) {
                    ((RunnableInstance) tasks[count]).resume();
                }
            }
        }
    }

    /**
     * Reset all tasks and flushes the taskgraph
     */
    private void resetTaskGraph(final TaskGraph tgraph) {
        if (tgState != ExecutionState.RESETTING) {
            tgState = ExecutionState.RESETTING;

            Runnable runnable = new Runnable() {
                public void run() {
                    Task[] tasks = TaskGraphUtils.getAllTasksRecursive(tgraph, true);
                    Cable[] cables = TaskGraphUtils
                            .getConnectedCables(TaskGraphUtils.getAllTasksRecursive(taskgraph, true));

                    for (int i = 0; i < cables.length; i++) {
                        if (cables[i] instanceof OutputCable) {
                            ((OutputCable) cables[i]).suspend();
                        } else if (cables[i] instanceof InputCable) {
                            ((InputCable) cables[i]).suspend();
                        }
                    }

                    for (int count = 0; count < tasks.length; count++) {
                        if ((tasks[count] instanceof RunnableInstance)) {
                            ((RunnableInstance) tasks[count]).reset();
                        }
                    }

                    for (int i = 0; i < cables.length; i++) {
                        if (cables[i] instanceof OutputCable) {
                            ((OutputCable) cables[i]).flush();
                        } else if (cables[i] instanceof InputCable) {
                            ((InputCable) cables[i]).flush();
                        }
                    }

                    boolean reset;

                    do {
                        reset = true;

                        for (int count = 0; count < tasks.length; count++) {
                            if ((tasks[count].getExecutionState() != ExecutionState.RESET) &&
                                    (tasks[count].getExecutionState() != ExecutionState.NOT_EXECUTABLE) &&
                                    (tasks[count].getExecutionState() != ExecutionState.UNKNOWN)) {
                                reset = false;
                            }
                        }

                        if (!reset) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException except) {
                            }
                        }
                    } while (!reset);

                    for (int i = 0; i < cables.length; i++) {
                        if (cables[i] instanceof OutputCable) {
                            ((OutputCable) cables[i]).resume();
                        } else if (cables[i] instanceof InputCable) {
                            ((InputCable) cables[i]).resume();
                        }
                    }
                    tgState = ExecutionState.RESET;
                }
            };

            tgraph.getProperties().getEngine().execute(runnable);
        }
    }

    /**
     * Stops all tasks for an error
     */
    private void stopTaskGraph(TaskGraph tgraph) {

        tgState = ExecutionState.ERROR;
        Task[] tasks = TaskGraphUtils.getAllTasksRecursive(tgraph, true);

        for (int count = 0; count < tasks.length; count++) {
            if ((tasks[count] instanceof RunnableInstance)) {
                ((RunnableInstance) tasks[count]).pause();
            }
        }

    }

    /**
     * Wakes up the specfied task within a running taskgraph
     */
    public void wakeTask(Task task) {

//        sched_id_count++;
//        stampedeLog.taskMap.put(task, sched_id_count);
        stampedeLog.wakeTask(task);
//        StampedeEvent wakeStartEvent = new StampedeEvent(LogDetail.START_WAKING_TASK);
//        addSchedJobInstDetails(wakeStartEvent, task);
//        logStampedeEvent(wakeStartEvent);

        if (tgState == ExecutionState.RUNNING) {
            if (task instanceof RunnableInstance) {
                attachHistoryClipIn(task);
                ((RunnableInstance) task).wakeUp();

            } else if (task instanceof TaskGraph) {
                TaskGraph tgraph = ((TaskGraph) task);
                tgraph.addExecutionListener(stampedeLog.getExecutionLogger());

                if (tgraph.isControlTask() && tgraph.isControlTaskConnected()) {
                    wakeTask(tgraph.getControlTask());
                } else {
                    Task[] tasks = tgraph.getTasks(false);

                    for (int count = 0; count < tasks.length; count++) {
                        wakeTask(tasks[count]);
                    }
                }
            }
        }

    }

//    private void logGraph(TaskGraph taskgraph) {
//        //Task INFO
//
//        logStampedeEvent(addBaseEventDetails(new StampedeEvent(LogDetail.TASK_INFO)
//                .add(LogDetail.TYPE_DESC, "compute")
//                .add(LogDetail.TASK_ID, "task:" + taskgraph.getQualifiedTaskName())
//                .add(LogDetail.ARGS, "\"\""))
//                .add(LogDetail.TYPE, "1")
//                .add(LogDetail.TRANSFORMATION, taskgraph.getQualifiedToolName())
//        );
//
//        for (Task task : TaskGraphUtils.getAllTasksRecursive(taskgraph, false)) {
//
//            logStampedeEvent(addBaseEventDetails(new StampedeEvent(LogDetail.TASK_INFO)
//                    .add(LogDetail.TYPE_DESC, "compute")
//                    .add(LogDetail.TASK_ID, "task:" + task.getQualifiedTaskName())
//                    .add(LogDetail.ARGS, getTaskArgs(task))
//                    .add(LogDetail.TYPE, "1")
//                    .add(LogDetail.TRANSFORMATION, task.getQualifiedToolName()))
//            );
//        }
//
//        for (Cable cable : TaskGraphUtils.getConnectedCables(TaskGraphUtils.getAllTasksRecursive(taskgraph, false))) {
//            logStampedeEvent(addBaseEventDetails(new StampedeEvent(LogDetail.TASK_CABLES)
//                    .add(LogDetail.CHILD_TASK, cable.getReceivingTask().getQualifiedTaskName())
//                    .add(LogDetail.PARENT_TASK, cable.getSendingTask().getQualifiedTaskName()))
//            );
//        }
//
//        //"Job" (Unit) Info
//
//        logStampedeEvent(addBaseEventDetails(
//                new StampedeEvent(LogDetail.UNIT_INFO)
//                        .add(LogDetail.UNIT_ID, "unit:" + taskgraph.getQualifiedToolName())
//                        .add(LogDetail.SUBMIT_FILE, "null")
//                        .add(LogDetail.TYPE, "1")
//                        .add(LogDetail.TYPE_DESC, "compute")
//                        .add(LogDetail.CLUSTERED, "0")
//                        .add(LogDetail.MAX_RETRIES, "1")
//                        .add(LogDetail.TASK_COUNT, "1")
//                        .add(LogDetail.ARGS, "\"\""))
//                .add(LogDetail.EXECUTABLE, taskgraph.getQualifiedToolName())
//        );
//        for (Task task : TaskGraphUtils.getAllTasksRecursive(taskgraph, false)) {
//
//            logStampedeEvent(addBaseEventDetails(
//                    new StampedeEvent(LogDetail.UNIT_INFO)
//                            .add(LogDetail.UNIT_ID, "unit:" + task.getQualifiedToolName())
//                            .add(LogDetail.SUBMIT_FILE, "null")
//                            .add(LogDetail.TYPE, "1")
//                            .add(LogDetail.TYPE_DESC, "compute")
//                            .add(LogDetail.CLUSTERED, "0")
//                            .add(LogDetail.MAX_RETRIES, "1")
//                            .add(LogDetail.TASK_COUNT, "1")
//                            .add(LogDetail.ARGS, getTaskArgs(task))
//                            .add(LogDetail.EXECUTABLE, task.getQualifiedToolName()))
//            );
//        }
//
//        //Map tasks to jobs 1->1
//
//        logStampedeEvent(addBaseEventDetails(new StampedeEvent(LogDetail.MAP_TASK_UNIT)
//                .add(LogDetail.TASK_ID, "task:" + taskgraph.getQualifiedTaskName())
//                .add(LogDetail.UNIT_ID, "unit:" + taskgraph.getQualifiedToolName())
//        ));
//        for (Task task : TaskGraphUtils.getAllTasksRecursive(taskgraph, false)) {
//            logStampedeEvent(addBaseEventDetails(new StampedeEvent(LogDetail.MAP_TASK_UNIT)
//                    .add(LogDetail.TASK_ID, "task:" + task.getQualifiedTaskName())
//                    .add(LogDetail.UNIT_ID, "unit:" + task.getQualifiedToolName())
//            ));
//        }
//
//        for (Cable cable : TaskGraphUtils.getConnectedCables(TaskGraphUtils.getAllTasksRecursive(taskgraph, false))) {
//            logStampedeEvent(addBaseEventDetails(new StampedeEvent(LogDetail.UNIT_CABLES)
//                    .add(LogDetail.CHILD_UNIT, cable.getReceivingTask().getQualifiedTaskName())
//                    .add(LogDetail.PARENT_UNIT, cable.getSendingTask().getQualifiedTaskName())
//            ));
//        }
//    }

//    public void logStampedeEvent(StampedeEvent stampedeEvent) {
//        if (stampedeEvent != null) {
//            if (LoggingUtils.loggingToRabbitMQ(taskgraph.getProperties())) {
//                Loggers.STAMPEDE_LOGGER.info(stampedeEvent);
//            }
//            runtimeFileLog.info(stampedeEvent);
//        }
//    }

//    public StampedeEvent addBaseJobInstDetails(StampedeEvent stampedeEvent, Task task) {
//        Integer changes = stateChanges.get(task);
//        if (changes == null) {
//            changes = 0;
//        } else {
//            changes++;
//        }
//        stateChanges.put(task, changes);
//        addBaseEventDetails(stampedeEvent)
//                .add(LogDetail.UNIT_INST_ID, String.valueOf(getTaskNumber(task)))
//                .add(LogDetail.UNIT_STATE_ID, String.valueOf(changes))
//                .add(LogDetail.UNIT_ID, "unit:" + task.getQualifiedToolName());
//
//        return stampedeEvent;
//    }
//
//    public StampedeEvent addBaseEventDetails(StampedeEvent stampedeEvent) {
//        stampedeEvent.add(LogDetail.LEVEL, LogDetail.LEVELS.INFO)
//                .add(LogDetail.UUID, runUUID.toString());
//        return stampedeEvent;
//    }
//
//    public StampedeEvent addSchedJobInstDetails(StampedeEvent stampedeEvent, Task task) {
//        addBaseJobInstDetails(stampedeEvent, task);
//        stampedeEvent.add(LogDetail.SCHEDULER_ID, String.valueOf(taskMap.get(task)));
//        return stampedeEvent;
//    }

//    public Integer getTaskNumber(Task task) {
//        return taskMap.get(task);
//    }

//    private StampedeEvent execStateToJobState(ExecutionEvent event) {
//        ExecutionState executionState = event.getState();
//        StampedeEvent stampedeEvent;
//
////        System.out.println("Task " + event.getTask() +
////                " changed from " + event.getOldState() +
////                " to " + event.getState());
//
//        switch (executionState) {
//            //CONDOR JOB STATES
////            case NOT_INITIALIZED:
////                //PRE_SCRIPT_STARTED
////                return 0;
////
////            case NOT_EXECUTABLE:
////                //PRE_SCRIPT_FAILED
////                return 3;
//
//            case SCHEDULED:
//                //SUBMIT
//                stampedeEvent = new StampedeEvent(LogDetail.SCHEDULED);
//                addSchedJobInstDetails(stampedeEvent, event.getTask());
//                stampedeEvent.add(LogDetail.STATUS, "0");
//                return stampedeEvent;
//
//            case RUNNING:
//                //EXECUTE
//                if (event.getOldState() == ExecutionState.PAUSED) {
//                    stampedeEvent = new StampedeEvent(LogDetail.HELD_END);
//                    addSchedJobInstDetails(stampedeEvent, event.getTask());
//                    stampedeEvent.add(LogDetail.STATUS, "0");
//                    return stampedeEvent;
//                } else {
//                    stampedeEvent = new StampedeEvent(LogDetail.JOB_START);
//                    addSchedJobInstDetails(stampedeEvent, event.getTask())
//                            .add(LogDetail.STD_OUT_FILE, runtimeFileLog.getLogFilePath())
//                            .add(LogDetail.STD_ERR_FILE, runtimeFileLog.getLogFilePath());
//                    return stampedeEvent;
//                }
//
//            case PAUSED:
//                //JOB_HELD
//                stampedeEvent = new StampedeEvent(LogDetail.HELD_START);
//                addSchedJobInstDetails(stampedeEvent, event.getTask());
//                return stampedeEvent;
//
//            case COMPLETE:
//                //TERMINATED
//                stampedeEvent = new StampedeEvent(LogDetail.JOB_END);
//                addSchedJobInstDetails(stampedeEvent, event.getTask())
//                        .add(LogDetail.STD_OUT_FILE, runtimeFileLog.getLogFilePath())
//                        .add(LogDetail.STD_ERR_FILE, runtimeFileLog.getLogFilePath())
//                        .add(LogDetail.SITE, getHostname())
//                        .add(LogDetail.MULTIPLIER, "1")
//                        .add(LogDetail.STATUS, "0")
//                        .add(LogDetail.EXIT_CODE, "0");
//                return stampedeEvent;
//
////            case RESETTING:
////                //    UNKNOWN
////                return 9;
////
////            case RESET:
////                //
////                return 9;
////
//            case ERROR:
//                //JOB FAILURE
//                stampedeEvent = new StampedeEvent(LogDetail.JOB_END);
//                addSchedJobInstDetails(stampedeEvent, event.getTask())
//                        .add(LogDetail.STD_OUT_FILE, runtimeFileLog.getLogFilePath())
//                        .add(LogDetail.STD_ERR_FILE, runtimeFileLog.getLogFilePath())
//                        .add(LogDetail.SITE, getHostname())
//                        .add(LogDetail.MULTIPLIER, "1")
//                        .add(LogDetail.STATUS, "-1")
//                        .add(LogDetail.EXIT_CODE, "1");
//                return stampedeEvent;
//
//            case SUSPENDED:
//                //JOB HELD
//                stampedeEvent = new StampedeEvent(LogDetail.HELD_START);
//                addSchedJobInstDetails(stampedeEvent, event.getTask());
//                return stampedeEvent;
//
//            case UNKNOWN:
//                return null;
////
////            case LOCK:
////                return 9;
//        }
//        return null;
//    }
//
//    private String getHostname() {
//        String hostname;
//        try {
//            hostname = Inet4Address.getLocalHost().getHostName();
//        } catch (UnknownHostException e) {
//            hostname = "localhost";
//        }
//        return hostname;
//    }

//    private String getTaskArgs(Task task) {
//        StringBuilder stringBuilder = new StringBuilder();
//        stringBuilder.append("\"");
//        for (String param : task.getParameterNames()) {
//            stringBuilder.append(param)
//                    .append(":")
//                    .append(task.getParameter(param))
//                    .append(",");
//        }
//        stringBuilder.append("\"");
//        return stringBuilder.toString().replaceAll("[\n\r]", "");
//    }

//    private class ExecutionLogger implements ExecutionListener {
//
//        @Override
//        public void executionStateChanged(ExecutionEvent event) {
//            StampedeEvent stampedeEvent = execStateToJobState(event);
//            logStampedeEvent(stampedeEvent);
//        }
//
//        @Override
//        public void executionRequested(ExecutionEvent event) {
//            if (event.getTask() instanceof TaskGraph) {
//                StampedeEvent stampedeEvent = new StampedeEvent(LogDetail.SCHEDULED);
//                addSchedJobInstDetails(stampedeEvent, event.getTask());
//                stampedeEvent.add(LogDetail.STATUS, "0");
//                logStampedeEvent(stampedeEvent);
//            }
//        }
//
//        @Override
//        public void executionStarting(ExecutionEvent event) {
//            StampedeEvent runEvent = new StampedeEvent(LogDetail.RUNNING_WORKFLOW)
//                    .add(LogDetail.RESTART_COUNT, "0");
//            addBaseEventDetails(runEvent);
//            logStampedeEvent(runEvent);
//        }
//
//        @Override
//        public void executionFinished(ExecutionEvent event) {
//
////            System.out.println("event : "
////                    + event.getTask().getQualifiedTaskName() + " finished");
//
//            logStampedeEvent(addSchedJobInstDetails(new StampedeEvent(LogDetail.JOB_TERM)
//                    .add(LogDetail.STATUS, "0"),
//                    event.getTask())
//            );
//            StampedeEvent stampedeEvent = new StampedeEvent(LogDetail.JOB_END);
//            addSchedJobInstDetails(stampedeEvent, event.getTask())
//                    .add(LogDetail.STD_OUT_FILE, runtimeFileLog.getLogFilePath())
//                    .add(LogDetail.STD_ERR_FILE, runtimeFileLog.getLogFilePath())
//                    .add(LogDetail.SITE, getHostname())
//                    .add(LogDetail.MULTIPLIER, "1")
//                    .add(LogDetail.STATUS, "0")
//                    .add(LogDetail.EXIT_CODE, "0");
//            logStampedeEvent(stampedeEvent);
//
//            Task task = event.getTask();
//            if (task instanceof TaskGraph) {
//                long duration = (new Date().getTime() / 1000) - startTime;
//                if (duration == 0) {
//                    duration = 1;
//                }
//
//                StampedeEvent invEnd = new StampedeEvent(LogDetail.INVOCATION_END);
//                addBaseEventDetails(invEnd)
//                        .add(LogDetail.UNIT_INST_ID, String.valueOf(getTaskNumber(task)))
//                        .add(LogDetail.INVOCATION_ID, "1")
//                        .add(LogDetail.UNIT_ID, "unit:" + task.getQualifiedToolName())
//                        .add(LogDetail.START_TIME, String.valueOf(startTime))
//                        .add(LogDetail.DURATION, String.valueOf(duration))
//                        .add(LogDetail.TRANSFORMATION, task.getQualifiedTaskName())
//                        .add(LogDetail.EXECUTABLE, "Triana")
//                        .add(LogDetail.ARGS, getTaskArgs(task))
//                        .add(LogDetail.TASK_ID, task.getQualifiedTaskName())
//                        .add(LogDetail.EXIT_CODE, "0")
//                ;
//                logStampedeEvent(invEnd);
//            }
//        }
//
//        @Override
//        public void executionReset(ExecutionEvent event) {
////            System.out.println("Reset event " + event.getTask().getQualifiedTaskName()
////                    + " event " + event.getState());
//        }
//    }
}


text:
/*	cscope - interactive C symbol or text cross-reference
 *
 *	command functions
 */

#include "global.h"
#include "build.h"		/* for rebuild() */
#include "alloc.h"

#include <stdlib.h>
#if defined(USE_NCURSES) && !defined(RENAMED_NCURSES)
#include <ncurses.h>
#else
#include <curses.h>
#endif
#include <ctype.h>

static char const rcsid[] = "$Id: command.c,v 1.33 2009/04/10 13:39:23 broeker Exp $";

int	selecting;
unsigned int   curdispline = 0;

BOOL	caseless;		/* ignore letter case when searching */
BOOL	*change;		/* change this line */
BOOL	changing;		/* changing text */
char	newpat[PATLEN + 1];	/* new pattern */
/* HBB 20040430: renamed to avoid lots of clashes with function arguments
 * also named 'pattern' */
char	Pattern[PATLEN + 1];	/* symbol or text pattern */

/* HBB FIXME 20060419: these should almost certainly be const */
static	char	appendprompt[] = "Append to file: ";
static	char	pipeprompt[] = "Pipe to shell command: ";
static	char	readprompt[] = "Read from file: ";
static	char	toprompt[] = "To: ";

/* Internal prototypes: */
static	BOOL	changestring(void);
static	void	clearprompt(void);
static	void	mark(unsigned int i);
static	void	scrollbar(MOUSE *p);

/* execute the command */
BOOL
command(int commandc)
{
    char filename[PATHLEN + 1];	/* file path name */
    MOUSE *p;			/* mouse data */
    int	c, i;
    FILE *file;
    struct cmd *curritem, *item;	/* command history */
    char *s;

    switch (commandc) {
    case ctrl('C'):	/* toggle caseless mode */
	if (caseless == NO) {
	    caseless = YES;
	    postmsg2("Caseless mode is now ON");
	} else {
	    caseless = NO;
	    postmsg2("Caseless mode is now OFF");
	}
	egrepcaseless(caseless);	/* turn on/off -i flag */
	return(NO);

    case ctrl('R'):	/* rebuild the cross reference */
	if (isuptodate == YES) {
	    postmsg("The -d option prevents rebuilding the symbol database");
	    return(NO);
	}
	exitcurses();
	freefilelist();		/* remake the source file list */
	makefilelist();
	rebuild();
	if (errorsfound == YES) {
	    errorsfound = NO;
	    askforreturn();
	}
	entercurses();
	clearmsg();		/* clear any previous message */
	totallines = 0;
	disprefs = 0;
	topline = nextline = 1;
	selecting = 0;
	break;

#if UNIXPC
    case ESC:	/* possible unixpc mouse selection */
#endif
    case ctrl('X'):	/* mouse selection */
	if ((p = getmouseaction(DUMMYCHAR)) == NULL) {
	    return(NO);	/* unknown control sequence */
	}
	/* if the button number is a scrollbar tag */
	if (p->button == '0') {
	    scrollbar(p);
	    break;
	}
	/* ignore a sweep */
	if (p->x2 >= 0) {
	    return(NO);
	}
	/* if this is a line selection */
	if (p->y1 < FLDLINE) {

	    /* find the selected line */
	    /* note: the selection is forced into range */
	    for (i = disprefs - 1; i > 0; --i) {
		if (p->y1 >= displine[i]) {
		    break;
		}
	    }
	    /* display it in the file with the editor */
	    editref(i);
	} else {	/* this is an input field selection */
	    field = p->y1 - FLDLINE;
	    /* force it into range */
	    if (field >= FIELDS) {
		field = FIELDS - 1;
	    }
	    setfield();
	    resetcmd();
	    return(NO);
	}
	break;

    case '\t':	/* go to next input field */
	if (disprefs) {
	    selecting = !selecting;
	    if (selecting) {
		move(displine[curdispline], 0);
		refresh();
	    } else {
		atfield();
		resetcmd();
	    }
	}
	return(NO);

#ifdef KEY_ENTER
    case KEY_ENTER:
#endif
    case '\r':
    case '\n':	/* go to reference */
	if (selecting) {
	    editref(curdispline);
	    return(YES);
	}
	/* FALLTHROUGH */

    case ctrl('N'):
#ifdef KEY_DOWN
    case KEY_DOWN:
#endif
#ifdef KEY_RIGHT
    case KEY_RIGHT:
#endif
	if (selecting) {
	    if ((curdispline + 1) < disprefs) {
		move(displine[++curdispline], 0);
		refresh();
	    }
	} else {
	    field = (field + 1) % FIELDS;
	    setfield();
	    atfield();
	    resetcmd();
	}
	return(NO);

    case ctrl('P'):	/* go to previous input field */
#ifdef KEY_UP
    case KEY_UP:
#endif
#ifdef KEY_LEFT
    case KEY_LEFT:
#endif
	if (selecting) {
	    if (curdispline) {
		move(displine[--curdispline], 0);
		refresh();
	    }
	} else {
	    field = (field + (FIELDS - 1)) % FIELDS;
	    setfield();
	    atfield();
	    resetcmd();
	}
	return(NO);
#ifdef KEY_HOME
    case KEY_HOME:	/* go to first input field */
	if (selecting) {
	    curdispline = 0;
	    move(REFLINE, 0);
	    refresh();
	} else {
	    field = 0;
	    setfield();
	    atfield();
	    resetcmd();
	}
	return(NO);
#endif

#ifdef KEY_LL
    case KEY_LL:	/* go to last input field */
	if (selecting) {
	    move(displine[disprefs - 1], 0);
	    refresh();
	} else {
	    field = FIELDS - 1;
	    setfield();
	    atfield();
	    resetcmd();
	}
	return(NO);
#endif /* def(KEY_LL) */

    case ' ':	/* display next page */
    case '+':
    case ctrl('V'):
#ifdef KEY_NPAGE
    case KEY_NPAGE:
#endif
	/* don't redisplay if there are no lines */
	if (totallines == 0) {
	    return(NO);
	}
	/* note: seekline() is not used to move to the next
	 * page because display() leaves the file pointer at
	 * the next page to optimize paging forward
	 */
	curdispline = 0;
	break;

    case ctrl('H'):
    case '-':	/* display previous page */
#ifdef KEY_PPAGE
    case KEY_PPAGE:
#endif
	/* don't redisplay if there are no lines */
	if (totallines == 0) {
	    return(NO);
	}

	curdispline = 0;

	/* if there are only two pages, just go to the other one */
	if (totallines <= 2 * mdisprefs) {
	    break;
	}
	/* if on first page but not at beginning, go to beginning */
	nextline -= mdisprefs;	/* already at next page */
	if (nextline > 1 && nextline <= mdisprefs) {
	    nextline = 1;
	} else {
	    nextline -= mdisprefs;
	    if (nextline < 1) {
		nextline = totallines - mdisprefs + 1;
		if (nextline < 1) {
		    nextline = 1;
		}
	    }
	}
	seekline(nextline);
	break;

    case '>':	/* write or append the lines to a file */
	if (totallines == 0) {
	    postmsg("There are no lines to write to a file");
	} else {	/* get the file name */
	    move(PRLINE, 0);
	    addstr("Write to file: ");
	    s = "w";
	    if ((c = mygetch()) == '>') {
		move(PRLINE, 0);
		addstr(appendprompt);
		c = '\0';
		s = "a";
	    }
	    if (c != '\r' &&
		mygetline("", newpat,
			  COLS - sizeof(appendprompt), c, NO) > 0
		) {
		shellpath(filename, sizeof(filename), newpat);
		if ((file = myfopen(filename, s)) == NULL) {
		    cannotopen(filename);
		} else {
		    seekline(1);
		    while ((c = getc(refsfound)) != EOF) {
			putc(c, file);
		    }
		    seekline(topline);
		    fclose(file);
		}
	    }
	    clearprompt();
	}
	return(NO);	/* return to the previous field */

    case '<':	/* read lines from a file */
	move(PRLINE, 0);
	addstr(readprompt);
	if (mygetline("", newpat, COLS - sizeof(readprompt),
		      '\0', NO) > 0) {
	    clearprompt();
	    shellpath(filename, sizeof(filename), newpat);
	    if (readrefs(filename) == NO) {
		postmsg2("Ignoring an empty file");
		return(NO);
	    }
	    return(YES);
	}
	clearprompt();
	return(NO);

    case '^':	/* pipe the lines through a shell command */
    case '|':	/* pipe the lines to a shell command */
	if (totallines == 0) {
	    postmsg("There are no lines to pipe to a shell command");
	    return(NO);
	}
	/* get the shell command */
	move(PRLINE, 0);
	addstr(pipeprompt);
	if (mygetline("", newpat, COLS - sizeof(pipeprompt), '\0', NO)
	    == 0) {
	    clearprompt();
	    return(NO);
	}
	/* if the ^ command, redirect output to a temp file */
	if (commandc == '^') {
	    strcat(strcat(newpat, " >"), temp2);
	    /* HBB 20020708: somebody might have even
	     * their non-interactive default shells
	     * complain about clobbering
	     * redirections... --> delete before
	     * overwriting */
	    remove(temp2);
	}
	exitcurses();
	if ((file = mypopen(newpat, "w")) == NULL) {
	    fprintf(stderr, "\
cscope: cannot open pipe to shell command: %s\n", newpat);
	} else {
	    seekline(1);
	    while ((c = getc(refsfound)) != EOF) {
		putc(c, file);
	    }
	    seekline(topline);
	    mypclose(file);
	}
	if (commandc == '^') {
	    if (readrefs(temp2) == NO) {
		postmsg("Ignoring empty output of ^ command");
	    }
	}
	askforreturn();
	entercurses();
	break;
#if defined(KEY_RESIZE) && !defined(__DJGPP__)
    case KEY_RESIZE:
	exitcurses();
	initscr();
	entercurses();
#if TERMINFO
	keypad(stdscr, TRUE);	/* enable the keypad */
#ifdef HAVE_FIXKEYPAD
	fixkeypad();	/* fix for getch() intermittently returning garbage */
#endif
#endif
#if UNIXPC
	standend();	/* turn off reverse video */
#endif
	dispinit();	/* initialize display parameters */
	setfield();	/* set the initial cursor position */
	postmsg("");	/* clear any build progress message */
	display();	/* display the version number and input fields */
	break;
#endif
    case ctrl('L'):	/* redraw screen */
#ifdef KEY_CLEAR
    case KEY_CLEAR:
#endif
	clearmsg2();
	clearok(curscr, TRUE);
	wrefresh(curscr);
	drawscrollbar(topline, bottomline);
	return(NO);

    case '!':	/* shell escape */
	execute(shell, shell, NULL);
	seekline(topline);
	break;

    case '?':	/* help */
	clear();
	help();
	clear();
	seekline(topline);
	break;

    case ctrl('E'):	/* edit all lines */
	editall();
	break;

    case ctrl('A'):		/* HBB 20050428: added alt. keymapping */
    case ctrl('Y'):	/* repeat last pattern */
	if (*Pattern != '\0') {
	    addstr(Pattern);
	    goto repeat;
	}
	break;

    case ctrl('B'):		/* cmd history back */
    case ctrl('F'):		/* cmd history fwd */
	if (selecting)
	    return(NO);

	curritem = currentcmd();
	item = (commandc == ctrl('F')) ? nextcmd() : prevcmd();
	clearmsg2();
	if (curritem == item) {	/* inform user that we're at history end */
	    postmsg2("End of input field and search pattern history");
	}
	if (item) {
	    field = item->field;
	    setfield();
	    atfield();
	    addstr(item->text);
	    strcpy(Pattern, item->text);
	    switch (c = mygetch()) {
	    case '\r':
	    case '\n':
		goto repeat;
	    case ctrl('F'):
	    case ctrl('B'):
		myungetch(c);
		atfield();
		clrtoeol();	/* clear current field */
		break;
	    default:
		myungetch(c);
		if (mygetline(Pattern, newpat, COLS - fldcolumn - 1, '\0', caseless )) {
		    strcpy (Pattern, newpat);
		    resetcmd();
		}
		goto repeat;
		break;
	    }
	}
	return(NO);

    case '\\':	/* next character is not a command */
	addch('\\');	/* display the quote character */

	/* get a character from the terminal */
	if ((commandc = mygetch()) == EOF) {
	    return(NO);	/* quit */
	}
	addstr("\b \b");	/* erase the quote character */
	goto ispat;

    case '.':
	postmsg("The . command has been replaced by ^Y");
	atfield();	/* move back to the input field */
	/* FALLTHROUGH */
    default:
	if (selecting && !mouse) {
	    char		*c;

	    if ((c = strchr(dispchars, commandc)))
		editref(c - dispchars);

	    /* if this is the start of a pattern */
	} else if (isprint(commandc)) {
	ispat:
	    if (mygetline("", newpat, COLS - fldcolumn - 1,
			  commandc, caseless) > 0) {
		strcpy(Pattern, newpat);
		resetcmd();	/* reset command history */
	    repeat:
		addcmd(field, Pattern);	/* add to command history */
		if (field == CHANGE) {
		    /* prompt for the new text */
		    move(PRLINE, 0);
		    addstr(toprompt);
		    mygetline("", newpat,
			      COLS - sizeof(toprompt),
			      '\0', NO);
		}
		/* search for the pattern */
		if (search() == YES) {
		    curdispline = 0;
		    ++selecting;

		    switch (field) {
		    case DEFINITION:
		    case FILENAME:
			if (totallines > 1) {
			    break;
			}
			topline = 1;
			editref(0);
			break;
		    case CHANGE:
			return(changestring());
		    }

		} else if (field == FILENAME &&
			   access(newpat, READ) == 0) {
		    /* try to edit the file anyway */
		    edit(newpat, "1");
		}
	    } else {	/* no pattern--the input was erased */
		return(NO);
	    }
	} else {	/* control character */
	    return(NO);
	}
    } /* switch(commandc) */
    return(YES);
}

/* clear the prompt line */

static void
clearprompt(void)
{
	move(PRLINE, 0);
	clrtoeol();
}

/* read references from a file */

BOOL
readrefs(char *filename)
{
	FILE	*file;
	int	c;

	if ((file = myfopen(filename, "rb")) == NULL) {
		cannotopen(filename);
		return(NO);
	}
	if ((c = getc(file)) == EOF) {	/* if file is empty */
		return(NO);
	}
	totallines = 0;
	disprefs = 0;
	nextline = 1;
	if (writerefsfound() == YES) {
		putc(c, refsfound);
		while ((c = getc(file)) != EOF) {
			putc(c, refsfound);
		}
		fclose(file);
		fclose(refsfound);
		if ( (refsfound = myfopen(temp1, "rb")) == NULL) {
			cannotopen(temp1);
			return(NO);
		}
		countrefs();
	}
	return(YES);
}

/* change one text string to another */

static BOOL
changestring(void)
{
    char    newfile[PATHLEN + 1];   /* new file name */
    char    oldfile[PATHLEN + 1];   /* old file name */
    char    linenum[NUMLEN + 1];    /* file line number */
    char    msg[MSGLEN + 1];        /* message */
    FILE    *script;                /* shell script file */
    BOOL    anymarked = NO;         /* any line marked */
    MOUSE *p;                       /* mouse data */
    int     c;
    unsigned int i;
    char    *s;

    /* open the temporary file */
    if ((script = myfopen(temp2, "w")) == NULL) {
	cannotopen(temp2);
	return(NO);
    }
    /* create the line change indicators */
    change = mycalloc(totallines, sizeof(BOOL));
    changing = YES;
    mousemenu();

    /* until the quit command is entered */
    for (;;) {
	/* display the current page of lines */
	display();
    same:
	atchange();

	/* get a character from the terminal */
	if ((c = mygetch()) == EOF
	    || c == ctrl('D')
	    || c == ctrl('Z')) {
	    break;	/* change lines */
	}
	/* see if the input character is a command */
	switch (c) {
	case ' ':	/* display next page */
	case '+':
	case ctrl('V'):
#ifdef KEY_NPAGE
	case KEY_NPAGE:
#endif
	case '-':	/* display previous page */
#ifdef KEY_PPAGE
	case KEY_PPAGE:
#endif
	case '!':	/* shell escape */
	case '?':	/* help */
	    command(c);
	    break;

	case ctrl('L'):	/* redraw screen */
#ifdef KEY_CLEAR
	case KEY_CLEAR:
#endif
	    command(c);
	    goto same;

	case ESC:	/* don't change lines */
#if UNIXPC
	    if((p = getmouseaction(DUMMYCHAR)) == NULL) {
		goto nochange;	/* unknown escape sequence */
	    }
	    break;
#endif
	case ctrl('G'):
	    goto nochange;

	case '*':	/* mark/unmark all displayed lines */
	    for (i = 0; topline + i < nextline; ++i) {
		mark(i);
	    }
	    goto same;

	case ctrl('A'):	/* mark/unmark all lines */
	    for (i = 0; i < totallines; ++i) {
		if (change[i] == NO) {
		    change[i] = YES;
		} else {
		    change[i] = NO;
		}
	    }
	    /* show that all have been marked */
	    seekline(totallines);
	    break;

	case ctrl('X'):	/* mouse selection */
	    if ((p = getmouseaction(DUMMYCHAR)) == NULL) {
		goto same;	/* unknown control sequence */
	    }
	    /* if the button number is a scrollbar tag */
	    if (p->button == '0') {
		scrollbar(p);
		break;
	    }
	    /* find the selected line */
	    /* note: the selection is forced into range */
	    for (i = disprefs - 1; i > 0; --i) {
		if (p->y1 >= displine[i]) {
		    break;
		}
	    }
	    mark(i);
	    goto same;

	default:
	    {
		/* if a line was selected */
		char		*cc;

		if ((cc = strchr(dispchars, c)))
		    mark(cc - dispchars);

		goto same;
	    } /* default case */
	} /* switch(change code character) */
    } /* for(ever) */

    /* for each line containing the old text */
    fprintf(script, "ed - <<\\!\n");
    *oldfile = '\0';
    seekline(1);
    for (i = 0;
	 fscanf(refsfound, "%" PATHLEN_STR "s%*s%" NUMLEN_STR "s%*[^\n]", newfile, linenum) == 2;
	 ++i) {
	/* see if the line is to be changed */
	if (change[i] == YES) {
	    anymarked = YES;

	    /* if this is a new file */
	    if (strcmp(newfile, oldfile) != 0) {

		/* make sure it can be changed */
		if (access(newfile, WRITE) != 0) {
		    snprintf(msg, sizeof(msg), "Cannot write to file %s", newfile);
		    postmsg(msg);
		    anymarked = NO;
		    break;
		}
		/* if there was an old file */
		if (*oldfile != '\0') {
		    fprintf(script, "w\n");	/* save it */
		}
		/* edit the new file */
		strcpy(oldfile, newfile);
		fprintf(script, "e %s\n", oldfile);
	    }
	    /* output substitute command */
	    fprintf(script, "%ss/", linenum);	/* change */
	    for (s = Pattern; *s != '\0'; ++s) {
		/* old text */
		if (strchr("/\\[.^*", *s) != NULL) {
		    putc('\\', script);
		}
		if (caseless == YES && isalpha((unsigned char)*s)) {
		    putc('[', script);
		    if(islower((unsigned char)*s)) {
			putc(toupper((unsigned char)*s), script);
			putc(*s, script);
		    } else {
			putc(*s, script);
			putc(tolower((unsigned char)*s), script);
		    }
		    putc(']', script);
		} else
		    putc(*s, script);
	    }
	    putc('/', script);			/* to */
	    for (s = newpat; *s != '\0'; ++s) {	/* new text */
		if (strchr("/\\&", *s) != NULL) {
		    putc('\\', script);
		}
		putc(*s, script);
	    }
	    fprintf(script, "/gp\n");	/* and print */
	}
    }
    fprintf(script, "w\nq\n!\n");	/* write and quit */
    fclose(script);

    /* if any line was marked */
    if (anymarked == YES) {

	/* edit the files */
	clearprompt();
	refresh();
	fprintf(stderr, "Changed lines:\n\r");
	execute("sh", "sh", temp2, NULL);
	askforreturn();
	seekline(1);
    } else {
    nochange:
	clearprompt();
    }
    changing = NO;
    mousemenu();
    free(change);
    return(anymarked);
}

/* mark/unmark this displayed line to be changed */
static void
mark(unsigned int i)
{
    unsigned int j;

    j = i + topline - 1;
    if (j < totallines) {
	move(displine[i], 1);

	if (change[j] == NO) {
	    change[j] = YES;
	    addch('>');
	} else {
	    change[j] = NO;
	    addch(' ');
	}
    }
}

/* scrollbar actions */
static void
scrollbar(MOUSE *p)
{
    /* reposition list if it makes sense */
    if (totallines == 0) {
	return;
    }
    switch (p->percent) {

    case 101: /* scroll down one page */
	if (nextline + mdisprefs > totallines) {
	    nextline = totallines - mdisprefs + 1;
	}
	break;

    case 102: /* scroll up one page */
	nextline = topline - mdisprefs;
	if (nextline < 1) {
	    nextline = 1;
	}
	break;

    case 103: /* scroll down one line */
	nextline = topline + 1;
	break;

    case 104: /* scroll up one line */
	if (topline > 1) {
	    nextline = topline - 1;
	}
	break;
    default:
	nextline = p->percent * totallines / 100;
    }
    seekline(nextline);
}

/* count the references found */
void
countrefs(void)
{
    char    *subsystem;             /* OGS subsystem name */
    char    *book;                  /* OGS book name */
    char    file[PATHLEN + 1];      /* file name */
    char    function[PATLEN + 1];   /* function name */
    char    linenum[NUMLEN + 1];    /* line number */
    int     i;

    /* count the references found and find the length of the file,
       function, and line number display fields */
    subsystemlen = 9;	/* strlen("Subsystem") */
    booklen = 4;		/* strlen("Book") */
    filelen = 4;		/* strlen("File") */
    fcnlen = 8;		/* strlen("Function") */
    numlen = 0;
    while ((i = fscanf(refsfound, "%250s%250s%5s %5000[^\n]", file,
		       function, linenum, tempstring)) != EOF) {
	if (i != 4 ||
	    !isgraph((unsigned char) *file) ||
	    !isgraph((unsigned char) *function) ||
	    !isdigit((unsigned char) *linenum)) {
	    postmsg("File does not have expected format");
	    totallines = 0;
	    disprefs = 0;
	    return;
	}
	if ((i = strlen(pathcomponents(file, dispcomponents))) > filelen) {
	    filelen = i;
	}
	if (ogs == YES) {
	    ogsnames(file, &subsystem, &book);
	    if ((i = strlen(subsystem)) > subsystemlen) {
		subsystemlen = i;
	    }
	    if ((i = strlen(book)) > booklen) {
		booklen = i;
	    }
	}
	if ((i = strlen(function)) > fcnlen) {
	    fcnlen = i;
	}
	if ((i = strlen(linenum)) > numlen) {
	    numlen = i;
	}
	++totallines;
    }
    rewind(refsfound);

    /* restrict the width of displayed columns */
    /* HBB FIXME 20060419: magic number alert! */
    i = (COLS - 5) / 3;
    if (ogs == YES) {
	i = (COLS - 7) / 5;
    }
    if (filelen > i && i > 4) {
	filelen = i;
    }
    if (subsystemlen > i && i > 9) {
	subsystemlen = i;
    }
    if (booklen > i && i > 4) {
	booklen = i;
    }
    if (fcnlen > i && i > 8) {
	fcnlen = i;
    }
}


text:
require 'spec_helper'

describe NiftySettings::Settings do
  let(:nested_settings_hash) { { pelle: 'fant', shnoo: 'shnaa' } }
  let(:settings_hash)        { { foo: 'bar', nested: nested_settings_hash, really?: true, not_really?: false, nothing?: nil } }
  let(:settings)             { NiftySettings::Settings.new(settings_hash) }
  let(:empty_settings)       { NiftySettings::Settings.new }

  context 'comparing two settings' do
    it 'works as expected' do
      expect(NiftySettings::Settings.new(settings_hash)).to     be == NiftySettings::Settings.new(settings_hash)
      expect(NiftySettings::Settings.new(settings_hash)).to_not be == NiftySettings::Settings.new(nested_settings_hash)
      expect(NiftySettings::Settings.new(settings_hash)).to_not be == 'random string'
    end
  end

  context '#key' do
    context 'when no setting with that key exists' do
      it 'returns nil' do
        expect(settings.not_found).to be_nil
      end

      it 'does not change the settings' do
        expect { settings.not_found }.to_not change { settings.to_h }
      end
    end

    context 'when the settings has a single value' do
      it 'returns the value' do
        expect(settings.foo).to eq('bar')
      end
    end

    context 'when the setting has nested values' do
      it 'returns a settings object with the values' do
        expect(settings.nested).to eq(NiftySettings::Settings.new(nested_settings_hash))
      end
    end
  end

  describe '#to_s' do
    context 'when no settings are stored' do
      it 'returns an empty string' do
        expect(empty_settings.to_s).to eq('')
      end
    end

    context 'when settings are stored' do
      it 'returns a string representation of the settings' do
        expect(settings.to_s).to eq(settings_hash.to_s)
      end
    end
  end

  describe '#key?' do
    context 'when no setting with that key exists' do
      it 'returns false' do
        expect(settings.bar?).to eq(false)
      end
    end

    context 'when the settings has a single value' do
      it 'returns true' do
        expect(settings.foo?).to eq(true)
      end
    end

    context 'when the settings has key ending with ?' do
      it 'returns true' do
        expect(settings.really?).to eq(true)
      end

      it 'returns false' do
        expect(settings.not_really?).to eq(false)
      end

      it 'returns nil' do
        expect(settings.nothing?).to be_nil
      end
    end

    context 'when the setting has nested values' do
      it 'returns true' do
        expect(settings.nested?).to eq(true)
      end
    end
  end

  describe '.load' do
    context 'without Rails and RACK_ENV' do
      before do
        # Make sure `ENV['RACK_ENV']` is not set and Rails is not loaded
        # so that the loaded settings are not scoped to the env.
        ENV['RACK_ENV'] = nil
        raise 'Rails should not be loaded.' if defined?(Rails)

        FileUtils.mkdir_p settings_dir
      end

      after do
        Dir[File.join(settings_dir, '*.yml')].unshift(settings_file).each do |file|
          File.delete file if File.exist?(file)
        end
        %i(settings_file settings_dir).each do |config|
          NiftySettings.configuration.unset config
        end
      end

      let(:settings_file) { File.expand_path('../../../config/settings.yml', __FILE__) }
      let(:settings_dir)  { File.expand_path('../../../config/settings', __FILE__) }
      1.upto(3).each do |i|
        let(:"support_settings_file_#{i}") { File.expand_path("../../support/settings#{i}.yml", __FILE__) }
      end

      context 'when only the settings file exists' do
        context 'in the default location' do
          before do
            FileUtils.cp support_settings_file_1, settings_file
          end

          it 'loads the settings' do
            settings = NiftySettings::Settings.load
            expect(settings).to eq('foo' => 'bar')
          end
        end

        context 'in a custom location' do
          before do
            NiftySettings.configuration.settings_file = support_settings_file_1
          end

          it 'loads the settings' do
            settings = NiftySettings::Settings.load
            expect(settings).to eq('foo' => 'bar')
          end
        end
      end

      context 'when only a file in the settings dir exists' do
        before do
          FileUtils.cp support_settings_file_1, settings_dir
        end

        it 'loads the settings' do
          settings = NiftySettings::Settings.load
          expect(settings).to eq('foo' => 'bar')
        end
      end

      context 'when the settings file and files in the settings dir exist' do
        before do
          FileUtils.cp support_settings_file_1, settings_file
          FileUtils.cp support_settings_file_2, settings_dir
          FileUtils.cp support_settings_file_3, settings_dir
        end

        it 'loads the settings' do
          settings = NiftySettings::Settings.load
          expect(settings).to eq(
            'foo'   => 'bar',
            'pelle' => 'fant',
            'zing'  => 'zang'
          )
        end
      end
    end
  end
end


text:
package org.killbill.billing.plugin.ingenico.client.model.paymentinfo;

import org.killbill.billing.plugin.ingenico.client.model.PaymentInfo;

public class SepaDirectDebit extends PaymentInfo {

    public static Integer SEPA_PAYMENT_ID = 770;

    private String countryCode;
    private String iban;
    private String bic;
    private String sepaAccountHolder;

    public String getCountryCode() {
        return countryCode;
    }

    public void setCountryCode(final String countryCode) {
        this.countryCode = countryCode;
    }

    public String getIban() {
        return iban;
    }

    public void setIban(final String iban) {
        this.iban = iban;
    }

    public String getBic() {
        return bic;
    }

    public void setBic(final String bic) {
        this.bic = bic;
    }

    public String getSepaAccountHolder() {
        return sepaAccountHolder;
    }

    public void setSepaAccountHolder(final String sepaAccountHolder) {
        this.sepaAccountHolder = sepaAccountHolder;
    }

    @Override
    public Integer getPaymentProductId() {
        return SEPA_PAYMENT_ID;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("SepaDirectDebit{");
        sb.append("countryCode='").append(countryCode).append('\'');
        sb.append(", iban='").append(iban).append('\'');
        sb.append(", bic='").append(bic).append('\'');
        sb.append(", sepaAccountHolder='").append(sepaAccountHolder).append('\'');
        sb.append('}');
        return sb.toString();
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }

        final SepaDirectDebit that = (SepaDirectDebit) o;

        if (countryCode != null ? !countryCode.equals(that.countryCode) : that.countryCode != null) {
            return false;
        }
        if (iban != null ? !iban.equals(that.iban) : that.iban != null) {
            return false;
        }
        if (bic != null ? !bic.equals(that.bic) : that.bic != null) {
            return false;
        }
        return sepaAccountHolder != null ? sepaAccountHolder.equals(that.sepaAccountHolder) : that.sepaAccountHolder == null;

    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (countryCode != null ? countryCode.hashCode() : 0);
        result = 31 * result + (iban != null ? iban.hashCode() : 0);
        result = 31 * result + (bic != null ? bic.hashCode() : 0);
        result = 31 * result + (sepaAccountHolder != null ? sepaAccountHolder.hashCode() : 0);
        return result;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package erp.mtrn.data;

import erp.lib.SLibUtilities;
import java.util.ArrayList;

/**
 *
 * @author Irving Sánchez
 */
public class SGuiDps {
    private SDataDps moDataDpsSource;
    private ArrayList<SGuiDpsEntry> maGuiDpsSourceEntries;

    public SGuiDps(SDataDps dataDpsSource) {
        moDataDpsSource = dataDpsSource;
        maGuiDpsSourceEntries = new ArrayList<>();
    }

    public SDataDps getDataDpsSource() { return moDataDpsSource; }
    public ArrayList<SGuiDpsEntry> getGuiDpsSourceEntries() {  return maGuiDpsSourceEntries; }

    public SGuiDpsEntry	pickGuiDpsSourceEntry(int[] pkGuiDpsSourceEntry) {
        SGuiDpsEntry guiDpsEntry = null;
        for (SGuiDpsEntry guiEntry : maGuiDpsSourceEntries) {
            if (SLibUtilities.compareKeys((int[]) guiEntry.getDataDpsSourceEntry().getPrimaryKey(), pkGuiDpsSourceEntry)) {
                guiDpsEntry = guiEntry;
            }
        }

        return guiDpsEntry;
    }
}


text:
import logging
import json

import fixtures
import mock

import cinderclient.client
import cinderclient.v1.client
import cinderclient.v2.client
from cinderclient import exceptions
from cinderclient.tests.unit import utils
from keystoneclient import adapter
from keystoneclient import exceptions as keystone_exception

class ClientTest(utils.TestCase):

    def test_get_client_class_v1(self):
        output = cinderclient.client.get_client_class('1')
        self.assertEqual(cinderclient.v1.client.Client, output)

    def test_get_client_class_v2(self):
        output = cinderclient.client.get_client_class('2')
        self.assertEqual(cinderclient.v2.client.Client, output)

    def test_get_client_class_unknown(self):
        self.assertRaises(cinderclient.exceptions.UnsupportedVersion,
                          cinderclient.client.get_client_class, '0')

    def test_log_req(self):
        self.logger = self.useFixture(
            fixtures.FakeLogger(
                format="%(message)s",
                level=logging.DEBUG,
                nuke_handlers=True
            )
        )

        kwargs = {}
        kwargs['headers'] = {"X-Foo": "bar"}
        kwargs['data'] = ('{"auth": {"tenantName": "fakeService",'
                          ' "passwordCredentials": {"username": "fakeUser",'
                          ' "password": "fakePassword"}}}')

        cs = cinderclient.client.HTTPClient("user", None, None,
                                            "http://127.0.0.1:5000")
        cs.http_log_debug = True
        cs.http_log_req('PUT', kwargs)

        output = self.logger.output.split('\n')

        print("JSBRYANT: output is", output)

        self.assertNotIn("fakePassword", output[1])
        self.assertIn("fakeUser", output[1])

    def test_versions(self):
        v1_url = 'http://fakeurl/v1/tenants'
        v2_url = 'http://fakeurl/v2/tenants'
        unknown_url = 'http://fakeurl/v9/tenants'

        self.assertEqual('1',
                         cinderclient.client.get_volume_api_from_url(v1_url))
        self.assertEqual('2',
                         cinderclient.client.get_volume_api_from_url(v2_url))
        self.assertRaises(cinderclient.exceptions.UnsupportedVersion,
                          cinderclient.client.get_volume_api_from_url,
                          unknown_url)

    @mock.patch.object(adapter.Adapter, 'request')
    @mock.patch.object(exceptions, 'from_response')
    def test_sessionclient_request_method(
            self, mock_from_resp, mock_request):
        kwargs = {
            "body": {
                "volume": {
                    "status": "creating",
                    "imageRef": "username",
                    "attach_status": "detached"
                },
                "authenticated": "True"
            }
        }

        resp = {
            "text": {
                "volume": {
                    "status": "creating",
                    "id": "431253c0-e203-4da2-88df-60c756942aaf",
                    "size": 1
                }
            },
            "code": 202
        }

        mock_response = utils.TestResponse({
            "status_code": 202,
            "text": json.dumps(resp),
        })

        # 'request' method of Adaptor will return 202 response
        mock_request.return_value = mock_response
        session_client = cinderclient.client.SessionClient(session=mock.Mock())
        response, body = session_client.request(mock.sentinel.url,
                                                'POST', **kwargs)

        # In this case, from_response method will not get called
        # because response status_code is < 400
        self.assertEqual(202, response.status_code)
        self.assertFalse(mock_from_resp.called)

    @mock.patch.object(adapter.Adapter, 'request')
    def test_sessionclient_request_method_raises_badrequest(
            self, mock_request):
        kwargs = {
            "body": {
                "volume": {
                    "status": "creating",
                    "imageRef": "username",
                    "attach_status": "detached"
                },
                "authenticated": "True"
            }
        }

        resp = {
            "badRequest": {
                "message": "Invalid image identifier or unable to access "
                           "requested image.",
                "code": 400
            }
        }

        mock_response = utils.TestResponse({
            "status_code": 400,
            "text": json.dumps(resp),
        })

        # 'request' method of Adaptor will return 400 response
        mock_request.return_value = mock_response
        session_client = cinderclient.client.SessionClient(
            session=mock.Mock())

        # 'from_response' method will raise BadRequest because
        # resp.status_code is 400
        self.assertRaises(exceptions.BadRequest, session_client.request,
                          mock.sentinel.url, 'POST', **kwargs)

    @mock.patch.object(exceptions, 'from_response')
    def test_keystone_request_raises_auth_failure_exception(
            self, mock_from_resp):

        kwargs = {
            "body": {
                "volume": {
                    "status": "creating",
                    "imageRef": "username",
                    "attach_status": "detached"
                },
                "authenticated": "True"
            }
        }

        with mock.patch.object(adapter.Adapter, 'request',
                               side_effect=
                               keystone_exception.AuthorizationFailure()):
            session_client = cinderclient.client.SessionClient(
                session=mock.Mock())
            self.assertRaises(keystone_exception.AuthorizationFailure,
                              session_client.request,
                              mock.sentinel.url, 'POST', **kwargs)

        # As keystonesession.request method will raise
        # AuthorizationFailure exception, check exceptions.from_response
        # is not getting called.
        self.assertFalse(mock_from_resp.called)


text:
New Product

        <form class="form-horizontal" data-ng-submit="create()" novalidate>
            <fieldset>

                    Name

                        <input type="text" data-ng-model="name" id="name" class="form-control" placeholder="Name" required>

                    Category

                        <select data-ng-model="category" class="form-control" id="category" ng-options="item._id as item.name for item in categories" placeholder="Category" required></select>

                    Quantity Per Unit

                        <input type="text" data-ng-model="quantityPerUnit" id="quantityPerUnit" class="form-control" placeholder="Quantity Per Unit" required>

                    Unit Price

                        <input type="text" data-ng-model="unitPrice" id="unitPrice" class="form-control" placeholder="Unit Price" required>

                    Units in Stock

                        <input type="text" data-ng-model="unitsInStock" id="unitsInStock" class="form-control" placeholder="Units in Stock" required>

                    Units On Order

                        <input type="text" data-ng-model="unitsOnOrder" id="unitsOnOrder" class="form-control" placeholder="Units On Order" required>

                    Discontinued

                        <input type="checkbox" data-ng-model="discontinued" id="discontinued" class="form-control" placeholder="discontinued" required>

                    <input type="submit" class="btn btn-default">

            </fieldset>
        </form>